Programs & Examples On #Socketserver

Python module which simplifies the task of writing network servers.

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

I had to allow ..\python27\python.exe in windows firewall. I don't need to do this on WinXP or Win8.

Http post and get request in angular 6

For reading full response in Angular you should add the observe option:

{ observe: 'response' }
    return this.http.get(`${environment.serverUrl}/api/posts/${postId}/comments/?page=${page}&size=${size}`, { observe: 'response' });

Select first empty cell in column F starting from row 1. (without using offset )

I found this thread while trying to carry out a similar task. In the end, I used

Range("F:F").SpecialCells(xlBlanks).Areas(1)(1).Select

Which works fine as long as there is a blank cell in the intersection of the specified range and the used range of the worksheet.

The areas property is not needed to find the absolute first blank in the range, but is useful for finding subsequent non consecutive blanks.

What's the scope of a variable initialized in an if statement?

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.

(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)

Compiler error: memset was not declared in this scope

Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.

$ man memset

MEMSET(3)                BSD Library Functions Manual                MEMSET(3)

NAME
     memset -- fill a byte string with a byte value

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <string.h>

     void *
     memset(void *b, int c, size_t len);

Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>/<cstdio>/<cstdlib>/etc, rather than C's <string.h>/<stdio.h>/<stdlib.h>/etc.

How to select only the records with the highest date in LINQ

If you just want the last date for each account, you'd use this:

var q = from n in table
        group n by n.AccountId into g
        select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};

If you want the whole record:

var q = from n in table
        group n by n.AccountId into g
        select g.OrderByDescending(t=>t.Date).FirstOrDefault();

Make more than one chart in same IPython Notebook cell

Another way, for variety. Although this is somewhat less flexible than the others. Unfortunately, the graphs appear one above the other, rather than side-by-side, which you did request in your original question. But it is very concise.

df.plot(subplots=True)

If the dataframe has more than the two series, and you only want to plot those two, you'll need to replace df with df[['korisnika','osiguranika']].

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

Python error message io.UnsupportedOperation: not readable

You are opening the file as "w", which stands for writable.

Using "w" you won't be able to read the file. Use the following instead:

file = open("File.txt","r")

Additionally, here are the other options:

"r"   Opens a file for reading only.
"r+"  Opens a file for both reading and writing.
"rb"  Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w"   Opens a file for writing only.
"a"   Open for writing.  The file is created if it does not exist.
"a+"  Open for reading and writing.  The file is created if it does not exist.

Returning value that was passed into a method

The generic Returns<T> method can handle this situation nicely.

_mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);

Or if the method requires multiple inputs, specify them like so:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);

Find all elements with a certain attribute value in jquery

It's not called a tag; what you're looking for is called an html attribute.

$('div[imageId="imageN"]').each(function(i,el){
  $(el).html('changes');
  //do what ever you wish to this object :) 
});

What is the difference between == and equals() in Java?

public class StringPool {

public static void main(String[] args) {

    String s1 = "Cat";// will create reference in string pool of heap memory
    String s2 = "Cat";
    String s3 = new String("Cat");//will create a object in heap memory

    // Using == will give us true because same reference in string pool

    if (s1 == s2) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }

    // Using == with reference and Object will give us False

    if (s1 == s3) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }

    // Using .equals method which refers to value

    if (s1.equals(s3)) {
        System.out.println("true");
    } else {
        System.out.println("False");
    }

    }
  }

----Output----- true false true

Update label from another thread

Use MethodInvoker for updating label text in other thread.

private void AggiornaContatore()
{
    MethodInvoker inv = delegate 
    {
      this.lblCounter.Text = this.index.ToString(); 
    }

 this.Invoke(inv);
}

You are getting the error because your UI thread is holding the label, and since you are trying to update it through another thread you are getting cross thread exception.

You may also see: Threading in Windows Forms

Downloading folders from aws s3, cp or sync?

Using aws s3 cp from the AWS Command-Line Interface (CLI) will require the --recursive parameter to copy multiple files.

aws s3 cp s3://myBucket/dir localdir --recursive

The aws s3 sync command will, by default, copy a whole directory. It will only copy new/modified files.

aws s3 sync s3://mybucket/dir localdir

Just experiment to get the result you want.

Documentation:

How can I add a string to the end of each line in Vim?

...and to prepend (add the beginning of) each line with *,

%s/^/*/g

How to disable margin-collapsing?

For your information you could use grid but with side effects :)

.parent {
  display: grid
}

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

How to test if parameters exist in rails

In addition to previous answers: has_key? and has_value? have shorter alternatives in form of key? and value?. Ruby team also suggests using shorter alternatives, but for readability some might still prefer longer versions of these methods.

Therefore in your case it would be something like

if params.key?(:one) && params.key?(:two)
  ... do something ...
elsif params.key?(:one)
  ... do something ...
end

NB! .key? will just check if the key exists and ignores the whatever possible value. For ex:

2.3.3 :016 > a = {first: 1, second: nil, third: ''}
  => {:first=>1, :second=>nil, :third=>""}
2.3.3 :017 > puts "#{a.key?(:first)}, #{a.key?(:second)}, #{a.key?(:third), #{a.key?(:fourth)}}"
true, true, true, false

How to add extra whitespace in PHP?

for adding space character you can use

<? 
echo "\x20\x20\x20"; 
 ?>

How do I change TextView Value inside Java Code?

I presume that this question is a continuation of this one.

What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:

<TextView  
android:id="@+id/rate"
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/rate"
/>

The string "@string/rate" refers to an entry in your strings.xml file that looks like this:

<string name="rate">Rate</string>

If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:


final TextView textViewToChange = (TextView) findViewById(R.id.rate);
textViewToChange.setText(
    "The new text that I'd like to display now that the user has pushed a button.");

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
{
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
        {
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()
        }
    );

Test code:

foreach(var item in newList)
{
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
    {
        Console.WriteLine("\t Name: {0}", child.Name);
    }
}

Result:

School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

whitespaces in the path of windows filepath

Try putting double quotes in your filepath variable

"\"E:/ABC/SEM 2/testfiles/all.txt\""

Check the permissions of the file or in any case consider renaming the folder to remove the space

How do you reverse a string in place in C or C++?

In the interest of completeness, it should be pointed out that there are representations of strings on various platforms in which the number of bytes per character varies depending on the character. Old-school programmers would refer to this as DBCS (Double Byte Character Set). Modern programmers more commonly encounter this in UTF-8 (as well as UTF-16 and others). There are other such encodings as well.

In any of these variable-width encoding schemes, the simple algorithms posted here (evil, non-evil or otherwise) would not work correctly at all! In fact, they could even cause the string to become illegible or even an illegal string in that encoding scheme. See Juan Pablo Califano's answer for some good examples.

std::reverse() potentially would still work in this case, as long as your platform's implementation of the Standard C++ Library (in particular, string iterators) properly took this into account.

How to pass multiple values to single parameter in stored procedure

I spent time finding a proper way. This may be useful for others.

Create a UDF and refer in the query -

http://www.geekzilla.co.uk/view5C09B52C-4600-4B66-9DD7-DCE840D64CBD.htm

Python: Figure out local timezone

Based on Thoku's answer above, here's an answer that resolves the time zone to the nearest half hour (which is relevant for some timezones eg South Australia's) :

from datetime import datetime
round((round((datetime.now()-datetime.utcnow()).total_seconds())/1800)/2)

git rebase merge conflict

Note: with Git 2.14.x/2.15 (Q3 2017), the git rebase message in case of conflicts will be clearer.

See commit 5fdacc1 (16 Jul 2017) by William Duclot (williamdclt).
(Merged by Junio C Hamano -- gitster -- in commit 076eeec, 11 Aug 2017)

rebase: make resolve message clearer for inexperienced users

Before:

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort"

After:

Resolve all conflicts manually, 
mark them as resolved with git add/rm <conflicted_files>
then run "git rebase --continue".

You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".')

The git UI can be improved by addressing the error messages to those they help: inexperienced and casual git users.
To this intent, it is helpful to make sure the terms used in those messages can be understood by this segment of users, and that they guide them to resolve the problem.

In particular, failure to apply a patch during a git rebase is a common problem that can be very destabilizing for the inexperienced user.
It is important to lead them toward the resolution of the conflict (which is a 3-steps process, thus complex) and reassure them that they can escape a situation they can't handle with "--abort".
This commit answer those two points by detailing the resolution process and by avoiding cryptic git linguo.

Jquery $(this) Child Selector

In the click event "this" is the a tag that was clicked

jQuery('.class1 a').click( function() {
   var divToSlide = $(this).parent().find(".class2");
   if (divToSlide.is(":hidden")) {
      divToSlide.slideDown("slow");
   } else {
      divToSlide.slideUp();
   }
});

There's multiple ways to get to the div though you could also use .siblings, .next etc

How do you pass a function as a parameter in C?

I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function. Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.

Compare Function

bool compare(int a, int b) {
    return a > b;
}

Now , the Bubble sort that takes another function as its parameter to perform comparison

Bubble sort function

void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {

    for (int i = 0;i < n - 1;i++) {
        for (int j = 0;j < (n - 1 - i);j++) {
            
            if (cmp(arr[j], arr[j + 1])) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.

int main()
{
    int i, n = 10, key = 11;
    int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };

    bubble_sort(arr, n, compare);
    cout<<"Sorted Order"<<endl;
    for (int i = 0;i < n;i++) {
        cout << arr[i] << " ";
    }
}

Output:

Sorted Order
3 6 8 11 12 12 15 18 20 22

Optimal way to concatenate/aggregate strings

Although @serge answer is correct but i compared time consumption of his way against xmlpath and i found the xmlpath is so faster. I'll write the compare code and you can check it by yourself. This is @serge way:

DECLARE @startTime datetime2;
DECLARE @endTime datetime2;
DECLARE @counter INT;
SET @counter = 1;

set nocount on;

declare @YourTable table (ID int, Name nvarchar(50))

WHILE @counter < 1000
BEGIN
    insert into @YourTable VALUES (ROUND(@counter/10,0), CONVERT(NVARCHAR(50), @counter) + 'CC')
    SET @counter = @counter + 1;
END

SET @startTime = GETDATE()

;WITH Partitioned AS
(
    SELECT 
        ID,
        Name,
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Name) AS NameNumber,
        COUNT(*) OVER (PARTITION BY ID) AS NameCount
    FROM @YourTable
),
Concatenated AS
(
    SELECT ID, CAST(Name AS nvarchar) AS FullName, Name, NameNumber, NameCount FROM Partitioned WHERE NameNumber = 1

    UNION ALL

    SELECT 
        P.ID, CAST(C.FullName + ', ' + P.Name AS nvarchar), P.Name, P.NameNumber, P.NameCount
    FROM Partitioned AS P
        INNER JOIN Concatenated AS C ON P.ID = C.ID AND P.NameNumber = C.NameNumber + 1
)
SELECT 
    ID,
    FullName
FROM Concatenated
WHERE NameNumber = NameCount

SET @endTime = GETDATE();

SELECT DATEDIFF(millisecond,@startTime, @endTime)
--Take about 54 milliseconds

And this is xmlpath way:

DECLARE @startTime datetime2;
DECLARE @endTime datetime2;
DECLARE @counter INT;
SET @counter = 1;

set nocount on;

declare @YourTable table (RowID int, HeaderValue int, ChildValue varchar(5))

WHILE @counter < 1000
BEGIN
    insert into @YourTable VALUES (@counter, ROUND(@counter/10,0), CONVERT(NVARCHAR(50), @counter) + 'CC')
    SET @counter = @counter + 1;
END

SET @startTime = GETDATE();

set nocount off
SELECT
    t1.HeaderValue
        ,STUFF(
                   (SELECT
                        ', ' + t2.ChildValue
                        FROM @YourTable t2
                        WHERE t1.HeaderValue=t2.HeaderValue
                        ORDER BY t2.ChildValue
                        FOR XML PATH(''), TYPE
                   ).value('.','varchar(max)')
                   ,1,2, ''
              ) AS ChildValues
    FROM @YourTable t1
    GROUP BY t1.HeaderValue

SET @endTime = GETDATE();

SELECT DATEDIFF(millisecond,@startTime, @endTime)
--Take about 4 milliseconds

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

Get the data received in a Flask request

To get JSON posted without the application/json content type, use request.get_json(force=True).

@app.route('/process_data', methods=['POST'])
def process_data():
    req_data = request.get_json(force=True)
    language = req_data['language']
    return 'The language value is: {}'.format(language)

Find nginx version?

In my case, I try to add sudo

sudo nginx -v

enter image description here

jQuery not working with IE 11

As Arnaud suggested in a comment to the original post, you should put this in your html header:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

I don't want any cred for this. I just want to make it more visible for anyone else that come here.

Java - get pixel array from image

I found Mota's answer gave me a 10 times speed increase - so thanks Mota.

I've wrapped up the code in a convenient class which takes the BufferedImage in the constructor and exposes an equivalent getRBG(x,y) method which makes it a drop in replacement for code using BufferedImage.getRGB(x,y)

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

public class FastRGB
{

    private int width;
    private int height;
    private boolean hasAlphaChannel;
    private int pixelLength;
    private byte[] pixels;

    FastRGB(BufferedImage image)
    {

        pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        width = image.getWidth();
        height = image.getHeight();
        hasAlphaChannel = image.getAlphaRaster() != null;
        pixelLength = 3;
        if (hasAlphaChannel)
        {
            pixelLength = 4;
        }

    }

    int getRGB(int x, int y)
    {
        int pos = (y * pixelLength * width) + (x * pixelLength);

        int argb = -16777216; // 255 alpha
        if (hasAlphaChannel)
        {
            argb = (((int) pixels[pos++] & 0xff) << 24); // alpha
        }

        argb += ((int) pixels[pos++] & 0xff); // blue
        argb += (((int) pixels[pos++] & 0xff) << 8); // green
        argb += (((int) pixels[pos++] & 0xff) << 16); // red
        return argb;
    }
}

Execute JavaScript using Selenium WebDriver in C#

The shortest code

ChromeDriver drv = new ChromeDriver();

drv.Navigate().GoToUrl("https://stackoverflow.com/questions/6229769/execute-javascript-using-selenium-webdriver-in-c-sharp");

drv.ExecuteScript("return alert(document.title);");


Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

UnicodeDecodeError, invalid continuation byte

This happened to me also, while i was reading text containing Hebrew from a .txt file.

I clicked: file -> save as and I saved this file as a UTF-8 encoding

Multiline for WPF TextBox

Here is a sample XAML that will allow TextBox to accept multiline text and it uses its own scrollbars:

<TextBox
Height="200"
Width="500"
TextWrapping="Wrap"
AcceptsReturn="True"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto"/>

Adding/removing items from a JavaScript object with jQuery

Adding an object in a json array

var arrList = [];
var arr = {};   
arr['worker_id'] = worker_id;
arr['worker_nm'] = worker_nm;
arrList.push(arr);

Removing an object from a json

It worker for me.

  arrList = $.grep(arrList, function (e) { 

        if(e.worker_id == worker_id) {
            return false;
        } else {
            return true;
        }
    });

It returns an array without that object.

Hope it helps.

Building a fat jar using maven

Note: If you are a spring-boot application, read the end of answer

Add following plugin to your pom.xml The latest version can be found at

...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>CHOOSE LATEST VERSION HERE</version>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
            <executions>
                <execution>
                    <id>assemble-all</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
...

After configuring this plug-in, running mvn package will produce two jars: one containing just the project classes, and a second fat jar with all dependencies with the suffix "-jar-with-dependencies".

if you want correct classpath setup at runtime then also add following plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>fully.qualified.MainClass</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>

For spring boot application use just following plugin (choose appropriate version of it)

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <fork>true</fork>
        <mainClass>${start-class}</mainClass>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

FPDF utf-8 encoding (HOW-TO)

There also is a official UTF-8 Version of FPDF called tFPDF http://www.fpdf.org/en/script/script92.php

You can easyly switch from the original FPDF, just make sure you also use a unicode Font as shown in the example in the above link or my code:

<?php

//this is a UTF-8 file, we won't need any encode/decode/iconv workarounds

//define the path to the .ttf files you want to use
define('FPDF_FONTPATH',"../fonts/");
require('tfpdf.php');

$pdf = new tFPDF();
$pdf->AddPage();

// Add Unicode fonts (.ttf files)
$fontName = 'Helvetica';
$pdf->AddFont($fontName,'','HelveticaNeue LightCond.ttf',true);
$pdf->AddFont($fontName,'B','HelveticaNeue MediumCond.ttf',true);

//now use the Unicode font in bold
$pdf->SetFont($fontName,'B',12);

//anything else is identical to the old FPDF, just use Write(),Cell(),MultiCell()... 
//without any encoding trouble
$pdf->Cell(100,20, "Some UTF-8 String");

//...
?>

I think its much more elegant to use this instead of spaming utf8_decode() everywhere and the ability to use .ttf files directly in AddFont() is an upside too.

Any other answer here is just a way to avoid or work around the problem, and avoiding UTF-8 is no real option for an up to date project.

There are also alternatives like mPDF or TCPDF (and others) wich base on FPDF but offer advanced functions, have UTF-8 Support and can interpret HTML Code (limited of course as there is no direct way to convert HTML to PDF). Most of the FPDF code can be used directly in those librarys, so its pretty easy to migrate the code.

https://github.com/mpdf/mpdf http://www.tcpdf.org/

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

how to use concatenate a fixed string and a variable in Python

I'm guessing that you meant to do this:

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in python, use       ^ 

how to use List<WebElement> webdriver

Try the following code:

//...
By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
List<WebElement> myElements = driver.findElements(mySelector);
for(WebElement e : myElements) {
  System.out.println(e.getText());
}

It will returns with the whole content of the <li> tags, like:

<a class="extra">Vše</a> (950)</li>

But you can easily get the number now from it, for example by using split() and/or substring().

PHP reindex array?

$myarray = array_values($myarray);

array_values

Which TensorFlow and CUDA version combinations are compatible?

TL;DR) See this table: https://www.tensorflow.org/install/source#gpu

Generally:

Check the CUDA version:

cat /usr/local/cuda/version.txt

and cuDNN version:

grep CUDNN_MAJOR -A 2 /usr/local/cuda/include/cudnn.h

and install a combination as given below in the images or here.

The following images and the link provide an overview of the officially supported/tested combinations of CUDA and TensorFlow on Linux, macOS and Windows:

Minor configurations:

Since the given specifications below in some cases might be too broad, here is one specific configuration that works:

  • tensorflow-gpu==1.12.0
  • cuda==9.0
  • cuDNN==7.1.4

The corresponding cudnn can be downloaded here.

Tested build configurations

Please refer to https://www.tensorflow.org/install/source#gpu for a up-to-date compatibility chart (for official TF wheels).

(figures updated May 20, 2020)

Linux GPU

enter image description here

Linux CPU

enter image description here

macOS GPU

enter image description here

macOS CPU

enter image description here

Windows GPU

enter image description here

Windows CPU

enter image description here

Updated as of Dec 5 2020: For the updated information please refer Link for Linux and Link for Windows.

Inserting a string into a list without getting split into characters

best put brackets around foo, and use +=

list+=['foo']

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

This is with reference to the original question
$('select').val(['a','c']);
$('select').trigger('change');

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

Is so simple,only add your java path for example:

C:\Program Files\Java\jdk1.8.0_121\bin

in PATH system variable

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

Understanding the Gemfile.lock file

It seems no clear document talking on the Gemfile.lock format. Maybe it's because Gemfile.lock is just used by bundle internally.

However, since Gemfile.lock is a snapshot of Gemfile, which means all its information should come from Gemfile (or from default value if not specified in Gemfile).

For GEM, it lists all the dependencies you introduce directly or indirectly in the Gemfile. remote under GEM tells where to get the gems, which is specified by source in Gemfile.

If a gem is not fetch from remote, PATH tells the location to find it. PATH's info comes from path in Gemfile when you declare a dependency.

And PLATFORM is from here.

For DEPENDENCIES, it's the snapshot of dependencies resolved by bundle.

how to set start page in webconfig file in asp.net c#

You can achieve it by code also, In you Global.asax file in Session_Start event write response.redirect to your start page like following.

void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

            Response.Redirect("~/Index.aspx");

        }

You can get redirect page name from database or any other storage to change the application start page while application is running no need to edit web.config or change any IIS settings

How to change font of UIButton with Swift

Example: button.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 12)

  • If you want to use defaul font from it's own family, use for example: "HelveticaNeue"
  • If you want to specify family font, use for example: "HelveticaNeue-Bold"

Open existing file, append a single line

//display sample reg form in notepad.txt
using (StreamWriter stream = new FileInfo("D:\\tt.txt").AppendText())//ur file location//.AppendText())
{
   stream.WriteLine("Name :" + textBox1.Text);//display textbox data in notepad
   stream.WriteLine("DOB : " + dateTimePicker1.Text);//display datepicker data in notepad
   stream.WriteLine("DEP:" + comboBox1.SelectedItem.ToString());
   stream.WriteLine("EXM :" + listBox1.SelectedItem.ToString());
}

How to read data when some numbers contain commas as thousand separator?

A very convenient way is readr::read_delim-family. Taking the example from here: Importing csv with multiple separators into R you can do it as follows:

txt <- 'OBJECTID,District_N,ZONE_CODE,COUNT,AREA,SUM
1,Bagamoyo,1,"136,227","8,514,187,500.000000000000000","352,678.813105723350000"
2,Bariadi,2,"88,350","5,521,875,000.000000000000000","526,307.288878142830000"
3,Chunya,3,"483,059","30,191,187,500.000000000000000","352,444.699742995200000"'

require(readr)
read_csv(txt) # = read_delim(txt, delim = ",")

Which results in the expected result:

# A tibble: 3 × 6
  OBJECTID District_N ZONE_CODE  COUNT        AREA      SUM
     <int>      <chr>     <int>  <dbl>       <dbl>    <dbl>
1        1   Bagamoyo         1 136227  8514187500 352678.8
2        2    Bariadi         2  88350  5521875000 526307.3
3        3     Chunya         3 483059 30191187500 352444.7

Listing information about all database files in SQL Server

Executing following sql (It will only work when you don't have multiple mdf/ldf files for same database)

SELECT
    db.name AS DBName,
    (select mf.Physical_Name FROM sys.master_files mf where mf.type_desc = 'ROWS' and db.database_id = mf.database_id ) as DataFile,
    (select mf.Physical_Name FROM sys.master_files mf where mf.type_desc = 'LOG' and db.database_id = mf.database_id ) as LogFile
FROM sys.databases db

will return this output

DBName       DataFile                     LogFile
--------------------------------------------------------------------------------
master       C:\....\master.mdf           C:\....\mastlog.ldf
tempdb       C:\....\tempdb.mdf           C:\....\templog.ldf
model        C:\....\model.mdf            C:\....\modellog.ldf

and rest of the databases

If your TempDB's have multiple MDF's (like mine have), this script will fail. However, you can use

WHERE db.database_id > 4

at the end and it will return all databases except system databases.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

auto run a bat script in windows 7 at login

I hit this question looking for how to run batch scripts during user logon on a standalone windows server (workgroup not in domain). I found the answer in using group policy.

  1. gpedit.msc
  2. user configuration->administrative templates->system->logon->run these programs at user logon
  3. add batch scripts.
  4. you can add them using cmd /k mybatchfile.cmd if you want the command window to stay (on desktop) after batch script have finished.
  5. gpupdate - to update the group policy.

How to delete all records from table in sqlite with Android?

SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DELETE FROM tablename"); //delete all rows in a table
db.close();

this work for me :)

Why write <script type="text/javascript"> when the mime type is set by the server?

Boris Zbarsky (Mozilla), who probably knows more about the innards of Gecko than anyone else, provided at http://lists.w3.org/Archives/Public/public-html/2009Apr/0195.html the pseudocode repeated below to describe what Gecko based browsers do:

if (@type not set or empty) {
   if (@language not set or empty) {
     // Treat as default script language; what this is depends on the
     // content-script-type HTTP header or equivalent META tag
   } else {
     if (@language is one of "javascript", "livescript", "mocha",
                             "javascript1.0", "javascript1.1",
                             "javascript1.2", "javascript1.3",
                             "javascript1.4", "javascript1.5",
                             "javascript1.6", "javascript1.7",
                             "javascript1.8") {
       // Treat as javascript
     } else {
       // Treat as unknown script language; do not execute
     }
   }
} else {
   if (@type is one of "text/javascript", "text/ecmascript",
                       "application/javascript",
                       "application/ecmascript",
                       "application/x-javascript") {
     // Treat as javascript
   } else {
     // Treat as specified (e.g. if pyxpcom is installed and
     // python script is allowed in this context and the type
     // is one that the python runtime claims to handle, use that).
     // If we don't have a runtime for this type, do not execute.
   }
}

How to get the range of occupied cells in excel sheet

dim lastRow as long   'in VBA it's a long 
lastrow = wks.range("A65000").end(xlup).row

tsconfig.json: Build:No inputs were found in config file

When using Visual Studio Code, building the project (i.e. pressing Ctrl + Shift + B), moves your .ts file into the .vscode folder (I don't know why it does this), then generates the TS18003 error. What I did was move my .ts file out of the .vscode folder, back into the root folder and build the project again.

The project built successfully!

SQL DELETE with INNER JOIN

if the database is InnoDB you dont need to do joins in deletion. only

DELETE FROM spawnlist WHERE spawnlist.type = "monster";

can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.

CREATE TABLE IF NOT EXIST spawnlist (
  npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY

)ENGINE=InnoDB;

CREATE TABLE IF NOT EXIST npc (
  idTemplate VARCHAR(20) NOT NULL,

  FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE

)ENGINE=InnoDB;

if you uses MyISAM you can delete records joining like this

DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';

in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.

Writing Unicode text to a text file?

How to print unicode characters into a file:

Save this to file: foo.py:

#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys 
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')

Run it and pipe output to file:

python foo.py > tmp.txt

Open tmp.txt and look inside, you see this:

el@apollo:~$ cat tmp.txt 
e with obfuscation: é

Thus you have saved unicode e with a obfuscation mark on it to a file.

How to import JsonConvert in C# application?

JsonConvert is from the namespace Newtonsoft.Json, not System.ServiceModel.Web

Use NuGet to download the package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

Boxplot show the value of mean

You can also use a function within stat_summary to calculate the mean and the hjust argument to place the text, you need a additional function but no additional data frame:

fun_mean <- function(x){
  return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}


ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)

enter image description here

adding css file with jquery

Just my couple cents... sometimes it's good to be sure there are no any duplicates... so we have the next function in the utils library:

jQuery.loadCSS = function(url) {
    if (!$('link[href="' + url + '"]').length)
        $('head').append('<link rel="stylesheet" type="text/css" href="' + url + '">');
}

How to use:

$.loadCSS('css/style2.css');

Facebook Javascript SDK Problem: "FB is not defined"

Use a setTimeout, because sometimes the FB.init takes some time to get declared

function testAPI() {
     console.log('Welcome!  Fetching your information.... ');
     FB.api('/me', function(response) {
         console.log('Good to see you, ' + response.name + '.');
     });
}
function login() {
    FB.login(function(response) {
        if (response.authResponse) {
            testAPI();
        } else {
            // cancelled
        }
    });
}
setTimeout(function() {
    login();
},2000);

Bootstrap 3 Collapse show state with Chevron icon

Thanks to biggates and steakpi. As answer of question Dreamonic, I made a little changes to make all headers clickable (not only title string and gluphs) and took off underline from link. To force an icons appear on same line I added h4 at the end of CSS instructions. Here is the modified code:

<div class="panel-group" id="accordion">
  <div class="panel panel-default">
    <div class="panel-heading">      
        <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
          <h4 class="panel-title">Collapsible Group Item #1</h4>
        </a>      
    </div>
    <div id="collapseOne" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">      
        <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
          <h4 class="panel-title">Collapsible Group Item #2</h4>
        </a>      
    </div>
    <div id="collapseTwo" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">      
        <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
          <h4 class="panel-title">Collapsible Group Item #3</h4>
        </a>      
    </div>
    <div id="collapseThree" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>

And the modified CSS:

.panel-heading .accordion-toggle h4:after {
    /* symbol for "opening" panels */
    font-family: 'Glyphicons Halflings';  
    content: "\e114";    
    float: right;        
    color: grey;        
    overflow: no-display;
}
.panel-heading .accordion-toggle.collapsed h4:after {
    /* symbol for "collapsed" panels */
    content: "\e080";    
}
a.accordion-toggle{
    text-decoration: none;
}

What is the difference between IQueryable<T> and IEnumerable<T>?

First of all, IQueryable<T> extends the IEnumerable<T> interface, so anything you can do with a "plain" IEnumerable<T>, you can also do with an IQueryable<T>.

IEnumerable<T> just has a GetEnumerator() method that returns an Enumerator<T> for which you can call its MoveNext() method to iterate through a sequence of T.

What IQueryable<T> has that IEnumerable<T> doesn't are two properties in particular—one that points to a query provider (e.g., a LINQ to SQL provider) and another one pointing to a query expression representing the IQueryable<T> object as a runtime-traversable abstract syntax tree that can be understood by the given query provider (for the most part, you can't give a LINQ to SQL expression to a LINQ to Entities provider without an exception being thrown).

The expression can simply be a constant expression of the object itself or a more complex tree of a composed set of query operators and operands. The query provider's IQueryProvider.Execute() or IQueryProvider.CreateQuery() methods are called with an Expression passed to it, and then either a query result or another IQueryable is returned, respectively.

Truncating all tables in a Postgres database

Explicit cursors are rarely needed in plpgsql. Use the simpler and faster implicit cursor of a FOR loop:

Note: Since table names are not unique per database, you have to schema-qualify table names to be sure. Also, I limit the function to the default schema 'public'. Adapt to your needs, but be sure to exclude the system schemas pg_* and information_schema.

Be very careful with these functions. They nuke your database. I added a child safety device. Comment the RAISE NOTICE line and uncomment EXECUTE to prime the bomb ...

CREATE OR REPLACE FUNCTION f_truncate_tables(_username text)
  RETURNS void AS
$func$
DECLARE
   _tbl text;
   _sch text;
BEGIN
   FOR _sch, _tbl IN 
      SELECT schemaname, tablename
      FROM   pg_tables
      WHERE  tableowner = _username
      AND  
      -- dangerous, test before you execute!
      RAISE NOTICE '%',  -- once confident, comment this line ...
      -- EXECUTE         -- ... and uncomment this one
         format('TRUNCATE TABLE %I.%I CASCADE', _sch, _tbl);
   END LOOP;
END
$func$ LANGUAGE plpgsql;

format() requires Postgres 9.1 or later. In older versions concatenate the query string like this:

'TRUNCATE TABLE ' || quote_ident(_sch) || '.' || quote_ident(_tbl)  || ' CASCADE';

Single command, no loop

Since we can TRUNCATE multiple tables at once we don't need any cursor or loop at all:

Aggregate all table names and execute a single statement. Simpler, faster:

CREATE OR REPLACE FUNCTION f_truncate_tables(_username text)
  RETURNS void AS
$func$
BEGIN
   -- dangerous, test before you execute!
   RAISE NOTICE '%',  -- once confident, comment this line ...
   -- EXECUTE         -- ... and uncomment this one
  (SELECT 'TRUNCATE TABLE '
       || string_agg(format('%I.%I', schemaname, tablename), ', ')
       || ' CASCADE'
   FROM   pg_tables
   WHERE  tableowner = _username
   AND    schemaname = 'public'
   );
END
$func$ LANGUAGE plpgsql;

Call:

SELECT truncate_tables('postgres');

Refined query

You don't even need a function. In Postgres 9.0+ you can execute dynamic commands in a DO statement. And in Postgres 9.5+ the syntax can be even simpler:

DO
$func$
BEGIN
   -- dangerous, test before you execute!
   RAISE NOTICE '%',  -- once confident, comment this line ...
   -- EXECUTE         -- ... and uncomment this one
   (SELECT 'TRUNCATE TABLE ' || string_agg(oid::regclass::text, ', ') || ' CASCADE'
    FROM   pg_class
    WHERE  relkind = 'r'  -- only tables
    AND    relnamespace = 'public'::regnamespace
   );
END
$func$;

About the difference between pg_class, pg_tables and information_schema.tables:

About regclass and quoted table names:

For repeated use

Create a "template" database (let's name it my_template) with your vanilla structure and all empty tables. Then go through a DROP / CREATE DATABASE cycle:

DROP DATABASE mydb;
CREATE DATABASE mydb TEMPLATE my_template;

This is extremely fast, because Postgres copies the whole structure on the file level. No concurrency issues or other overhead slowing you down.

If concurrent connections keep you from dropping the DB, consider:

Assigning default values to shell variables with a single command in bash

Then there's the way of expressing your 'if' construct more tersely:

FOO='default'
[ -n "${VARIABLE}" ] && FOO=${VARIABLE}

PL/SQL block problem: No data found error

This data not found causes because of some datatype we are using .

like select empid into v_test

above empid and v_test has to be number type , then only the data will be stored .

So keep track of the data type , when getting this error , may be this will help

slideToggle JQuery right to left

Try this:

$(this).hide("slide", { direction: "left" }, 1000);

$(this).show("slide", { direction: "left" }, 1000);

What does on_delete do on Django models?

FYI, the on_delete parameter in models is backwards from what it sounds like. You put on_delete on a foreign key (FK) on a model to tell Django what to do if the FK entry that you are pointing to on your record is deleted. The options our shop have used the most are PROTECT, CASCADE, and SET_NULL. Here are the basic rules I have figured out:

  1. Use PROTECT when your FK is pointing to a look-up table that really shouldn't be changing and that certainly should not cause your table to change. If anyone tries to delete an entry on that look-up table, PROTECT prevents them from deleting it if it is tied to any records. It also prevents Django from deleting your record just because it deleted an entry on a look-up table. This last part is critical. If someone were to delete the gender "Female" from my Gender table, I CERTAINLY would NOT want that to instantly delete any and all people I had in my Person table who had that gender.
  2. Use CASCADE when your FK is pointing to a "parent" record. So, if a Person can have many PersonEthnicity entries (he/she can be American Indian, Black, and White), and that Person is deleted, I really would want any "child" PersonEthnicity entries to be deleted. They are irrelevant without the Person.
  3. Use SET_NULL when you do want people to be allowed to delete an entry on a look-up table, but you still want to preserve your record. For example, if a Person can have a HighSchool, but it doesn't really matter to me if that high-school goes away on my look-up table, I would say on_delete=SET_NULL. This would leave my Person record out there; it just would just set the high-school FK on my Person to null. Obviously, you will have to allow null=True on that FK.

Here is an example of a model that does all three things:

class PurchPurchaseAccount(models.Model):
    id = models.AutoField(primary_key=True)
    purchase = models.ForeignKey(PurchPurchase, null=True, db_column='purchase', blank=True, on_delete=models.CASCADE) # If "parent" rec gone, delete "child" rec!!!
    paid_from_acct = models.ForeignKey(PurchPaidFromAcct, null=True, db_column='paid_from_acct', blank=True, on_delete=models.PROTECT) # Disallow lookup deletion & do not delete this rec.
    _updated = models.DateTimeField()
    _updatedby = models.ForeignKey(Person, null=True, db_column='_updatedby', blank=True, related_name='acctupdated_by', on_delete=models.SET_NULL) # Person records shouldn't be deleted, but if they are, preserve this PurchPurchaseAccount entry, and just set this person to null.

    def __unicode__(self):
        return str(self.paid_from_acct.display)
    class Meta:
        db_table = u'purch_purchase_account'

As a last tidbit, did you know that if you don't specify on_delete (or didn't), the default behavior is CASCADE? This means that if someone deleted a gender entry on your Gender table, any Person records with that gender were also deleted!

I would say, "If in doubt, set on_delete=models.PROTECT." Then go test your application. You will quickly figure out which FKs should be labeled the other values without endangering any of your data.

Also, it is worth noting that on_delete=CASCADE is actually not added to any of your migrations, if that is the behavior you are selecting. I guess this is because it is the default, so putting on_delete=CASCADE is the same thing as putting nothing.

How to get status code from webclient?

Erik's answer doesn't work on Windows Phone as is. The following does:

class WebClientEx : WebClient
{
    private WebResponse m_Resp = null;

    protected override WebResponse GetWebResponse(WebRequest Req, IAsyncResult ar)
    {
        try
        {
            this.m_Resp = base.GetWebResponse(request);
        }
        catch (WebException ex)
        {
            if (this.m_Resp == null)
                this.m_Resp = ex.Response;
        }
        return this.m_Resp;
    }

    public HttpStatusCode StatusCode
    {
        get
        {
            if (m_Resp != null && m_Resp is HttpWebResponse)
                return (m_Resp as HttpWebResponse).StatusCode;
            else
                return HttpStatusCode.OK;
        }
    }
}

At least it does when using OpenReadAsync; for other xxxAsync methods, careful testing would be highly recommended. The framework calls GetWebResponse somewhere along the code path; all one needs to do is capture and cache the response object.

The fallback code is 200 in this snippet because genuine HTTP errors - 500, 404, etc - are reported as exceptions anyway. The purpose of this trick is to capture non-error codes, in my specific case 304 (Not modified). So the fallback assumes that if the status code is somehow unavailable, at least it's a non-erroneous one.

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

for-in statement

TypeScript isn't giving you a gun to shoot yourself in the foot with.

The iterator variable is a string because it is a string, full stop. Observe:

var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';

for(var key in obj) {
    console.log('Type: ' + typeof key);
    console.log(key + ' => ' + obj[key]);
}

How many key/value pairs are in obj now? 6, more or less? No, 3, and all of the keys are strings:

Type: string
0 => zero point zero
Type: string
[object Object] => this obj; 
Type: string
undefined => the literal string "undefined" 

Why isn't .ico file defined when setting window's icon?

I had the same problem too, but I found a solution.

root.mainloop()

from tkinter import *
    
# must add
root = Tk()
root.title("Calculator")
root.iconbitmap(r"image/icon.ico")
    
root.mainloop()

In the example, what python needed is an icon file, so when you dowload an icon as .png it won't work cause it needs an .ico file. So you need to find converters to convert your icon from png to ico.

Breaking to a new line with inline-block?

I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.

.text span {
       background:rgba(165, 220, 79, 0.8);
       float: left;
       clear: left;
       padding:7px 10px;
       color:white;
    }

Note:Remove <br/>'s before using this off course.

Join a list of items with different types as string in Python

For example:

lst_points = [[313, 262, 470, 482], [551, 254, 697, 449]]

lst_s_points = [" ".join(map(str, lst)) for lst in lst_points]
print lst_s_points
# ['313 262 470 482', '551 254 697 449']

As to me, I want to add a str before each str list:

# here o means class, other four points means coordinate
print ['0 ' + " ".join(map(str, lst)) for lst in lst_points]
# ['0 313 262 470 482', '0 551 254 697 449']

Or single list:

lst = [313, 262, 470, 482]
lst_str = [str(i) for i in lst]
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482

lst_str = map(str, lst)
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482

How to tell if browser/tab is active

All of the examples here (with the exception of rockacola's) require that the user physically click on the window to define focus. This isn't ideal, so .hover() is the better choice:

$(window).hover(function(event) {
    if (event.fromElement) {
        console.log("inactive");
    } else {
        console.log("active");
    }
});

This'll tell you when the user has their mouse on the screen, though it still won't tell you if it's in the foreground with the user's mouse elsewhere.

How to download files using axios

It's very simple javascript code to trigger a download for the user:

window.open("<insert URL here>")

You don't want/need axios for this operation; it should be standard to just let the browser do it's thing.

Note: If you need authorisation for the download then this might not work. I'm pretty sure you can use cookies to authorise a request like this, provided it's within the same domain, but regardless, this might not work immediately in such a case.


As for whether it's possible... not with the in-built file downloading mechanism, no.

SQL Server: Make all UPPER case to Proper Case/Title Case

Is it too late to go back and get the un-uppercased data?

The von Neumann's, McCain's, DeGuzman's, and the Johnson-Smith's of your client base may not like the result of your processing...

Also, I'm guessing that this is intended to be a one-time upgrade of the data? It might be easier to export, filter/modify, and re-import the corrected names into the db, and then you can use non-SQL approaches to name fixing...

What does "subject" mean in certificate?

The subject of the certificate is the entity its public key is associated with (i.e. the "owner" of the certificate).

As RFC 5280 says:

The subject field identifies the entity associated with the public key stored in the subject public key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.

X.509 certificates have a Subject (Distinguished Name) field and can also have multiple names in the Subject Alternative Name extension.

The Subject DN is made of multiple relative distinguished names (RDNs) (themselves made of attribute assertion values) such as "CN=yourname" or "O=yourorganization".

In the context of the article you're linking to, the subject would be the user/owner of the cert.

How to Resize image in Swift?

For Swift 4 I would just make an extension on UIImage with referencing to self.

import UIKit
extension UIImage {
  func resizeImage(targetSize: CGSize) -> UIImage {
    let size = self.size
    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / size.height
    let newSize = widthRatio > heightRatio ?  CGSize(width: size.width * heightRatio, height: size.height * heightRatio) : CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    self.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
  }
}

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

If you can live without tools.jar and it's only included as a chained dependency, you can exclude it from the offending project:

<dependency>
    <groupId>org.apache.ambari</groupId>
    <artifactId>ambari-metrics-common</artifactId>
    <version>2.1.0.0</version>
    <exclusions>
        <exclusion>
            <artifactId>jdk.tools</artifactId>
            <groupId>jdk.tools</groupId>
        </exclusion>
    </exclusions>
</dependency>

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

How do I detect the Python version at runtime?

Since all you are interested in is whether you have Python 2 or 3, a bit hackish but definitely the simplest and 100% working way of doing that would be as follows: python python_version_major = 3/2*2 The only drawback of this is that when there is Python 4, it will probably still give you 3.

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

SQL Query for Selecting Multiple Records

I have 3 fields to fetch from Oracle Database,Which is for Forex and Currency Application.

SELECT BUY.RATE FROM FRBU.CURRENCY WHERE CURRENCY.MARKET =10 AND CURRENCY.CODE IN (‘USD’, ’AUD’, ‘SGD’)

Convert JSON array to Python list

Tested on Ideone.


import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

How do I see which checkbox is checked?

you can check that by either isset() or empty() (its check explicit isset) weather check box is checked or not

for example

  <input type='checkbox' name='Mary' value='2' id='checkbox' />

here you can check by

if (isset($_POST['Mary'])) {
    echo "checked!";
}

or

if (!empty($_POST['Mary'])) {
    echo "checked!";
}

the above will check only one if you want to do for many than you can make an array instead writing separate for all checkbox try like

<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />

php

  $aDoor = $_POST['formDoor'];
  if(empty($aDoor))
  {
    echo("You didn't select any buildings.");
  }
  else
  {
    $N = count($aDoor);
    echo("You selected $N door(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo htmlspecialchars($aDoor[$i] ). " ";
    }
  }

How to give environmental variable path for file appender in configuration file in log4j

you CAN give it environment variables. Just preppend env: before the variable name, like this:

value="${env:MY_HOME}/logs/message.log"

Android: adb pull file on desktop

do adb pull \sdcard\log.txt C:Users\admin\Desktop

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

Another way of doing it. This approach can be useful for changing the text to 2 different colors, just by adding 2 spans.

Label1.Text = "String with original color" + "<b><span style=""color:red;"">" + "Your String Here" + "</span></b>";

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

How to Import .bson file format on mongodb

Just for reference if anyone is still struggling with mongorestore.

You have to run monogorestore in terminal/command prompt and not in mongo console.

$ mongorestore -d db_name /path_to_mongo_dump/

for more details you can visit official documentations

https://docs.mongodb.com/manual/reference/program/mongorestore/

How to change package name of an Android Application

I found the easiest solution was to use Regexxer to replace "com.package.name" with "com.newpackage.name", then rename the directories properly. Super easy, super fast.

Attach IntelliJ IDEA debugger to a running Java process

Also, don't forget you need to add "-Xdebug" flag in app JAVA_OPTS if you want connect in debug mode.

How to solve maven 2.6 resource plugin dependency?

I have faced the same issue. Try declaring missing plugin in the conf/settings.xml.

<build>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>2.6</version>
        </plugin>           
      </plugins>
    </pluginManagement>   
</build>

How to put wildcard entry into /etc/hosts?

It happens that /etc/hosts file doesn't support wild card entries.

You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf and add the following line:

address=/example.com/127.0.0.1

Validate that end date is greater than start date with jQuery

In javascript/jquery most of the developer uses From & To date comparison which is string, without converting into date format. The simplest way to compare from date is greater then to date is.

Date.parse(fromDate) > Date.parse(toDate)

Always parse from and to date before comparison to get accurate results

What does "both" mean in <div style="clear:both">

Clear:both gives you that space between them.

For example your code:

  <div style="float:left">Hello</div>
  <div style="float:right">Howdy dere pardner</div>

Will currently display as :

Hello  ...................   Howdy dere pardner

If you add the following to above snippet,

  <div style="clear:both"></div>

In between them it will display as:

Hello ................ 
                       Howdy dere pardner

giving you that space between hello and Howdy dere pardner.

Js fiiddle http://jsfiddle.net/Qk5vR/1/

Executing a stored procedure within a stored procedure

Inline Stored procedure we using as per our need. Example like different Same parameter with different values we have to use in queries..

Create Proc SP1
(
 @ID int,
 @Name varchar(40)
 -- etc parameter list, If you don't have any parameter then no need to pass.
 )

  AS
  BEGIN

  -- Here we have some opereations

 -- If there is any Error Before Executing SP2 then SP will stop executing.

  Exec SP2 @ID,@Name,@SomeID OUTPUT 

 -- ,etc some other parameter also we can use OutPut parameters like 

 -- @SomeID is useful for some other operations for condition checking insertion etc.

 -- If you have any Error in you SP2 then also it will stop executing.

 -- If you want to do any other operation after executing SP2 that we can do here.

END

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

If the keystore is for tomcat then, after creating the keystore with the above answers, you must add a final step to create the "tomcat" alias for the key:

keytool -changealias -alias "1" -destalias "tomcat" -keystore keystore-file.jks

You can check the result with:

keytool -list -keystore keystore-file.jks -v

Determine distance from the top of a div to top of window with javascript

I used this:

                              myElement = document.getElemenById("xyz");
Get_Offset_From_Start       ( myElement );  // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement );  // returns positions from current scrolled view's TOP and LEFT

code:

function Get_Offset_From_Start (object, offset) { 
    offset = offset || {x : 0, y : 0};
    offset.x += object.offsetLeft;       offset.y += object.offsetTop;
    if(object.offsetParent) {
        offset = Get_Offset_From_Start (object.offsetParent, offset);
    }
    return offset;
}

function Get_Offset_From_CurrentView (myElement) {
    if (!myElement) return;
    var offset = Get_Offset_From_Start (myElement);
    var scrolled = GetScrolled (myElement.parentNode);
    var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
    return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
    scrolled = scrolled || {x : 0, y : 0};
    scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
    if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
    return scrolled;
}

    /*
    // live monitoring
    window.addEventListener('scroll', function (evt) {
        var Positionsss =  Get_Offset_From_CurrentView(myElement);  
        console.log(Positionsss);
    });
    */

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

The javax.mail-api artifact is only good for compiling against.

You actually need to run code, so you need a complete implementation of JavaMail API. Use this:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

NOTE: The version number will probably differ. Check the latest version here.

How do I get values from a SQL database into textboxes using C#?

If you want to display single value access from database into textbox, please refer to the code below:

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
TextBox1.Text=cmd.ExecuteScalar();
Con.Close();

or

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
SqlDataReader dr=new SqlDataReadr();
dr=cmd.Executereader();
if(dr.read())
{
    TextBox1.Text=dr.GetValue(0).Tostring();
}
Con.Close();

how to dynamically add options to an existing select in vanilla javascript

Try this;

   var data = "";
   data = "<option value = Some value> Some Option </option>";         
   options = [];
   options.push(data);
   select = document.getElementById("drop_down_id");
   select.innerHTML = optionsHTML.join('\n'); 

HTML/CSS: how to put text both right and left aligned in a paragraph

I wouldn't put it in the same <p>, since IMHO the two infos are semantically too different. If you must, I'd suggest this:

<p style="text-align:right">
 <span style="float:left">I'll be on the left</span>
 I'll be on the right
</p>

Difference between Console.Read() and Console.ReadLine()?

Difference between Read(),Readline() and ReadKey() in C#

Read()-Accept the string value and return the string value. Readline() -Accept the string and return Integer ReadKey() -Accept the character and return Character

Summary:

1.The above mentioned three methods are mainly used in Console application and these are used for return the different values . 2.If we use Read line or Read() we need press Enter button to come back to code. 3.If we using Read key() we can press any key to come back code in application

How to upload file to server with HTTP POST multipart/form-data?

I was also wanted to upload stuff to a Server and it was a Spring application i finally discovered that I needed to acctually set an content type for it to interpret it as a file. Just like this:

...
MultipartFormDataContent form = new MultipartFormDataContent();
var fileStream = new FileStream(uniqueTempPathInProject, FileMode.Open);
var streamContent = new StreamContent(fileStream);
streamContent.Headers.ContentType=new MediaTypeHeaderValue("application/zip");
form.Add(streamContent, "file",fileName);
...

How do I POST XML data with curl

-H "text/xml" isn't a valid header. You need to provide the full header:

-H "Content-Type: text/xml" 

RSA: Get exponent and modulus given a public key

It depends on the tools you can use. I doubt there is a JavaScript too that could do it directly within the browser. It also depends if it's a one-off (always the same key) or whether you need to script it.

Command-line / OpenSSL

If you want to use something like OpenSSL on a unix command line, you can do something as follows. I'm assuming you public.key file contains something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmBAjFv+29CaiQqYZIw4P
J0q5Qz2gS7kbGleS3ai8Xbhu5n8PLomldxbRz0RpdCuxqd1yvaicqpDKe/TT09sR
mL1h8Sx3Qa3EQmqI0TcEEqk27Ak0DTFxuVrq7c5hHB5fbJ4o7iEq5MYfdSl4pZax
UxdNv4jRElymdap8/iOo3SU1RsaK6y7kox1/tm2cfWZZhMlRFYJnpoXpyNYrp+Yo
CNKxmZJnMsS698kaFjDlyznLlihwMroY0mQvdD7dCeBoVlfPUGPAlamwWyqtIU+9
5xVkSp3kxcNcNb/mePSKQIPafQ1sAmBKPwycA/1I5nLzDVuQa95ZWMn0JkphtFIh
HQIDAQAB
-----END PUBLIC KEY-----

Then, the commands would be:

PUBKEY=`grep -v -- ----- public.key | tr -d '\n'`

Then, you can look into the ASN.1 structure:

echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i

This should give you something like this:

    0:d=0  hl=4 l= 290 cons: SEQUENCE          
    4:d=1  hl=2 l=  13 cons:  SEQUENCE          
    6:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
   17:d=2  hl=2 l=   0 prim:   NULL              
   19:d=1  hl=4 l= 271 prim:  BIT STRING 

The modulus and public exponent are in the last BIT STRING, offset 19, so use -strparse:

 echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i -strparse 19

This will give you the modulus and the public exponent, in hexadecimal (the two INTEGERs):

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim:  INTEGER           :98102316FFB6F426A242A619230E0F274AB9433DA04BB91B1A5792DDA8BC5DB86EE67F0F2E89A57716D1CF4469742BB1A9DD72BDA89CAA90CA7BF4D3D3DB1198BD61F12C7741ADC4426A88D1370412A936EC09340D3171B95AEAEDCE611C1E5F6C9E28EE212AE4C61F752978A596B153174DBF88D1125CA675AA7CFE23A8DD253546C68AEB2EE4A31D7FB66D9C7D665984C951158267A685E9C8D62BA7E62808D2B199926732C4BAF7C91A1630E5CB39CB96287032BA18D2642F743EDD09E0685657CF5063C095A9B05B2AAD214FBDE715644A9DE4C5C35C35BFE678F48A4083DA7D0D6C02604A3F0C9C03FD48E672F30D5B906BDE5958C9F4264A61B452211D
  265:d=1  hl=2 l=   3 prim:  INTEGER           :010001

That's probably fine if it's always the same key, but this is probably not very convenient to put in a script.

Alternatively (and this might be easier to put into a script),

openssl rsa -pubin -inform PEM -text -noout < public.key

will return this:

Modulus (2048 bit):
    00:98:10:23:16:ff:b6:f4:26:a2:42:a6:19:23:0e:
    0f:27:4a:b9:43:3d:a0:4b:b9:1b:1a:57:92:dd:a8:
    bc:5d:b8:6e:e6:7f:0f:2e:89:a5:77:16:d1:cf:44:
    69:74:2b:b1:a9:dd:72:bd:a8:9c:aa:90:ca:7b:f4:
    d3:d3:db:11:98:bd:61:f1:2c:77:41:ad:c4:42:6a:
    88:d1:37:04:12:a9:36:ec:09:34:0d:31:71:b9:5a:
    ea:ed:ce:61:1c:1e:5f:6c:9e:28:ee:21:2a:e4:c6:
    1f:75:29:78:a5:96:b1:53:17:4d:bf:88:d1:12:5c:
    a6:75:aa:7c:fe:23:a8:dd:25:35:46:c6:8a:eb:2e:
    e4:a3:1d:7f:b6:6d:9c:7d:66:59:84:c9:51:15:82:
    67:a6:85:e9:c8:d6:2b:a7:e6:28:08:d2:b1:99:92:
    67:32:c4:ba:f7:c9:1a:16:30:e5:cb:39:cb:96:28:
    70:32:ba:18:d2:64:2f:74:3e:dd:09:e0:68:56:57:
    cf:50:63:c0:95:a9:b0:5b:2a:ad:21:4f:bd:e7:15:
    64:4a:9d:e4:c5:c3:5c:35:bf:e6:78:f4:8a:40:83:
    da:7d:0d:6c:02:60:4a:3f:0c:9c:03:fd:48:e6:72:
    f3:0d:5b:90:6b:de:59:58:c9:f4:26:4a:61:b4:52:
    21:1d
Exponent: 65537 (0x10001)

Java

It depends on the input format. If it's an X.509 certificate in a keystore, use (RSAPublicKey)cert.getPublicKey(): this object has two getters for the modulus and the exponent.

If it's in the format as above, you might want to use BouncyCastle and its PEMReader to read it. I haven't tried the following code, but this would look more or less like this:

PEMReader pemReader = new PEMReader(new FileReader("file.pem"));
Object obj = pemReader.readObject();
pemReader.close();
if (obj instanceof X509Certificate) {
   // Just in case your file contains in fact an X.509 certificate,
   // useless otherwise.
   obj = ((X509Certificate)obj).getPublicKey();
}
if (obj instanceof RSAPublicKey) {
   // ... use the getters to get the BigIntegers.
}

(You can use BouncyCastle similarly in C# too.)

Refresh page after form submitting

If you want the form to be submitted on the same page then remove the action from the form attributes.

<form method="POST" name="myform">
 <!-- Your HTML code Here -->
</form>

However, If you want to reload the page or redirect the page after submitting the form from another file then you call this function in php and it will redirect the page in 0 seconds. Also, You can use the header if you want to, just make sure you don't have any content before using the header

 function page_redirect($location)
 {
   echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
   exit; 
 }

 // I want the page to go to google.
 // page_redirect("http://www.google.com")

Replace text inside td using jQuery having td containing other elements

Using text nodes in jquery is a particularly delicate endeavour and most operations are made to skip them altogether.

Instead of going through the trouble of carefully avoiding the wrong nodes, why not just wrap whatever you need to replace inside a <span> for instance:

<td><span class="replaceme">8: Tap on APN and Enter <B>www</B>.</span></td>

Then:

$('.replaceme').html('Whatever <b>HTML</b> you want here.');

Best way to check if a Data Table has a null value in it

You can null/blank/space Etc value using LinQ Use Following Query

   var BlankValueRows = (from dr1 in Dt.AsEnumerable()
                                  where dr1["Columnname"].ToString() == ""
                                  || dr1["Columnname"].ToString() == ""
                                   || dr1["Columnname"].ToString() == ""
                                  select Columnname);

Here Replace Columnname with table column name and "" your search item in above code we looking null value.

python mpl_toolkits installation issue

if anyone has a problem on Mac, can try this

sudo pip install --upgrade matplotlib --ignore-installed six

What does "where T : class, new()" mean?

where T : struct

The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.

where T : class

The type argument must be a reference type, including any class, interface, delegate, or array type. (See note below.)

where T : new() The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last.

where T : [base class name]

The type argument must be or derive from the specified base class.

where T : [interface name]

The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

where T : U

The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.

Split string into string array of single characters

Try this:

var charArray = "this is a test".ToCharArray().Select(c=>c.ToString());

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JavaScript moving element in the DOM

jQuery.fn.swap = function(b){ 
    b = jQuery(b)[0]; 
    var a = this[0]; 
    var t = a.parentNode.insertBefore(document.createTextNode(''), a); 
    b.parentNode.insertBefore(a, b); 
    t.parentNode.insertBefore(b, t); 
    t.parentNode.removeChild(t); 
    return this; 
};

and use it like this:

$('#div1').swap('#div2');

if you don't want to use jQuery you could easily adapt the function.

Finding duplicate rows in SQL Server

You can do it like this:

SELECT
    o.id, o.orgName, d.intCount
FROM (
     SELECT orgName, COUNT(*) as intCount
     FROM organizations
     GROUP BY orgName
     HAVING COUNT(*) > 1
) AS d
    INNER JOIN organizations o ON o.orgName = d.orgName

If you want to return just the records that can be deleted (leaving one of each), you can use:

SELECT
    id, orgName
FROM (
     SELECT 
         orgName, id,
         ROW_NUMBER() OVER (PARTITION BY orgName ORDER BY id) AS intRow
     FROM organizations
) AS d
WHERE intRow != 1

Edit: SQL Server 2000 doesn't have the ROW_NUMBER() function. Instead, you can use:

SELECT
    o.id, o.orgName, d.intCount
FROM (
     SELECT orgName, COUNT(*) as intCount, MIN(id) AS minId
     FROM organizations
     GROUP BY orgName
     HAVING COUNT(*) > 1
) AS d
    INNER JOIN organizations o ON o.orgName = d.orgName
WHERE d.minId != o.id

How to open a web page from my application?

    string target= "http://www.google.com";
try
{
    System.Diagnostics.Process.Start(target);
}
catch (System.ComponentModel.Win32Exception noBrowser)
{
    if (noBrowser.ErrorCode==-2147467259)
    MessageBox.Show(noBrowser.Message);
}
catch (System.Exception other)
{
    MessageBox.Show(other.Message);
}

Draw in Canvas by finger, Android

In addition to Ishan's answer, if you want to draw programatically without user interaction, you can edit the class just a little like this.

public class DrawingCanvas extends View {

private Paint mPaint;
private Path mPath;
private boolean isUserInteractionEnabled = false;

public DrawingCanvas(Context context, AttributeSet attrs) {
    super(context, attrs);
    mPaint = new Paint();
    mPaint.setColor(Color.RED);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(10);
    mPath = new Path();
}


@Override
protected void onDraw(Canvas canvas) {
    canvas.drawPath(mPath, mPaint);
    super.onDraw(canvas);
}


@Override
public boolean onTouchEvent(MotionEvent event) {
    if (isUserInteractionEnabled) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPath.moveTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                mPath.lineTo(event.getX(), event.getY());
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
    }

    return true;
}

public void moveCursorTo(float x, float y) {
    mPath.moveTo(x, y);
}

public void makeLine(float toX, float toY) {
    mPath.lineTo(toX, toY);
}

public void setUserInteractionEnabled(boolean userInteractionEnabled) {
    isUserInteractionEnabled = userInteractionEnabled;
}
}

And then use it like

drawingCanvas.setUserInteractionEnabled(true) // to enable user interaction
drawingCanvas.setUserInteractionEnabled(true) // to disable user interaction

To Draw programatically

drawingCanvas.moveCursorTo(70f, 70f) // Move the cursor (Define starting point)
drawingCanvas.makeLine(200f, 200f) // End point (To where you need to draw)

How to make "if not true condition"?

try

if ! grep -q sysa /etc/passwd ; then

grep returns true if it finds the search target, and false if it doesn't.

So NOT false == true.

if evaluation in shells are designed to be very flexible, and many times doesn't require chains of commands (as you have written).

Also, looking at your code as is, your use of the $( ... ) form of cmd-substitution is to be commended, but think about what is coming out of the process. Try echo $(cat /etc/passwd | grep "sysa") to see what I mean. You can take that further by using the -c (count) option to grep and then do if ! [ $(grep -c "sysa" /etc/passwd) -eq 0 ] ; then which works but is rather old school.

BUT, you could use the newest shell features (arithmetic evaluation) like

if ! (( $(grep -c "sysa" /etc/passwd) == 0 )) ; then ...`

which also gives you the benefit of using the c-lang based comparison operators, ==,<,>,>=,<=,% and maybe a few others.

In this case, per a comment by Orwellophile, the arithmetic evaluation can be pared down even further, like

if ! (( $(grep -c "sysa" /etc/passwd) )) ; then ....

OR

if (( ! $(grep -c "sysa" /etc/passwd) )) ; then ....

Finally, there is an award called the Useless Use of Cat (UUOC). :-) Some people will jump up and down and cry gothca! I'll just say that grep can take a file name on its cmd-line, so why invoke extra processes and pipe constructions when you don't have to? ;-)

I hope this helps.

How to implement Android Pull-to-Refresh

I've written a pull to refresh component here: https://github.com/guillep/PullToRefresh It works event if the list does not have items, and I've tested it on >=1.6 android phones.

Any suggestion or improvement is appreciated :)

Can table columns with a Foreign Key be NULL?

I also stuck on this issue. But I solved simply by defining the foreign key as unsigned integer. Find the below example-

CREATE TABLE parent (
   id int(10) UNSIGNED NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id int(10) UNSIGNED NOT NULL,
    parent_id int(10) UNSIGNED DEFAULT NULL,
    FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;

pycharm running way slow

Every performance problem with PyCharm is unique, a solution that helps to one person will not work for another. The only proper way to fix your specific performance problem is by capturing the CPU profiler snapshot as described in this document and sending it to PyCharm support team, either by submitting a ticket or directly into the issue tracker.

After the CPU snapshot is analyzed, PyCharm team will work on a fix and release a new version which will (hopefully) not be affected by this specific performance problem. The team may also suggest you some configuration change or workaround to remedy the problem based on the analysis of the provided data.

All the other "solutions" (like enabling Power Save mode and changing the highlighting level) will just hide the real problems that should be fixed.

MySQL WHERE: how to write "!=" or "not equals"?

DELETE FROM konta WHERE taken <> '';

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

While the question has already been answered several times, this simple solution to the problem has not been listed yet.

x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z4 = {}
z4.update(x)
z4.update(y)

It is as fast as z0 and the evil z2 mentioned above, but easy to understand and change.

Recursive mkdir() system call on Unix

The two other answers given are for mkdir(1) and not mkdir(2) like you ask for, but you can look at the source code for that program and see how it implements the -p options which calls mkdir(2) repeatedly as needed.

Can you recommend a free light-weight MySQL GUI for Linux?

I really like the MySQL collection of of GUI Tools. They aren't too large or resource hungry.

There are quite a few options here as well. Of the applications presented on that page, I like SQL Buddy - it does require a web server, however.

Transparent CSS background color

Here is an example class using CSS named colors:

.semi-transparent {
  background: yellow;
  opacity: 0.25;
}

This adds a background that is 25% opaque (colored) and 75% transparent.

CAVEAT Unfortunately, opacity will affect then entire element it's attached to.
So if you have text in that element, it will set the text to 25% opacity too. :-(

The way to get past this is to use the rgba or hsla methods to indicate transparency as part of your desired background "color". This allows you to specify the background transparency, independent from the transparency of the other items in your element.

Here are 3 ways to set a blue background at 75% transparency, without affecting other elements:

  • background: rgba(0%, 0%, 100%, 0.75)
  • background: rgba(0, 0, 255, 0.75)
  • background: hsla(240, 100%, 50%, 0.75)

Checking if a collection is empty in Java: which is the best method?

Apache Commons' CollectionUtils.isNotEmpty(Collection) is a NULL-SAFE check

Returns TRUE is the Collection/List is not-empty and not-null Returns FALSE if the Collection is Null

Example:

List<String> properties = new ArrayList();
...
if (CollectionUtils.isNotEmpty(properties)) {
  // process the list
} else {
 // list is null or empty
}

Refer: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#isNotEmpty(java.util.Collection)

How do I change screen orientation in the Android emulator?

You no longer need to remember the shortcuts. The latest Android AVD interface contains a sidebar with various functional shortcuts. I've circled in blue the buttons that rotate the screen clockwise and counter-clockwise.

enter image description here

how do I create an array in jquery?

your question makes no sense. you are asking how to turn a hash into an array. You cant.

you can make a list of values, or make a list of keys, and neither of these have anything to do with jquery, this is pure javascript

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

Try this. It can handle more than 2 values

SELECT Max(v) FROM (VALUES (1), (2), (3)) AS value(v)

How to load local html file into UIWebView

May be your HTML file doesn't support UTF-8 encoding, because the same code is working for me.

Or u can also these line of code:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"Notes For Apple" ofType:@"htm" inDirectory:nil];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[WebView loadHTMLString:htmlString baseURL:nil];

How to perform case-insensitive sorting in JavaScript?

The other answers assume that the array contains strings. My method is better, because it will work even if the array contains null, undefined, or other non-strings.

var notdefined;
var myarray = ['a', 'c', null, notdefined, 'nulk', 'BYE', 'nulm'];

myarray.sort(ignoreCase);

alert(JSON.stringify(myarray));    // show the result

function ignoreCase(a,b) {
    return (''+a).toUpperCase() < (''+b).toUpperCase() ? -1 : 1;
}

The null will be sorted between 'nulk' and 'nulm'. But the undefined will be always sorted last.

How to get the name of a class without the package?

If using a StackTraceElement, use:

String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);

System.out.println(simpleClassName);

To add server using sp_addlinkedserver

I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.

An extended answer for remote IP db connections:

Step 1: Link servers

EXEC sp_addlinkedserver @server='SRV_NAME',
   @srvproduct=N'',
   @provider=N'SQLNCLI',   
   @datasrc=N'aaa.bbb.ccc.ddd';

EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'

...where SRV_NAME is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd is the ip address of the remote server hosting your SQLserver DB.

Step 2: Run your queries For instance:

SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table

...and that's it!

Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

this error basically comes when you use the object before using it.

What is the fastest way to compare two sets in Java?

public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof Set))
            return false;

        Set<String> a = this;
        Set<String> b = o;
        Set<String> thedifference_a_b = new HashSet<String>(a);


        thedifference_a_b.removeAll(b);
        if(thedifference_a_b.isEmpty() == false) return false;

        Set<String> thedifference_b_a = new HashSet<String>(b);
        thedifference_b_a.removeAll(a);

        if(thedifference_b_a.isEmpty() == false) return false;

        return true;
    }

Revert to a commit by a SHA hash in Git?

It reverts the said commit, that is, adds the commit opposite to it. If you want to checkout an earlier revision, you do:

git checkout 56e05fced214c44a37759efa2dfc25a65d8ae98d

Underline text in UIlabel

NSMutableAttributedString *text = [self.myUILabel.attributedText mutableCopy];
[text addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, text.length)];
self.myUILabel.attributedText = text;

Python basics printing 1 to 100

x=1 while x<=100: print(x) x=x+3

Update OpenSSL on OS X with Homebrew

installed openssl on mac with brew but nothing found on /usr/local/bin where other brew installed bins are located. Found my fresh openssl here:

/usr/local/opt/openssl/bin/openssl

Run it like this:

/usr/local/opt/openssl/bin/openssl version

I don't want to update OS X openssl, while some OS stuff or other 3rd party apps may have dependency on older version.

I also don't mind longer path than just openssl

Writing this here for all the Googlers who are looking for location of openssl installed by brew.

How to "properly" create a custom object in JavaScript?

To continue off of bobince's answer

In es6 you can now actually create a class

So now you can do:

class Shape {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    toString() {
        return `Shape at ${this.x}, ${this.y}`;
    }
}

So extend to a circle (as in the other answer) you can do:

class Circle extends Shape {
    constructor(x, y, r) {
        super(x, y);
        this.r = r;
    }

    toString() {
        let shapeString = super.toString();
        return `Circular ${shapeString} with radius ${this.r}`;
    }
}

Ends up a bit cleaner in es6 and a little easier to read.


Here is a good example of it in action:

_x000D_
_x000D_
class Shape {_x000D_
  constructor(x, y) {_x000D_
    this.x = x;_x000D_
    this.y = y;_x000D_
  }_x000D_
_x000D_
  toString() {_x000D_
    return `Shape at ${this.x}, ${this.y}`;_x000D_
  }_x000D_
}_x000D_
_x000D_
class Circle extends Shape {_x000D_
  constructor(x, y, r) {_x000D_
    super(x, y);_x000D_
    this.r = r;_x000D_
  }_x000D_
_x000D_
  toString() {_x000D_
    let shapeString = super.toString();_x000D_
    return `Circular ${shapeString} with radius ${this.r}`;_x000D_
  }_x000D_
}_x000D_
_x000D_
let c = new Circle(1, 2, 4);_x000D_
_x000D_
console.log('' + c, c);
_x000D_
_x000D_
_x000D_

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

The answer here is not clear, so I wanted to add more detail.

Using the link provided above, I performed the following step.

In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.

This information is available at the link the OP posted in the Answer.

The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

What's the source of Error: getaddrinfo EAI_AGAIN?

In my case the problem was the docker networks ip allocation range, see this post for details

Replace text in HTML page with jQuery

var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);

for variable:

var replaced = $("body").html().replace(new RegExp("-1o9-2202", "igm"),'The ALL new string');
$("body").html(replaced);

Re-sign IPA (iPhone)

Thank you, Erik, for posting this. This worked for me. I'd like to add a note about an extra step I needed. Within "Payload/Application.app/" there was a directory named "CACertChains" that contained a file named "cacert.pem". I had to remove the directory and the .pem to complete these steps. Thanks again! –

Disable browsers vertical and horizontal scrollbars

So far we have overflow:hidden on the body. However IE doesn't always honor that and you need to put scroll="no" on the body element as well and/or place overflow:hidden on the html element as well.

You can take this further when you need to 'take control' of the view port you can do this:-

<style>
 body {width:100%; height:100%; overflow:hidden; margin:0; }
 html {width:100%; height:100%; overflow:hidden; }
</style>

An element granted height 100% in the body has the full height of the window viewport, and element positioned absolutely using bottom:nnPX will be set nn pixels above the bottom edge of the window, etc.

Get git branch name in Jenkins Pipeline/Jenkinsfile

Just getting the name from scm.branches is not enough if you've used a build parameter as a branch specifier, e.g. ${BRANCH}. You need to expand that string into a real name:

scm.branches.first().getExpandedName(env.getEnvironment())

Note that getEnvironment() must be an explicit getter otherwise env will look up for an environment variable called environment.

Don't forget that you need to approve those methods to make them accessible from the sandbox.

Force file download with php using header()

This worked for me like a charm for downloading PNG and PDF.

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_url)); //Absolute URL
ob_clean();
flush();
readfile($file_url); //Absolute URL
exit();

Python+OpenCV: cv2.imwrite

wtluo, great ! May I propose a slight modification of your code 2. ? Here it is:

for i, detected_box in enumerate(detect_boxes):
    box = detected_box["box"]
    face_img = img[ box[1]:box[1] + box[3], box[0]:box[0] + box[2] ]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

Git - push current branch shortcut

I use such alias in my .bashrc config

alias gpb='git push origin `git rev-parse --abbrev-ref HEAD`'

On the command $gpb it takes the current branch name and pushes it to the origin.

Here are my other aliases:

alias gst='git status'
alias gbr='git branch'
alias gca='git commit -am'
alias gco='git checkout'

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

Replace part of a string with another string

To have the new string returned use this:

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

Output:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

Here's the code that works for me everytime (for Outlook emails):

#to read Subjects and Body of email in a folder (or subfolder)

import win32com.client  
#import package

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")  
#create object

#get to the desired folder ([email protected] is my root folder)

root_folder = 
outlook.Folders['[email protected]'].Folders['Inbox'].Folders['SubFolderName']

#('Inbox' and 'SubFolderName' are the subfolders)

messages = root_folder.Items

for message in messages:
if message.Unread == True:    # gets only 'Unread' emails
    subject_content = message.subject
# to store subject lines of mails

    body_content = message.body
# to store Body of mails

    print(subject_content)
    print(body_content)

    message.Unread = True         # mark the mail as 'Read'
    message = messages.GetNext()  #iterate over mails

In SQL, how can you "group by" in ranges?

I see answers here that won't work in SQL Server's syntax. I would use:

select t.range as [score range], count(*) as [number of occurences]
from (
  select case 
    when score between  0 and  9 then ' 0-9 '
    when score between 10 and 19 then '10-19'
    when score between 20 and 29 then '20-29'
    ...
    else '90-99' end as range
  from scores) t
group by t.range

EDIT: see comments

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

It's important to note that using viewDidLoad for positioning is a bit risky and should be avoided since the bounds are not set. this may cause unexpected results (I had a variety of issues...)

This post describes quite well the different methods and what happens in each of them.

currently for one-time init and positioning I'm thinking of using viewDidAppear with a flag, if anyone has any other recommendation please let me know.

WampServer orange icon

To add to the above post^^:

If either of the services are not running, it might simply just be because they need to be installed/configured. This is easy to do straight from the WampManager Icon.


If Apache is not running:

 WampManager Icon -> Apache -> Service -> Install Service

You should get a command prompt pop-up if port 80 is free (if not, see above post):

      'Your port 80 is available. Install will proceed.

       Press Enter to continue...'


If MySQL is not running:

WampManager Icon -> MySQL -> Service -> Install Service


Do that for one or both services then:

WampManager Icon -> Restart All Services

The icon should now turn green :)

What do raw.githubusercontent.com URLs represent?

There are two ways of looking at github content, the "raw" way and the "Web page" way.

raw.githubusercontent.com returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.

If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com.

To see the content of raw.githubusercontent.com/${repo}/${branch}/${path} in the usual github interface:

  1. you replace raw.githubusercontent.com with plain github.com
  2. AND you insert "blob" between the repo name and the branch name.

In this case, the branch name is "master" (which is a very common branch name), so you replace /master/ with /blob/master/, and so

https://raw.githubusercontent.com/Homebrew/install/master/install

becomes

https://github.com/Homebrew/install/blob/master/install

This is the reverse of finding a file on Github and clicking the Raw link.

How do I create a Python function with optional arguments?

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

How can I parse a string with a comma thousand separator to a number?

This converts a number in whatever locale to normal number. Works for decimals points too:

function numberFromLocaleString(stringValue, locale){
    var parts = Number(1111.11).toLocaleString(locale).replace(/\d+/g,'').split('');
    if (stringValue === null)
        return null;
    if (parts.length==1) {
        parts.unshift('');
    }   
    return Number(String(stringValue).replace(new RegExp(parts[0].replace(/\s/g,' '),'g'), '').replace(parts[1],"."));
}
//Use default browser locale
numberFromLocaleString("1,223,333.567") //1223333.567

//Use specific locale
numberFromLocaleString("1 223 333,567", "ru") //1223333.567

How do I load a file into the python console?

Open command prompt in the folder in which you files to be imported are present. when you type 'python', python terminal will be opened. Now you can use

import script_name
Note: no .py extension to be used while importing.
How can I open a cmd window in a specific location?

Type datetime for input parameter in procedure

You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.

The ISO-8601 format for a DATETIME when using only the date is: YYYYMMDD (no dashes or antyhing!)

For a DATETIME with the time portion, it's YYYY-MM-DDTHH:MM:SS (with dashes, and a T in the middle to separate date and time portions).

If you want to convert a string to a DATE for SQL Server 2008 or newer, you can use YYYY-MM-DD (with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.

So in your case, you should try:

declare @a datetime
declare @b datetime 

set @a = '2012-04-06T12:23:45'   -- 6th of April, 2012
set @b = '2012-08-06T21:10:12'   -- 6th of August, 2012

exec LogProcedure 'AccountLog', N'test', @a, @b

Furthermore - your stored proc has problem, since you're concatenating together datetime and string into a string, but you're not converting the datetime to string first, and also, you're forgetting the close quotes in your statement after both dates.

So change this line here to this:

IF @DateFirst <> '' and @DateLast <> ''
   SET @FinalSQL  = @FinalSQL + '  OR CONVERT(Date, DateLog) >= ''' + 
                    CONVERT(VARCHAR(50), @DateFirst, 126) +   -- convert @DateFirst to string for concatenation!
                    ''' AND CONVERT(Date, DateLog) <=''' +  -- you need closing quotes after @DateFirst!
                    CONVERT(VARCHAR(50), @DateLast, 126) + ''''      -- convert @DateLast to string and also: closing tags after that missing!

With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.

Implicit function declarations in C

C is a very low-level language, so it permits you to create almost any legal object (.o) file that you can conceive of. You should think of C as basically dressed-up assembly language.

In particular, C does not require functions to be declared before they are used. If you call a function without declaring it, the use of the function becomes it's (implicit) declaration. In a simple test I just ran, this is only a warning in the case of built-in library functions like printf (at least in GCC), but for random functions, it will compile just fine.

Of course, when you try to link, and it can't find foo, then you will get an error.

In the case of library functions like printf, some compilers contain built-in declarations for them so they can do some basic type checking, so when the implicit declaration (from the use) doesn't match the built-in declaration, you'll get a warning.

How to open port in Linux

The following configs works on Cent OS 6 or earlier

As stated above first have to disable selinux.

Step 1 nano /etc/sysconfig/selinux

Make sure the file has this configurations

SELINUX=disabled

SELINUXTYPE=targeted

Then restart the system

Step 2

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

Step 3

sudo service iptables save

For Cent OS 7

step 1

firewall-cmd --zone=public --permanent --add-port=8080/tcp

Step 2

firewall-cmd --reload

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

I re-encounter this in the hard way as well. H vs h, for 24-hour vs 12 hour !

How to remove certain characters from a string in C++?

Here's yet another alternative:

template<typename T>
void Remove( std::basic_string<T> & Str, const T * CharsToRemove )
{
    std::basic_string<T>::size_type pos = 0;
    while (( pos = Str.find_first_of( CharsToRemove, pos )) != std::basic_string<T>::npos )
    {
        Str.erase( pos, 1 ); 
    }
}

std::string a ("(555) 555-5555");
Remove( a, "()-");

Works with std::string and std::wstring

Processing $http response in service

Related to this I went through a similar problem, but not with get or post made by Angular but with an extension made by a 3rd party (in my case Chrome Extension).
The problem that I faced is that the Chrome Extension won't return then() so I was unable to do it the way in the solution above but the result is still Asynchronous.
So my solution is to create a service and to proceed to a callback

app.service('cookieInfoService', function() {
    this.getInfo = function(callback) {
        var model = {};
        chrome.cookies.get({url:serverUrl, name:'userId'}, function (response) {
            model.response= response;
            callback(model);
        });
    };
});

Then in my controller

app.controller("MyCtrl", function ($scope, cookieInfoService) {
    cookieInfoService.getInfo(function (info) {
        console.log(info);
    });
});

Hope this can help others getting the same issue.

C# with MySQL INSERT parameters

Three things: use the using statement, use AddWithValue and prefix parameters with ? and add Allow User Variables=True to the connection string.

 string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
 using (var conn = new MySqlConnection(connString))
 {
      conn.Open();
      var comm = conn.CreateCommand();
      comm.CommandText = "INSERT INTO room(person,address) VALUES(@person, @address)";
      comm.Parameters.AddWithValue("?person", "Myname");
      comm.Parameters.AddWithValue("?address", "Myaddress");
      comm.ExecuteNonQuery();
  }

Also see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx for more information about the command usage, and http://dev.mysql.com/doc/refman/5.1/en/connector-net-connection-options.html for information about the Allow User Variables option (only supported in version 5.2.2 and above).

Random color generator

A working single-line solution (with padding leading zeroes):

var color = "#" + "colors".split("").map(function(){return parseInt(Math.random()*0x10).toString(16);}).join("");

How to make a pure css based dropdown menu?

View code online on: WebCrafts.org

HTML code:

<body id="body">
<div id="navigation">
    <h2>
        Pure CSS Drop-down Menu
    </h2>
  <div id="nav" class="nav">
    <ul>
        <li><a href="#">Menu1</a></li>
        <li>
            <a href="#">Menu2</a>
          <ul>
                <li><a href="#">Sub-Menu1</a></li>
                <li>
                    <a href="#">Sub-Menu2</a>
                  <ul>
                        <li><a href="#">Demo1</a></li>
                      <li><a href="#">Demo2</a></li>
                    </ul>
                </li>
                <li><a href="#">Sub-Menu3</a></li>
                <li><a href="#">Sub-Menu4</a></li>
            </ul>
        </li>
        <li><a href="#">Menu3</a></li>
        <li><a href="#">Menu4</a></li>
    </ul>
  </div>
</div>
</body>

Css code:

body{
    background-color:#111;
}

#navigation{
    text-align:center;
}
#navigation h2{
    color:#DDD;
}

.nav{
    display:inline-block;
    z-index:5;
    font-weight:bold;
}
.nav ul{
    width:auto;
    list-style:none;
}

.nav ul li{
    display:inline-block;
}

.nav ul li a{
    text-decoration:none;
    text-align:center;
    color:#222;
    display:block;
    width:120px;
    line-height:30px;
    background-color:gray;
}

.nav ul li a:hover{
    background-color:#EEC;   
}
.nav ul li ul{
    margin-top:0px;
    padding-left:0px;
    position:absolute;
    display:none;
}

.nav ul li:hover ul{
    display:block;
}

.nav ul li ul li{
    display:block;
}

.nav ul li ul li ul{
    margin-left:100%;
    margin-top:-30px;
    visibility:hidden;
}

.nav ul li ul li:hover ul{
    margin-left:100%;
    visibility:visible;
}

Create list or arrays in Windows Batch

Sometimes the array element may be very long, at that time you can create an array in this way:

set list=a
set list=%list%;b 
set list=%list%;c 
set list=%list%;d

Then show it:

@echo off
for %%a in (%list%) do ( 
 echo %%a
 echo/
)

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Worth mentioning: you should download the x64 version!

From the main download page (https://www.iis.net/downloads/microsoft/url-rewrite) click "additional downloads" (under the main download button) and download the x64 version (because for some reason - the default download version is x86)

Correct way of getting Client's IP Addresses from http.Request

This is how I come up with the IP

func ReadUserIP(r *http.Request) string {
    IPAddress := r.Header.Get("X-Real-Ip")
    if IPAddress == "" {
        IPAddress = r.Header.Get("X-Forwarded-For")
    }
    if IPAddress == "" {
        IPAddress = r.RemoteAddr
    }
    return IPAddress
}
  • X-Real-Ip - fetches first true IP (if the requests sits behind multiple NAT sources/load balancer)

  • X-Forwarded-For - if for some reason X-Real-Ip is blank and does not return response, get from X-Forwarded-For

  • Remote Address - last resort (usually won't be reliable as this might be the last ip or if it is a naked http request to server ie no load balancer)

Regular expression to search multiple strings (Textpad)

I suggest much better solution. Task in my case: add http://google.com/ path before each record and import multiple fields.

CSV single field value (all images just have filenames, separate by |):
"123.jpg|345.jpg|567.jpg"

Tamper 1st plugin: find and replace by REGEXP: pattern: /([a-zA-Z0-9]*)./ replacement: http://google.com/$1

Tamper 2nd plugin: explode setting: explode by |

In this case you don't need any additinal fields mappings and can use 1 field in CSV

Transfer data from one HTML file to another

The old fashioned way of setting a global variable that persist between pages is to set the data in a Cookie. The modern way is to use Local Storage, which has a good browser support (IE8+, Firefox 3.5+, Chrome 4+, Android 2+, iPhone 2+). Using localStorage is as easy as using an array:

localStorage["key"] = value;

... in another page ...
value = localStorage["key"];

You can also attach event handlers to listen for changes, though the event API is slightly different between browsers. More on the topic.

How can I copy network files using Robocopy?

I use the following format and works well.

robocopy \\SourceServer\Path \\TargetServer\Path filename.txt

to copy everything you can replace filename.txt with *.* and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

What is the easiest way to install BLAS and LAPACK for scipy?

For windows: Best is to use pre-compiled package available from this site: http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#scipy

How to update a value in a json file and save it through node.js

addition to the previous answer add file path directory for the write operation

 fs.writeFile(path.join(__dirname,jsonPath), JSON.stringify(newFileData), function (err) {}

Serving favicon.ico in ASP.NET MVC

I agree with the answer from Chris, but seeing this is a specific ASP.NET MVC question it would be better to use either Razor syntax:

<link rel="icon" href="@Url.Content("~/content/favicon.ico")"/>

Or traditionally

<link rel="icon" href="<%= Url.Content("~/content/favicon.ico") %>"/>

rather than

<link rel="icon" href="http://www.mydomain.com/content/favicon.ico"/>

Get Row Index on Asp.net Rowcommand event

this is answer for your question.

GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;

int RowIndex = gvr.RowIndex; 

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

Amazon Linux: fixing GCC issue

Since this comes up as the first result on Google, I just wanted to document my experience with Amazon Linux. Installing gcc-c++.noarch fixed the problem:

sudo yum install gcc-c++.noarch

Some people also reported this alternative as a solution:

sudo yum install gcc72-c++

Simple division in Java - is this a bug or a feature?

Please do not take this as an answer to the question. It is not, but an advice related to exploiting the difference of int and float. I would have put this under a comment except that the answer box allows me to format this comment.

This feature has been used in every respectable programming language since the days of fortran (or earlier) - I must confess I was once a Fortran and Cobol punch card programmer.

As an example, integer division of 10/3 yields integer value 3 since an integer has no facility to hold fractional residual .3333.. .

One of the ways we (old time ancient programmers) had been using this feature is loop control.

Let's say we wish to print an array of 1000 strings, but we wish to insert a line break after every 15th string, to insert some prettyfying chars at the end of the line and at the beginning of the next line. We exploit this, given that integer k is the position of a string in that array.

int(k/15)*15 == k

is true only when k is divisible by 15, an occurrence at a frequency of every 15th cell. Which is akin to what my friend said about his grandfather's dead watch being accurate twice a day.

int(1/15) = 0 -> int(1/15)*15 = 0
int(2/15) = 0 -> int(2/15)*15 = 0
...
int(14/15) = 0 -> int(14/15)*15 = 0
int(15/15) = 1 -> int(15/15)*15 = 15

int(16/15) = 1 -> int(16/15)*15 = 15
int(17/15) = 1 -> int(17/15)*15 = 15
...
int(29/15) = 1 -> int(29/15)*15 = 15
int(30/15) = 2 -> int(30/15)*15 = 30

Therefore, the loop,

leftPrettyfy();
for(int k=0; k<sa.length; k++){
  print(sa[k]);
  int z = k + 1;
  if ((z/15)*15 == z){
    rightPrettyfy();
    leftPrettyfy();
  }
}

By varying k in a fanciful way in the loop, we could print a triangular printout

1
2  3
4  5  6
7  8  9  10
11 12 13 14 15

That is to demonstrate that, if you consider this a bug, this "bug" is a useful feature that we would not want to be removed from any of the various languages that we have used thus far.

How to fetch JSON file in Angular 2

For example, in your component before you declare your @Component

const en = require('../assets/en.json');

How to add image background to btn-default twitter-bootstrap button?

_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<style type="text/css">_x000D_
  .sign-in-facebook_x000D_
  {_x000D_
    background-image: url('http://i.stack.imgur.com/e2S63.png');_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
  .sign-in-facebook:hover_x000D_
  {_x000D_
    background-image: url('http://i.stack.imgur.com/e2S63.png');_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
</style>_x000D_
<p>My current button got white background<br/>_x000D_
<input type="button" value="Sign In with Facebook" class="sign-in-facebook btn btn-secondary" style="margin-top:2px; margin-bottom:2px;" >_x000D_
</p>_x000D_
<p>I need the current btn-default style like below<br/>_x000D_
<input type="button" class="btn btn-default" value="Sign In with Facebook" />_x000D_
</p>_x000D_
<strong>NOTE:</strong> facebook icon at left side of the button.
_x000D_
_x000D_
_x000D_

Getting the first index of an object

To get the first key of your object

const myObject = {
   'foo1': { name: 'myNam1' },
   'foo2': { name: 'myNam2' }
}

const result = Object.keys(myObject)[0];

// result will return 'foo1'

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

Is there an alternative to string.Replace that is case-insensitive?

The regular expression method should work. However what you can also do is lower case the string from the database, lower case the %variables% you have, and then locate the positions and lengths in the lower cased string from the database. Remember, positions in a string don't change just because its lower cased.

Then using a loop that goes in reverse (its easier, if you do not you will have to keep a running count of where later points move to) remove from your non-lower cased string from the database the %variables% by their position and length and insert the replacement values.

Facebook how to check if user has liked page and show content?

There is an article here that describes your problem

http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/

    <fb:visible-to-connection>
       Fans will see this content.
       <fb:else>
           Non-fans will see this content.
       </fb:else>
    </fb:visible-to-connection>

JDBC connection to MSSQL server in windows authentication mode

Try following these steps:

  1. Add the integratedSecurity=true to JDBC URL like this:

    Url: jdbc:sqlserver://<<Server>>:<<Port>>;databasename=<<DatabaseName>>;integratedsecurity=true 
    
  2. Make sure to add the sqljdbc driver 4 or above version (sqljdbc.jar) in your project build path:

    java.sql.DatabaseMetaData metaData = connection.getMetaData();
    System.out.println("Driver version:" + metaData.getDriverVersion());
    
  3. Add the VM argument for your project:

    • Find the sqljdbc_auth.dll file from DB installed server (C:\Program Files\sqljdbc_4.0\enu\auth\x86), or download from this link.

    • Place the dll file in your project folder and specify the VM argument like this: VM Argument: -Djava.library.path="<<DLL File path till folder>>"

      NOTE: Check your java version 32/64 bit then add 32/64 bit version dll file accordingly.

Remove a fixed prefix/suffix from a string in Bash

$ string="hello-world"
$ prefix="hell"
$ suffix="ld"

$ #remove "hell" from "hello-world" if "hell" is found at the beginning.
$ prefix_removed_string=${string/#$prefix}

$ #remove "ld" from "o-world" if "ld" is found at the end.
$ suffix_removed_String=${prefix_removed_string/%$suffix}
$ echo $suffix_removed_String
o-wor

Notes:

#$prefix : adding # makes sure that substring "hell" is removed only if it is found in beginning. %$suffix : adding % makes sure that substring "ld" is removed only if it is found in end.

Without these, the substrings "hell" and "ld" will get removed everywhere, even it is found in the middle.