Programs & Examples On #Anti patterns

An anti-pattern mimics [tag:design-patterns] in that it appears to be a solution to a problem, but in fact has negative effects.

Any reason not to use '+' to concatenate two strings?

I use the following with python 3.8

string4 = f'{string1}{string2}{string3}'

How to block users from closing a window in Javascript?

How about that?

function internalHandler(e) {
    e.preventDefault(); // required in some browsers
    e.returnValue = ""; // required in some browsers
    return "Custom message to show to the user"; // only works in old browsers
}

if (window.addEventListener) {
    window.addEventListener('beforeunload', internalHandler, true);
} else if (window.attachEvent) {
    window.attachEvent('onbeforeunload', internalHandler);
}

Singleton with Arguments in Java

I think this is a common problem. Separating the "initialization" of the singleton from the "get" of the singleton might work (this example uses a variation of double checked locking).

public class MySingleton {

    private static volatile MySingleton INSTANCE;

    @SuppressWarnings("UnusedAssignment")
    public static void initialize(
            final SomeDependency someDependency) {

        MySingleton result = INSTANCE;

        if (result != null) {
            throw new IllegalStateException("The singleton has already "
                    + "been initialized.");
        }

        synchronized (MySingleton.class) {
            result = INSTANCE;

            if (result == null) {
                INSTANCE = result = new MySingleton(someDependency);
            } 
        }
    }

    public static MySingleton get() {
        MySingleton  result = INSTANCE;

        if (result == null) {
            throw new IllegalStateException("The singleton has not been "
                    + "initialized. You must call initialize(...) before "
                    + "calling get()");
        }

       return result;
    }

    ...
}

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

List comprehension vs map

If you plan on writing any asynchronous, parallel, or distributed code, you will probably prefer map over a list comprehension -- as most asynchronous, parallel, or distributed packages provide a map function to overload python's map. Then by passing the appropriate map function to the rest of your code, you may not have to modify your original serial code to have it run in parallel (etc).

How to calculate age in T-SQL with years, months, and days

SELECT DOB AS Birthdate ,
       YEAR(GETDATE()) AS ThisYear,
       YEAR(getdate()) - YEAR(DOB) AS Age
FROM tableprincejain

How to detect when a UIScrollView has finished scrolling

On some earlier iOS versions(like iOS 9, 10), scrollViewDidEndDecelerating won't be triggered if the scrollView is suddenly stopped by touching.

But in the current version (iOS 13), scrollViewDidEndDecelerating will be triggered for sure (As far as I know).

So, if your App targeted earlier versions as well, you might need a workaround like the one mentioned by Ashley Smart, or you can the following one.


    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if !scrollView.isTracking, !scrollView.isDragging, !scrollView.isDecelerating { // 1
            scrollViewDidEndScrolling(scrollView)
        }
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate, scrollView.isTracking, !scrollView.isDragging, !scrollView.isDecelerating { // 2
            scrollViewDidEndScrolling(scrollView)
        }
    }

    func scrollViewDidEndScrolling(_ scrollView: UIScrollView) {
        // Do something here
    }

Explanation

UIScrollView will be stoped in three ways:
- quickly scrolled and stopped by itself
- quickly scrolled and stopped by finger touch (like Emergency brake)
- slowly scrolled and stopped

The first one can be detected by scrollViewDidEndDecelerating and other similar methods while the other two can't.

Luckily, UIScrollView has three statuses we can use to identify them, which is used in the two lines commented by "//1" and "//2".

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

How do I implement a progress bar in C#?

I have not compiled this as it is meant for a proof of concept. This is how I have implemented a Progress bar for database access in the past. This example shows access to a SQLite database using the System.Data.SQLite module

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{   
    // Get the BackgroundWorker that raised this event.
    BackgroundWorker worker = sender as BackgroundWorker;
    using(SQLiteConnection cnn = new SQLiteConnection("Data Source=MyDatabase.db"))
    {
        cnn.Open();
        int TotalQuerySize = GetQueryCount("Query", cnn); // This needs to be implemented and is not shown in example
        using (SQLiteCommand cmd = cnn.CreateCommand())
        {
            cmd.CommandText = "Query is here";
            using(SQLiteDataReader reader = cmd.ExecuteReader())
            {
                int i = 0;
                while(reader.Read())
                {
                    // Access the database data using the reader[].  Each .Read() provides the next Row
                    if(worker.WorkerReportsProgress) worker.ReportProgress(++i * 100/ TotalQuerySize);
                }
            }
        }
    }
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    this.progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // Notify someone that the database access is finished.  Do stuff to clean up if needed
    // This could be a good time to hide, clear or do somthign to the progress bar
}

public void AcessMySQLiteDatabase()
{
    BackgroundWorker backgroundWorker1 = new BackgroundWorker();
    backgroundWorker1.DoWork += 
        new DoWorkEventHandler(backgroundWorker1_DoWork);
    backgroundWorker1.RunWorkerCompleted += 
        new RunWorkerCompletedEventHandler(
    backgroundWorker1_RunWorkerCompleted);
    backgroundWorker1.ProgressChanged += 
        new ProgressChangedEventHandler(
    backgroundWorker1_ProgressChanged);
}

Google Play Services Missing in Emulator (Android 4.4.2)

Setp 1 : Download the following apk files. 1)com.google.android.gms.apk (https://androidfilehost.com/?fid=95916177934534438) 2)com.android.vending-4.4.22.apk (https://androidfilehost.com/?fid=23203820527945795)

Step 2 : Create a new AVD without the google API's

Step 3 : Run the AVD (Start the emulator)

Step 4 : Install the downloaded apks using adb .

     1)adb install com.google.android.gms-6.7.76_\(1745988-038\)-6776038-minAPI9.apk  
     2)adb install com.android.vending-4.4.22.apk

adb come up with android sdks/studio

Step 5 : Create the application in google developer console

Step 6 : Configure the api key in your Androidmanifest.xml and google api version.

Note : In step1 you need to download the apk based on your Android API level(..18,19,21..) and google play services version (5,5.1,6,6.5......)

This will work 100%.

Clearing a text field on button click

How about just a simple reset button?

<form>

  <input type="text" id="textfield1" size="5">
  <input type="text" id="textfield2" size="5">

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

</form>

Makefile - missing separator

You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

PROG = semsearch
all: $(PROG)
%: %.c
        gcc -o $@ $< -lpthread

clean:
        rm $(PROG)

Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread

clean: ; rm $(PROG)

Angular 2 Cannot find control with unspecified name attribute on formArrays

Instead of

formGroupName="i"

You must use:

[formGroupName]="i"

Tips:

Since you're looping over the controls, you've already the variable area, so you can replace this:

*ngIf="areasForm.get('areas').controls[i].name.hasError('required')"

by:

*ngIf="area.hasError('required', 'name')"

What is the size limit of a post request?

You can post large amount of data by setting php.ini variable: max_input_vars Default size of this variable is 1000 but if you want to sent large amount of data you have to increase the size accordingly. If you can't set the size from ini_set you have to do it through htaccess or by doing changes into php.ini file directly.

max_input_vars  2500
memory_limit    256M

tomcat - CATALINA_BASE and CATALINA_HOME variables

If you are running multiple instances of Tomcat on a single host you should set CATALINA_BASE to be equal to the .../tomcat_instance1 or .../tomcat_instance2 directory as appropriate for each instance and the CATALINA_HOME environment variable to the common Tomcat installation whose files will be shared between the two instances.

The CATALINA_BASE environment is optional if you are running a single Tomcat instance on the host and will default to CATALINA_HOME in that case. If you are running multiple instances as you are it should be provided.

There is a pretty good description of this setup in the RUNNING.txt file in the root of the Apache Tomcat distribution under the heading Advanced Configuration - Multiple Tomcat Instances

force line break in html table cell

It's hard to answer you without the HTML, but in general you can put:

style="width: 50%;"

On either the table cell, or place a div inside the table cell, and put the style on that.

But one problem is "50% of what?" It's 50% of the parent element which may not be what you want.

Post a copy of your HTML and maybe you'll get a better answer.

Switch tabs using Selenium WebDriver with Java

This is a simple solution for opening a new tab, changing focus to it, closing the tab and return focus to the old/original tab:

@Test
public void testTabs() {
    driver.get("https://business.twitter.com/start-advertising");
    assertStartAdvertising();

    // considering that there is only one tab opened in that point.
    String oldTab = driver.getWindowHandle();
    driver.findElement(By.linkText("Twitter Advertising Blog")).click();
    ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
    newTab.remove(oldTab);
    // change focus to new tab
    driver.switchTo().window(newTab.get(0));
    assertAdvertisingBlog();

    // Do what you want here, you are in the new tab

    driver.close();
    // change focus back to old tab
    driver.switchTo().window(oldTab);
    assertStartAdvertising();

    // Do what you want here, you are in the old tab
}

private void assertStartAdvertising() {
    assertEquals("Start Advertising | Twitter for Business", driver.getTitle());
}

private void assertAdvertisingBlog() {
    assertEquals("Twitter Advertising", driver.getTitle());
}

Select rows with same id but different value in another column

This ought to do it:

SELECT *
FROM YourTable
WHERE ARIDNR IN (
    SELECT ARIDNR
    FROM YourTable
    GROUP BY ARIDNR
    HAVING COUNT(*) > 1
)

The idea is to use the inner query to identify the records which have a ARIDNR value that occurs 1+ times in the data, then get all columns from the same table based on that set of values.

Regular Expression to select everything before and up to a particular text

After executing the below regex, your answer is in the first capture.

/^(.*?)\.txt/

How to tell if a file is git tracked (by shell exit code)?

If you don't want to clutter up your console with error messages, you can also run

git ls-files file_name

and then check the result. If git returns nothing, then the file is not tracked. If it's tracked, git will return the file path.

This comes in handy if you want to combine it in a script, for example PowerShell:

$gitResult = (git ls-files $_) | out-string
if ($gitResult.length -ne 0)
{
    ## do stuff with the tracked file
}

Space between Column's children in Flutter

Just use padding to wrap it like this:

Column(
  children: <Widget>[
  Padding(
    padding: EdgeInsets.all(8.0),
    child: Text('Hello World!'),
  ),
  Padding(
    padding: EdgeInsets.all(8.0),
    child: Text('Hello World2!'),
  )
]);

You can also use Container(padding...) or SizeBox(height: x.x). The last one is the most common but it will depents of how you want to manage the space of your widgets, I like to use padding if the space is part of the widget indeed and use sizebox for lists for example.

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

This error may be about password characters. If your password contains special characters and also you add your password into Transport class methods;

For Example

Transport transport = session.getTransport("smtp");
transport.connect("user","passw@rd");

or

Transport.send(msg, "user", "passw%rd");

you may get that error. Because Transport class' methods may not handle special characters. If you add your username and password into your message using javax.mail.PasswordAuthentication class, i hope you will escape that error;

For Example

...
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
  protected PasswordAuthentication getPasswordAuthentication()
  {
    return new PasswordAuthentication("user", "pas$w@r|d");
  }
});

Message message = new MimeMessage(session);
...
Transport.send(message);

How to read connection string in .NET Core?

This is how I did it:

I added the connection string at appsettings.json

"ConnectionStrings": {
"conStr": "Server=MYSERVER;Database=MYDB;Trusted_Connection=True;MultipleActiveResultSets=true"},

I created a class called SqlHelper

public class SqlHelper
{
    //this field gets initialized at Startup.cs
    public static string conStr;

    public static SqlConnection GetConnection()
    {
        try
        {
            SqlConnection connection = new SqlConnection(conStr);
            return connection;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}

At the Startup.cs I used ConfigurationExtensions.GetConnectionString to get the connection,and I assigned it to SqlHelper.conStr

public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        SqlHelper.connectionString = ConfigurationExtensions.GetConnectionString(this.Configuration, "conStr");
    }

Now wherever you need the connection string you just call it like this:

SqlHelper.GetConnection();

Gson: Is there an easier way to serialize a map

Map<String, Object> config = gson.fromJson(reader, Map.class);

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

Regex for not empty and not whitespace

/^$|\s+/ This matches when empty or white spaces

/(?!^$)([^\s])/ This matches when its not empty or white spaces

git with IntelliJ IDEA: Could not read from remote repository

Don't forget to contact your system administrator.

Because in my case I had every thing rightly configured(SSH also added) but I got the same error

repository access denied. fatal: Could not read from remote repository.

the reason was I only had read access to that repository. Therefore with out wasting your valuable time please check that as the first thing. Thank you.

Sending websocket ping/pong frame from browser

Ping is meant to be sent only from server to client, and browser should answer as soon as possible with Pong OpCode, automatically. So you have not to worry about that on higher level.

Although that not all browsers support standard as they suppose to, they might have some differences in implementing such mechanism, and it might even means there is no Pong response functionality. But personally I am using Ping / Pong, and never saw client that does not implement this type of OpCode and automatic response on low level client side implementation.

How to find and replace string?

void replace(char *str, char *strFnd, char *strRep)
{
    for (int i = 0; i < strlen(str); i++)
    {
        int npos = -1, j, k;
        if (str[i] == strFnd[0])
        {
            for (j = 1, k = i+1; j < strlen(strFnd); j++)
                if (str[k++] != strFnd[j])
                    break;
            npos = i;
        }
        if (npos != -1)
            for (j = 0, k = npos; j < strlen(strRep); j++)
                str[k++] = strRep[j];
    }

}

int main()
{
    char pst1[] = "There is a wrong message";
    char pfnd[] = "wrong";
    char prep[] = "right";

    cout << "\nintial:" << pst1;

    replace(pst1, pfnd, prep);

    cout << "\nfinal : " << pst1;
    return 0;
}

How can I enable auto complete support in Notepad++?

It is very easy:

  1. Find the XML file with unity keywords
  2. Copy only lines with "< KeyWord name="......" / > "
  3. Go to C:\Program Files\Notepad++\plugins\APIs and find cs.xml for example
  4. Paste what you copied in 1., but be careful: Don't delete any line of it cs.xml
  5. Save the file and enjoy autocompleting :)

Search for a string in Enum and return the Enum

As mentioned in previous answers, you can cast directly to the underlying datatype (int -> enum type) or parse (string -> enum type).

but beware - there is no .TryParse for enums, so you WILL need a try/catch block around the parse to catch failures.

Edittext change border color with shape.xml

Why using selector as the root tag? selector is used for applying multiple alternate drawables for different states of the view, so in this case, there is no need for selector.

Try the following code.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Background Color -->
    <solid android:color="#ffffff" />

    <!-- Border Color -->
    <stroke android:width="1dp" android:color="#ff9900" />

    <!-- Round Corners -->
    <corners android:radius="5dp" />

</shape>

Also It's worth mentioning that all color entries support alpha channel as well, meaning that you can have transparent or semi-transparent colors. For example #RRGGBBAA.

How can I display just a portion of an image in HTML/CSS?

adjust the background-position to move background images in different positions of the div

div { 
       background-image: url('image url')
       background-position: 0 -250px; 
    }

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Why are iframes considered dangerous and a security risk?

The IFRAME element may be a security risk if your site is embedded inside an IFRAME on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe> or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY and hope that the browser knows its job.

In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe> on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).

That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.

If somebody claims that using an <iframe> element on your site is dangerous and causes a security risk, he does not understand what <iframe> element does, or he is speaking about possibility of <iframe> related vulnerabilities in browsers. Security of <iframe src="..."> tag is equal to <img src="..." or <a href="..."> as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>, <img> or <a> element, so it's not worth considering for this issue.

However, be warned that content from <iframe> can initiate top level navigation by default. That is, content within the <iframe> is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox attribute without value allow-top-navigation. For example, <iframe sandbox="allow-forms allow-scripts" ...>. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.

Note that X-Frame-Options: DENY also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").

Are global variables bad?

Use of Global variables actually depends on the requirements. Its advantage is that,it reduces the overhead of passing the values repeatedly.

But your professor is right because it raises security issues so use of global variables should be avoided as much as possible. Global variables also create problems which are sometimes difficult to debug.

For example:-

Situations when the variables values is getting modified on runtime. At that moment its difficult to identify which part of code is modifying it and on what conditions.

Return datetime object of previous month

You could do it in two lines like this:

now = datetime.now()
last_month = datetime(now.year, now.month - 1, now.day)

remember the imports

from datetime import datetime

How to change sa password in SQL Server 2008 express?

I didn't know the existing sa password so this is what I did:

  1. Open Services in Control Panel

  2. Find the "SQL Server (SQLEXPRESS)" entry and select properties

  3. Stop the service

  4. Enter "-m" at the beginning of the "Start parameters" fields. If there are other parameters there already add a semi-colon after -m;

  5. Start the service

  6. Open a Command Prompt

Enter the command:

osql -S YourPcName\SQLEXPRESS -E

(change YourPcName to whatever your PC is called).

  1. At the prompt type the following commands:
alter login sa enable
go
sp_password NULL,'new_password','sa'
go
quit
  1. Stop the "SQL Server (SQLEXPRESS)" service

  2. Remove the "-m" from the Start parameters field

  3. Start the service

How to study design patterns?

I have found that it is a bit hard to comprehend or understand the benefits of some patterns until one understands the problems they solve and the other (worse) ways the problems have been implemented.

Other than the GOF and POSA books I have not really read any so I can't give you other recommendations. Really you just have to have an understanding of the problems domains and I think that many less experienced developers may not be able to appreciate the benefits of patterns. This is no slight against them. It is a lot easier to embrace, understand and appreciate good solutions when one has to struggle with poor alternatives first.

Good luck

Call Jquery function

To call the function on click of some html element (control).

$('#controlID').click(myFunction);

You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready

$(document).ready(function(){
    $('#controlID').click(myFunction);
});

You can use anonymous function to bind the event to the html element.

$(document).ready(function(){
    $('#controlID').click(function(){
         $.messager.show({  
            title:'My Title',  
            msg:'The message content',  
            showType:'fade',  
            style:{  
                right:'',  
                bottom:''  
            }  
        });  
    });
});

If you want to bind click with many elements you can use class selector

$('.someclass').click(myFunction);

Edit based on comments by OP, If you want to call function under some condition

You can use if for conditional execution, for example,

if(a == 3)
     myFunction();

How to get child element by index in Jquery?

You can get first element via index selector:

$('div.second div:eq(0)')

Code: http://jsfiddle.net/RX46D/

How to make a HTML Page in A4 paper size page(s)?

Ages ago, in November 2005, AlistApart.com published an article on how they published a book using nothing but HTML and CSS. See: http://alistapart.com/article/boom

Here's an excerpt of that article:

CSS2 has a notion of paged media (think sheets of paper), as opposed to continuous media (think scrollbars). Style sheets can set the size of pages and their margins. Page templates can be given names and elements can state which named page they want to be printed on. Also, elements in the source document can force page breaks. Here is a snippet from the style sheet we used:

@page {
   size: 7in 9.25in;
   margin: 27mm 16mm 27mm 16mm;
}

Having a US-based publisher, we were given the page size in inches. We, being Europeans, continued with metric measurements. CSS accepts both.

After setting the up the page size and margin, we needed to make sure there are page breaks in the right places. The following excerpt shows how page breaks are generated after chapters and appendices:

div.chapter, div.appendix {
    page-break-after: always;
}

Also, we used CSS2 to declare named pages:

div.titlepage {
  page: blank;
}

That is, the title page is to be printed on pages with the name “blank.” CSS2 described the concept of named pages, but their value only becomes apparent when headers and footers are available.

Anyway…

Since you want to print A4, you'll need different dimensions of course:

@page {
    size: 21cm 29.7cm;
    margin: 30mm 45mm 30mm 45mm;
     /* change the margins as you want them to be. */
}

The article dives into things like setting page-breaks, etc. so you might want to read that completely.

In your case, the trick is to create the print CSS first. Most modern browsers (>2005) support zooming and will already be able to display a website based on the print CSS.

Now, you'll want to make the web display look a bit different and adapt the whole design to fit most browsers too (including the old, pre 2005 ones). For that, you'll have to create a web CSS file or override some parts of your print CSS. When creating CSS for web display, remember that a browser can have ANY size (think: “mobile” up to “big-screen TVs”). Meaning: for the web CSS your page-width and image-width is best set using a variable width (%) to support as many display devices and web-browsing clients as possible.

EDIT (26-02-2015)

Today, I happened to stumble upon another, more recent article at SmashingMagazine which also dives into designing for print with HTML and CSS… just in case you could use yet-another-tutorial.

EDIT (30-10-2018)

It has been brought to my attention in that size is not valid CSS3, which is indeed correct — I merely repeated the code quoted in the article which (as noted) was good old CSS2 (which makes sense when you look at the year the article and this answer were first published). Anyway, here's the valid CSS3 code for your copy-and-paste convenience:

@media print {
    body{
        width: 21cm;
        height: 29.7cm;
        margin: 30mm 45mm 30mm 45mm; 
        /* change the margins as you want them to be. */
   } 
}

In case you think you really need pixels (you should actually avoid using pixels), you will have to take care of choosing the correct DPI for printing:

  • 72 dpi (web) = 595 X 842 pixels
  • 300 dpi (print) = 2480 X 3508 pixels
  • 600 dpi (high quality print) = 4960 X 7016 pixels

Yet, I would avoid the hassle and simply use cm (centimeters) or mm (millimeters) for sizing as that avoids rendering glitches that can arise depending on which client you use.

Creating a UICollectionView programmatically

Apple Docs:

- (id)initWithFrame:(CGRect)frame 
      collectionViewLayout:(UICollectionViewLayout *)layoutParameters

Use this method when initializing a collection view object programmatically. If you specify nil for the layout parameter, you must assign a layout object to the collectionViewLayout property before displaying the collection view onscreen. If you do not, the collection view will be unable to present any items onscreen.

This method is the designated initializer.

This method is used to initialize the UICollectionView. here you provide frame and a UICollectionViewLayout object.

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];

At the end, add UICollectionView as a subview to your view.

Now collection view is added pro grammatically. You can go on learning.
Happy learning!! Hope it helps you.

How can I wait for 10 second without locking application UI in android

You never want to call thread.sleep() on the UI thread as it sounds like you have figured out. This freezes the UI and is always a bad thing to do. You can use a separate Thread and postDelayed

This SO answer shows how to do that as well as several other options

Handler

TimerTask

You can look at these and see which will work best for your particular situation

Submit Button Image

It's very important for accessibility reasons that you always specify value of the submit even if you are hiding this text, or if you use <input type="image" .../> to always specify alt="" attribute for this input field.

Blind people don't know what button will do if it doesn't contain meaningful alt="" or value="".

Read XLSX file in Java

Aspose.Cells for Java supports XLSX format. You may find more details and further help in Aspose.Cells for Java Documentation. Please see if this helps.

Disclosure: I work as developer evangelist at Aspose.

Creating a Shopping Cart using only HTML/JavaScript

Here's a one page cart written in Javascript with localStorage. Here's a full working pen. Previously found on Codebox

cart.js

var cart = {
  // (A) PROPERTIES
  hPdt : null, // HTML products list
  hItems : null, // HTML current cart
  items : {}, // Current items in cart

  // (B) LOCALSTORAGE CART
  // (B1) SAVE CURRENT CART INTO LOCALSTORAGE
  save : function () {
    localStorage.setItem("cart", JSON.stringify(cart.items));
  },

  // (B2) LOAD CART FROM LOCALSTORAGE
  load : function () {
    cart.items = localStorage.getItem("cart");
    if (cart.items == null) { cart.items = {}; }
    else { cart.items = JSON.parse(cart.items); }
  },

  // (B3) EMPTY ENTIRE CART
  nuke : function () {
    if (confirm("Empty cart?")) {
      cart.items = {};
      localStorage.removeItem("cart");
      cart.list();
    }
  },

  // (C) INITIALIZE
  init : function () {
    // (C1) GET HTML ELEMENTS
    cart.hPdt = document.getElementById("cart-products");
    cart.hItems = document.getElementById("cart-items");

    // (C2) DRAW PRODUCTS LIST
    cart.hPdt.innerHTML = "";
    let p, item, part;
    for (let id in products) {
      // WRAPPER
      p = products[id];
      item = document.createElement("div");
      item.className = "p-item";
      cart.hPdt.appendChild(item);

      // PRODUCT IMAGE
      part = document.createElement("img");
      part.src = "images/" +p.img;
      part.className = "p-img";
      item.appendChild(part);

      // PRODUCT NAME
      part = document.createElement("div");
      part.innerHTML = p.name;
      part.className = "p-name";
      item.appendChild(part);

      // PRODUCT DESCRIPTION
      part = document.createElement("div");
      part.innerHTML = p.desc;
      part.className = "p-desc";
      item.appendChild(part);

      // PRODUCT PRICE
      part = document.createElement("div");
      part.innerHTML = "$" + p.price;
      part.className = "p-price";
      item.appendChild(part);

      // ADD TO CART
      part = document.createElement("input");
      part.type = "button";
      part.value = "Add to Cart";
      part.className = "cart p-add";
      part.onclick = cart.add;
      part.dataset.id = id;
      item.appendChild(part);
    }

    // (C3) LOAD CART FROM PREVIOUS SESSION
    cart.load();

    // (C4) LIST CURRENT CART ITEMS
    cart.list();
  },

  // (D) LIST CURRENT CART ITEMS (IN HTML)
  list : function () {
    // (D1) RESET
    cart.hItems.innerHTML = "";
    let item, part, pdt;
    let empty = true;
    for (let key in cart.items) {
      if(cart.items.hasOwnProperty(key)) { empty = false; break; }
    }

    // (D2) CART IS EMPTY
    if (empty) {
      item = document.createElement("div");
      item.innerHTML = "Cart is empty";
      cart.hItems.appendChild(item);
    }

    // (D3) CART IS NOT EMPTY - LIST ITEMS
    else {
      let p, total = 0, subtotal = 0;
      for (let id in cart.items) {
        // ITEM
        p = products[id];
        item = document.createElement("div");
        item.className = "c-item";
        cart.hItems.appendChild(item);

        // NAME
        part = document.createElement("div");
        part.innerHTML = p.name;
        part.className = "c-name";
        item.appendChild(part);

        // REMOVE
        part = document.createElement("input");
        part.type = "button";
        part.value = "X";
        part.dataset.id = id;
        part.className = "c-del cart";
        part.addEventListener("click", cart.remove);
        item.appendChild(part);

        // QUANTITY
        part = document.createElement("input");
        part.type = "number";
        part.value = cart.items[id];
        part.dataset.id = id;
        part.className = "c-qty";
        part.addEventListener("change", cart.change);
        item.appendChild(part);

        // SUBTOTAL
        subtotal = cart.items[id] * p.price;
        total += subtotal;
      }

      // EMPTY BUTTONS
      item = document.createElement("input");
      item.type = "button";
      item.value = "Empty";
      item.addEventListener("click", cart.nuke);
      item.className = "c-empty cart";
      cart.hItems.appendChild(item);

      // CHECKOUT BUTTONS
      item = document.createElement("input");
      item.type = "button";
      item.value = "Checkout - " + "$" + total;
      item.addEventListener("click", cart.checkout);
      item.className = "c-checkout cart";
      cart.hItems.appendChild(item);
    }
  },

  // (E) ADD ITEM INTO CART
  add : function () {
    if (cart.items[this.dataset.id] == undefined) {
      cart.items[this.dataset.id] = 1;
    } else {
      cart.items[this.dataset.id]++;
    }
    cart.save();
    cart.list();
  },

  // (F) CHANGE QUANTITY
  change : function () {
    if (this.value == 0) {
      delete cart.items[this.dataset.id];
    } else {
      cart.items[this.dataset.id] = this.value;
    }
    cart.save();
    cart.list();
  },
  
  // (G) REMOVE ITEM FROM CART
  remove : function () {
    delete cart.items[this.dataset.id];
    cart.save();
    cart.list();
  },
  
  // (H) CHECKOUT
  checkout : function () {
    // SEND DATA TO SERVER
    // CHECKS
    // SEND AN EMAIL
    // RECORD TO DATABASE
    // PAYMENT
    // WHATEVER IS REQUIRED
    alert("TO DO");

    /*
    var data = new FormData();
    data.append('cart', JSON.stringify(cart.items));
    data.append('products', JSON.stringify(products));
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "SERVER-SCRIPT");
    xhr.onload = function(){ ... };
    xhr.send(data);
    */
  }
};
window.addEventListener("DOMContentLoaded", cart.init);

Real-world examples of recursion

Suppose you are building a CMS for a website, where your pages are in a tree structure, with say the root being the home-page.

Suppose also your {user|client|customer|boss} requests that you place a breadcrumb trail on every page to show where you are in the tree.

For any given page n, you'll may want to walk up to the parent of n, and its parent, and so on, recursively to build a list of nodes back up to the root of page tree.

Of course, you're hitting the db several times per page in that example, so you may want to use some SQL aliasing where you look up page-table as a, and page-table again as b, and join a.id with b.parent so you make the database do the recursive joins. It's been a while, so my syntax is probably not helpful.

Then again, you may just want to only calculate this once and store it with the page record, only updating it if you move the page. That'd probably be more efficient.

Anyway, that's my $.02

How to parse a query string into a NameValueCollection in .NET

A lot of the answers are providing custom examples because of the accepted answer's dependency on System.Web. From the Microsoft.AspNet.WebApi.Client NuGet package there is a UriExtensions.ParseQueryString, method that can also be used:

var uri = new Uri("https://stackoverflow.com/a/22167748?p1=6&p2=7&p3=8");
NameValueCollection query = uri.ParseQueryString();

So if you want to avoid the System.Web dependency and don't want to roll your own, this is a good option.

ImportError: No module named 'Tkinter'

Make sure that when you are running your python code that it is in the python3 context. I had the same issue and all I had to do was input the command as:

sudo python3 REPLACE.py

versus

sudo python REPLACE.py

the latter code is incorrect because tkinter is apparently unnavailable in python1 or python2.

How do I send a POST request as a JSON?

This one works fine for me with apis

import requests

data={'Id':id ,'name': name}
r = requests.post( url = 'https://apiurllink', data = data)

C++ catching all exceptions

Well, if you would like to catch all exception to create a minidump for example...

Somebody did the work on Windows.

See http://www.codeproject.com/Articles/207464/Exception-Handling-in-Visual-Cplusplus In the article, he explains how he found out how to catch all kind of exceptions and he provides code that works.

Here is the list you can catch:

 SEH exception
 terminate
 unexpected
 pure virtual method call
 invalid parameter
 new operator fault 
 SIGABR
 SIGFPE
 SIGILL
 SIGINT
 SIGSEGV
 SIGTERM
 Raised exception
C++ typed exception

And the usage: CCrashHandler ch; ch.SetProcessExceptionHandlers(); // do this for one thread ch.SetThreadExceptionHandlers(); // for each thred


By default, this creates a minidump in the current directory (crashdump.dmp)

How display only years in input Bootstrap Datepicker?

For bootstrap datetimepicker, assign decade value as follow:

$(".years").datetimepicker({
    format: "yyyy",
    startView: 'decade',
    minView: 'decade',
    viewSelect: 'decade',
    autoclose: true,
});

Maintain image aspect ratio when changing height

Declare where display: flex; was given Element.
align-items: center;

Convert array of strings to List<string>

Just use this constructor of List<T>. It accepts any IEnumerable<T> as an argument.

string[] arr = ...
List<string> list = new List<string>(arr);

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

As a workaround you could add a handler to the ServicePointManager's ServerCertificateValidationCallback on the client side:

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
    (se, cert, chain, sslerror) =>
        {
            return true;
        };

but be aware that this is not a good practice as it completely ignores the server certificate and tells the service point manager that whatever certificate is fine which can seriously compromise client security. You could refine this and do some custom checking (for certificate name, hash etc). at least you can circumvent problems during development when using test certificates.

How to emulate a do-while loop in Python?

For me a typical while loop will be something like this:

xBool = True
# A counter to force a condition (eg. yCount = some integer value)

while xBool:
    # set up the condition (eg. if yCount > 0):
        (Do something)
        yCount = yCount - 1
    else:
        # (condition is not met, set xBool False)
        xBool = False

I could include a for..loop within the while loop as well, if situation so warrants, for looping through another set of condition.

How do I disable form fields using CSS?

input[name=username] { disabled: true; /* Does not work */ }

I know this question is quite old but for other users who come across this problem, I suppose the easiest way to disable input is simply by ':disabled'

<input type="text" name="username" value="admin" disabled />
<style type="text/css">
  input[name=username]:disabled {
    opacity: 0.5 !important; /* Fade effect */
    cursor: not-allowed; /* Cursor change to disabled state*/
  }
</style>

In reality, if you have some script to disable the input dynamically/automatically with javascript or jquery that would automatically disable based on the condition you add.

In jQuery for Example:

if (condition) {
// Make this input prop disabled state
  $('input').prop('disabled', true);
}
else {
// Do something else
}

Hope the answer in CSS helps.

How to turn off caching on Firefox?

Have you tried to use CTRL-F5 to update the page?

Using only CSS, show div on hover over <a>

For me, if I want to interact with the hidden div without seeing it disappear each time I leave the triggering element (a in that case) I must add:

div:hover {
    display: block;
}

Ruby function to remove all white spaces?

It's a bit late, but anyone else googling this page might be interested in this version -

If you want to clean up a chunk of pre-formatted text that a user may have cut & pasted into your app somehow, but preserve the word spacing, try this:

content = "      a big nasty          chunk of     something

that's been pasted                        from a webpage       or something        and looks 

like      this

"

content.gsub(/\s+/, " ").strip

#=> "a big nasty chunk of something that's been pasted from a webpage or something and looks like this"

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

CSS submit button weird rendering on iPad/iPhone

The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)

-webkit-appearance:none;
opacity: 1

After setting the opacity, the button looked the same on all the different devices/emulator/desktop.

Multiplying across in a numpy array

I've compared the different options for speed and found that – much to my surprise – all options (except diag) are equally fast. I personally use

A * b[:, None]

(or (A.T * b).T) because it's short.

enter image description here


Code to reproduce the plot:

import numpy
import perfplot


def newaxis(data):
    A, b = data
    return A * b[:, numpy.newaxis]


def none(data):
    A, b = data
    return A * b[:, None]


def double_transpose(data):
    A, b = data
    return (A.T * b).T


def double_transpose_contiguous(data):
    A, b = data
    return numpy.ascontiguousarray((A.T * b).T)


def diag_dot(data):
    A, b = data
    return numpy.dot(numpy.diag(b), A)


def einsum(data):
    A, b = data
    return numpy.einsum("ij,i->ij", A, b)


perfplot.save(
    "p.png",
    setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n)),
    kernels=[
        newaxis,
        none,
        double_transpose,
        double_transpose_contiguous,
        diag_dot,
        einsum,
    ],
    n_range=[2 ** k for k in range(13)],
    xlabel="len(A), len(b)",
)

top nav bar blocking top content of the page

with navbar navbar-default everything works fine, but if you are using navbar-fixed-top you have to include custom style body { padding-top: 60px;} otherwise it will block content underneath.

CORS Access-Control-Allow-Headers wildcard being ignored?

Those CORS headers do not support * as value, the only way is to replace * with this:

Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With


.htaccess Example (CORS Included):

<IfModule mod_headers.c>
  Header unset Connection
  Header unset Time-Zone
  Header unset Keep-Alive
  Header unset Access-Control-Allow-Origin
  Header unset Access-Control-Allow-Headers
  Header unset Access-Control-Expose-Headers
  Header unset Access-Control-Allow-Methods
  Header unset Access-Control-Allow-Credentials

  Header set   Connection                         keep-alive
  Header set   Time-Zone                          "Asia/Jerusalem"
  Header set   Keep-Alive                         timeout=100,max=500
  Header set   Access-Control-Allow-Origin        "*"
  Header set   Access-Control-Allow-Headers       "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Expose-Headers      "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Allow-Methods       "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
  Header set   Access-Control-Allow-Credentials   "true"

  Header set DNT "0"
  Header set Accept-Ranges "bytes"
  Header set Vary "Accept-Encoding"
  Header set X-UA-Compatible "IE=edge,chrome=1"
  Header set X-Frame-Options "SAMEORIGIN"
  Header set X-Content-Type-Options "nosniff"
  Header set X-Xss-Protection "1; mode=block"
</IfModule>

F.A.Q:

  • Why Access-Control-Allow-Headers, Access-Control-Expose-Headers, Access-Control-Allow-Methods values are super long?

    Those do not support the * syntax, so I've collected the most common (and exotic) headers from around the web, in various formats #1 #2 #3 (and I will update the list from time to time)

  • Why do you use Header unset ______ syntax?

    GoDaddy servers (which my website is hosted on..) have a weird bug where if the headers are already set, the previous value will join the existing one.. (instead of replacing it) this way I "pre-clean" existing values (really just a a quick && dirty solution)

  • Is it safe for me to use 'as-is'?

    Well.. mostly the answer would be YES since the .htaccess is limiting the headers to the scripts (PHP, HTML, ...) and resources (.JPG, .JS, .CSS) served from the following "folder"-location. You optionally might want to remove the Access-Control-Allow-Methods lines. Also Connection, Time-Zone, Keep-Alive and DNT, Accept-Ranges, Vary, X-UA-Compatible, X-Frame-Options, X-Content-Type-Options and X-Xss-Protection are just a suggestion I'm using for my online-service.. feel free to remove those too...

taken from my comment above

Bootstrap 4: Multilevel Dropdown Inside Navigation

Using official HTML without adding extra CSS styles and classes, it's like native support.

Just add the following code:

$.fn.dropdown = (function() {
    var $bsDropdown = $.fn.dropdown;
    return function(config) {
        if (typeof config === 'string' && config === 'toggle') { // dropdown toggle trigged
            $('.has-child-dropdown-show').removeClass('has-child-dropdown-show');
            $(this).closest('.dropdown').parents('.dropdown').addClass('has-child-dropdown-show');
        }
        var ret = $bsDropdown.call($(this), config);
        $(this).off('click.bs.dropdown'); // Turn off dropdown.js click event, it will call 'this.toggle()' internal
        return ret;
    }
})();

$(function() {
    $('.dropdown [data-toggle="dropdown"]').on('click', function(e) {
        $(this).dropdown('toggle');
        e.stopPropagation();
    });
    $('.dropdown').on('hide.bs.dropdown', function(e) {
        if ($(this).is('.has-child-dropdown-show')) {
            $(this).removeClass('has-child-dropdown-show');
            e.preventDefault();
        }
        e.stopPropagation();
    });
});

Dropdown of bootstrap can be easily changed to infinite level. It's a pity that they didn't do it.

BTW, a hover version: https://github.com/dallaslu/bootstrap-4-multi-level-dropdown

Here is a perfect demo: https://jsfiddle.net/dallaslu/adky6jvs/ (works well with Bootstrap v4.4.1)

Can I remove the URL from my print css, so the web address doesn't print?

@media print 
{
  a[href]:after { content: none !important; }
  img[src]:after { content: none !important; }
}

Find which version of package is installed with pip

There's also a tool called pip-check which gives you a quick overview of all installed packages and their update status:

enter image description here

Haven't used it myself; just stumbled upon it and this SO question in quick succession, and since it wasn't mentioned...

Java current machine name and logged in user?

To get the currently logged in user:

System.getProperty("user.name"); //platform independent 

and the hostname of the machine:

java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());

How to detect a remote side socket close?

You can also check for socket output stream error while writing to client socket.

out.println(output);
if(out.checkError())
{
    throw new Exception("Error transmitting data.");
}

Is it possible to style html5 audio tag?

You have to create your own player that interfaces with the HTML5 audio element. This tutorial will help http://alexkatz.me/html5-audio/building-a-custom-html5-audio-player-with-javascript/

Sass .scss: Nesting and multiple classes?

You can use the parent selector reference &, it will be replaced by the parent selector after compilation:

For your example:

.container {
    background:red;
    &.desc{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
.container.desc {
    background: blue;
}

The & will completely resolve, so if your parent selector is nested itself, the nesting will be resolved before replacing the &.

This notation is most often used to write pseudo-elements and -classes:

.element{
    &:hover{ ... }
    &:nth-child(1){ ... }
}

However, you can place the & at virtually any position you like*, so the following is possible too:

.container {
    background:red;
    #id &{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
#id .container {
    background: blue;
}

However be aware, that this somehow breaks your nesting structure and thus may increase the effort of finding a specific rule in your stylesheet.

*: No other characters than whitespaces are allowed in front of the &. So you cannot do a direct concatenation of selector+& - #id& would throw an error.

Finding an item in a List<> using C#

item = objects.Find(obj => obj.property==myValue);

How to set cellpadding and cellspacing in table with CSS?

The padding inside a table-divider (TD) is a padding property applied to the cell itself.

CSS

td, th {padding:0}

The spacing in-between the table-dividers is a space between cell borders of the TABLE. To make it effective, you have to specify if your table cells borders will 'collapse' or be 'separated'.

CSS

table, td, th {border-collapse:separate}
table {border-spacing:6px}

Try this : https://www.google.ca/search?num=100&newwindow=1&q=css+table+cellspacing+cellpadding+site%3Astackoverflow.com ( 27 100 results )

TypeScript static classes

Defining static properties and methods of a class is described in 8.2.1 of the Typescript Language Specification:

class Point { 
  constructor(public x: number, public y: number) { 
    throw new Error('cannot instantiate using a static class');
  } 
  public distance(p: Point) { 
    var dx = this.x - p.x; 
    var dy = this.y - p.y; 
    return Math.sqrt(dx * dx + dy * dy); 
  } 
  static origin = new Point(0, 0); 
  static distance(p1: Point, p2: Point) { 
    return p1.distance(p2); 
  } 
}

where Point.distance() is a static (or "class") method.

Consider marking event handler as 'passive' to make the page more responsive

For those receiving this warning for the first time, it is due to a bleeding edge feature called Passive Event Listeners that has been implemented in browsers fairly recently (summer 2016). From https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md:

Passive event listeners are a new feature in the DOM spec that enable developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners. Developers can annotate touch and wheel listeners with {passive: true} to indicate that they will never invoke preventDefault. This feature shipped in Chrome 51, Firefox 49 and landed in WebKit. For full official explanation read more here.

See also: What are passive event listeners?

You may have to wait for your .js library to implement support.

If you are handling events indirectly via a JavaScript library, you may be at the mercy of that particular library's support for the feature. As of December 2019, it does not look like any of the major libraries have implemented support. Some examples:

LaTeX source code listing like in professional books

I wonder why nobody mentioned the Minted package. It has far better syntax highlighting than the LaTeX listing package. It uses Pygments.

$ pip install Pygments

Example in LaTeX:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage{minted}

\begin{document}
\begin{minted}{python}
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1) 

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{minted}
\end{document}

Which results in:

enter image description here

You need to use the flag -shell-escape with the pdflatex command.

For more information: https://www.sharelatex.com/learn/Code_Highlighting_with_minted

What is the closest thing Windows has to fork()?

There is no easy way to emulate fork() on Windows.

I suggest you to use threads instead.

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   position:relative;
   margin-top:10px;
   margin-left:10px;
   background-color:red;
   width:210px;
   padding: 5px;
}

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

Unless your application has specially needs, I think you have 2 approaches:

  1. Do not use session at all
  2. Use session as is and perform fine tuning as joel mentioned.

Session is not only thread-safe but also state-safe, in a way that you know that until the current request is completed, every session variable wont change from another active request. In order for this to happen you must ensure that session WILL BE LOCKED until the current request have completed.

You can create a session like behavior by many ways, but if it does not lock the current session, it wont be 'session'.

For the specific problems you mentioned I think you should check HttpContext.Current.Response.IsClientConnected. This can be useful to to prevent unnecessary executions and waits on the client, although it cannot solve this problem entirely, as this can be used only by a pooling way and not async.

How do I vertically align something inside a span tag?

Use line-height:50px; instead of height. That should do the trick ;)

Spring Boot application.properties value not populating

The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.

You need to do one of the following:

Better solution

@Component
public class MyBean {

    private final String prop;

    @Autowired
    public MyBean(@Value("${some.prop}") String prop) {
        this.prop = prop;
        System.out.println("================== " + prop + "================== ");
    }
}

Solution that will work but is less testable and slightly less readable

@Component
public class MyBean {

    @Value("${some.prop}")
    private String prop;

    public MyBean() {

    }

    @PostConstruct
    public void init() {
        System.out.println("================== " + prop + "================== ");
    }
}

Also note that is not Spring Boot specific but applies to any Spring application

In Java, should I escape a single quotation mark (') in String (double quoted)?

It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!

The only times you should need to escape are when trying to put " inside a string, or ' in a character:

String quotes = "He said \"Hello, World!\"";
char quote = '\'';

C# Help reading foreign characters using StreamReader

For swedish Å Ä Ö the only solution form the ones above working was:

Encoding.GetEncoding("iso-8859-1")

Hopefully this will save someone time.

Git Server Like GitHub?

You can even install GitHub on your local server (but not for free):

https://enterprise.github.com/

Singleton in Android

You are copying singleton's customVar into a singletonVar variable and changing that variable does not affect the original value in singleton.

// This does not update singleton variable
// It just assigns value of your local variable
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);

// This actually assigns value of variable in singleton
Singleton.customVar = singletonVar;

How to implement a ViewPager with different Fragments / Layouts

As this is a very frequently asked question, I wanted to take the time and effort to explain the ViewPager with multiple Fragments and Layouts in detail. Here you go.

ViewPager with multiple Fragments and Layout files - How To

The following is a complete example of how to implement a ViewPager with different fragment Types and different layout files.

In this case, I have 3 Fragment classes, and a different layout file for each class. In order to keep things simple, the fragment-layouts only differ in their background color. Of course, any layout-file can be used for the Fragments.

FirstFragment.java has a orange background layout, SecondFragment.java has a green background layout and ThirdFragment.java has a red background layout. Furthermore, each Fragment displays a different text, depending on which class it is from and which instance it is.

Also be aware that I am using the support-library's Fragment: android.support.v4.app.Fragment

MainActivity.java (Initializes the Viewpager and has the adapter for it as an inner class). Again have a look at the imports. I am using the android.support.v4 package.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {

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

        ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int pos) {
            switch(pos) {

            case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
            case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
            case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
            case 3: return ThirdFragment.newInstance("ThirdFragment, Instance 2");
            case 4: return ThirdFragment.newInstance("ThirdFragment, Instance 3");
            default: return ThirdFragment.newInstance("ThirdFragment, Default");
            }
        }

        @Override
        public int getCount() {
            return 5;
        }       
    }
}

activity_main.xml (The MainActivitys .xml file) - a simple layout file, only containing the ViewPager that fills the whole screen.

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

The Fragment classes, FirstFragment.java import android.support.v4.app.Fragment;

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.first_frag, container, false);

        TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
        tv.setText(getArguments().getString("msg"));

        return v;
    }

    public static FirstFragment newInstance(String text) {

        FirstFragment f = new FirstFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }
}

first_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_orange_dark" >

    <TextView
        android:id="@+id/tvFragFirst"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />
</RelativeLayout>

SecondFragment.java

public class SecondFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.second_frag, container, false);

    TextView tv = (TextView) v.findViewById(R.id.tvFragSecond);
    tv.setText(getArguments().getString("msg"));

    return v;
}

public static SecondFragment newInstance(String text) {

    SecondFragment f = new SecondFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);

    f.setArguments(b);

    return f;
}
}

second_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_green_dark" >

    <TextView
        android:id="@+id/tvFragSecond"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />

</RelativeLayout>

ThirdFragment.java

public class ThirdFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.third_frag, container, false);

    TextView tv = (TextView) v.findViewById(R.id.tvFragThird);      
    tv.setText(getArguments().getString("msg"));

    return v;
}

public static ThirdFragment newInstance(String text) {

    ThirdFragment f = new ThirdFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);

    f.setArguments(b);

    return f;
}
}

third_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_light" >

    <TextView
        android:id="@+id/tvFragThird"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />

</RelativeLayout>

The end result is the following:

The Viewpager holds 5 Fragments, Fragments 1 is of type FirstFragment, and displays the first_frag.xml layout, Fragment 2 is of type SecondFragment and displays the second_frag.xml, and Fragment 3-5 are of type ThirdFragment and all display the third_frag.xml.

enter image description here

Above you can see the 5 Fragments between which can be switched via swipe to the left or right. Only one Fragment can be displayed at the same time of course.

Last but not least:

I would recommend that you use an empty constructor in each of your Fragment classes.

Instead of handing over potential parameters via constructor, use the newInstance(...) method and the Bundle for handing over parameters.

This way if detached and re-attached the object state can be stored through the arguments. Much like Bundles attached to Intents.

How can I view all historical changes to a file in SVN

Slightly different from what you described, but I think this might be what you actually need:

svn blame filename

It will print the file with each line prefixed by the time and author of the commit that last changed it.

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

Like Robin Winslow says in a comment :

I found my solution over here: stackoverflow.com/a/5178444/613540

In my case, my complete error message was :

/usr/bin/ld: cannot find -lz 
collect2: error: ld returned 1 exit status
error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

I was trying to install torrench :

sudo python3 setup.py install

With given stackoverflow link, I solve this issue by :

sudo apt install zlib1g-dev

Note that the following packages were already installed :

libxslt1-dev is already the newest version.
python3-dev is already the newest version.
libxml2-dev is already the newest version.

Hope that will help !

How to COUNT rows within EntityFramework without loading contents?

I think you want something like

var count = context.MyTable.Count(t => t.MyContainer.ID == '1');

(edited to reflect comments)

Google Map API v3 ~ Simply Close an infowindow?

With the v3 API, you can easily close the InfoWindow with the InfoWindow.close() method. You simply need to keep a reference to the InfoWindow object that you are using. Consider the following example, which opens up an InfoWindow and closes it after 5 seconds:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
  <title>Google Maps API InfoWindow Demo</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 400px; height: 500px;"></div>

  <script type="text/javascript">
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: new google.maps.LatLng(-25.36388, 131.04492),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      map: map
    });

    var infowindow = new google.maps.InfoWindow({
      content: 'An InfoWindow'
    });

    infowindow.open(map, marker);

    setTimeout(function () { infowindow.close(); }, 5000);
  </script>
</body>
</html>

If you have a separate InfoWindow object for each Marker, you may want to consider adding the InfoWindow object as a property of your Marker objects:

var marker = new google.maps.Marker({
  position: map.getCenter(),
   map: map
});

marker.infowindow = new google.maps.InfoWindow({
  content: 'An InfoWindow'
});

Then you would be able to open and close that InfoWindow as follows:

marker.infowindow.open(map, marker);
marker.infowindow.close();

The same applies if you have an array of markers:

var markers = [];

marker[0] = new google.maps.Marker({
  position: map.getCenter(),
   map: map
});

marker[0].infowindow = new google.maps.InfoWindow({
  content: 'An InfoWindow'
});

// ...

marker[0].infowindow.open(map, marker);
marker[0].infowindow.close();

Importing files from different folder

The answers here are lacking in clarity, this is tested on Python 3.6

With this folder structure:

main.py
|
---- myfolder/myfile.py

Where myfile.py has the content:

def myfunc():
    print('hello')

The import statement in main.py is:

from myfolder.myfile import myfunc
myfunc()

and this will print hello.

No signing certificate "iOS Distribution" found

enter image description here

Solution Steps:

  1. Unchecked "Automatically manage signing".

  2. Select "Provisioning profile" in "Signing (Release)" section.

  3. No signing certificate error will be show.

  4. Then below the error has a "Manage Certificates" button. click the button.

enter image description here

  1. This window will come. Click the + sign and click "iOS Distribution". xcode will create the private key for your distribution certificate and error will be gone.

How to use LINQ Distinct() with multiple fields

I assume that you use distinct like a method call on a list. You need to use the result of the query as datasource for your DropDownList, for example by materializing it via ToList.

var distinctCategories = product
                        .Select(m => new {m.CategoryId, m.CategoryName})
                        .Distinct()
                        .ToList();
DropDownList1.DataSource     = distinctCategories;
DropDownList1.DataTextField  = "CategoryName";
DropDownList1.DataValueField = "CategoryId";

Another way if you need the real objects instead of the anonymous type with only few properties is to use GroupBy with an anonymous type:

List<Product> distinctProductList = product
    .GroupBy(m => new {m.CategoryId, m.CategoryName})
    .Select(group => group.First())  // instead of First you can also apply your logic here what you want to take, for example an OrderBy
    .ToList();

A third option is to use MoreLinq's DistinctBy.

Synchronous Requests in Node.js

The short answer is: don't. If you want code that reads linearly, use a library like seq. But just don't expect synchronous. You really can't. And that's a good thing.

There's little or nothing that can't be put in a callback. If they depend on common variables, create a closure to contain them. What's the actual task at hand?

You'd want to have a counter, and only call the callback when the data is there:

var waiting = 2;
request( {url: base + u_ext}, function( err, res, body ) {
    var split1 = body.split("\n");
    var split2 = split1[1].split(", ");
    ucomp = split2[1];
    if(--waiting == 0) callback();
});

request( {url: base + v_ext}, function( err, res, body ) {
    var split1 = body.split("\n");
    var split2 = split1[1].split(", ");
    vcomp = split2[1];
    if(--waiting == 0) callback();
});

function callback() {
    // do math here.
}

Update 2018: node.js supports async/await keywords in recent editions, and with libraries that represent asynchronous processes as promises, you can await them. You get linear, sequential flow through your program, and other work can progress while you await. It's pretty well built and worth a try.

SQL How to remove duplicates within select query?

Select Distinct CAST(FLOOR( CAST(start_date AS FLOAT ) )AS DATETIME) from Table

ALTER DATABASE failed because a lock could not be placed on database

I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn't able to use any of the alter database commands because an exclusive lock couldn't be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

Capturing a form submit with jquery and .submit

Wrap the code in document ready and prevent the default submit action:

$(function() { //shorthand document.ready function
    $('#login_form').on('submit', function(e) { //use on if jQuery 1.7+
        e.preventDefault();  //prevent form from submitting
        var data = $("#login_form :input").serializeArray();
        console.log(data); //use the console for debugging, F12 in Chrome, not alerts
    });
});

"Prevent saving changes that require the table to be re-created" negative effects

SQL Server drops and recreates the tables only if you:

  • Add a new column
  • Change the Allow Nulls setting for a column
  • Change the column order in the table
  • Change the column data type

Using ALTER is safer, as in case the metadata is lost while you re-create the table, your data will be lost.

Java: method to get position of a match in a String?

You can get all matches in a file simply by assigning inside while-loop, cool:

$ javac MatchTest.java 
$ java MatchTest 
1
16
31
46
$ cat MatchTest.java 
import java.util.*;
import java.io.*;

public class MatchTest {
    public static void main(String[] args){
        String match = "hello";
        String text = "hello0123456789hello0123456789hello1234567890hello3423243423232";
        int i =0;
        while((i=(text.indexOf(match,i)+1))>0)
            System.out.println(i);
    }
}

How to create a signed APK file using Cordova command line interface?

On Mac (osx), I generated two .sh files, one for the first publication and another one for updating :

#!/bin/sh
echo "Ionic to Signed APK ---- [email protected] // Benjamin Rathelot\n"
printf "Project dir : "
read DIR
printf "Project key alias : "
read ALIAS
cd $DIR/
cordova build --release android
cd platforms/android/build/outputs/apk/
keytool -genkey -v -keystore my-release-key.keystore -alias $ALIAS -keyalg RSA -keysize 2048 -validity 10000
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore android-release-unsigned.apk $ALIAS
zipalign -v 4 android-release-unsigned.apk signedApk.apk

And to update your app:

#!/bin/sh
echo "Ionic to Signed APK ---- [email protected] // Benjamin Rathelot\n"
printf "Project dir : "
read DIR
printf "Project key alias : "
read ALIAS
cd $DIR/
cordova build --release android
cd platforms/android/build/outputs/apk/
rm signedApk.apk
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore android-release-unsigned.apk $ALIAS
zipalign -v 4 android-release-unsigned.apk signedApk.apk

Assuming you're in your home folder or a folder topping your apps folders. Make sure to set correctly chmod to use this script. Then :

./ionicToApk.sh # or whatever depending of the name of your file, in CLI

Your signed apk will be in Your App folder/platforms/android/build/outputs/apk/ as SignedApk.apk Make sure to use the correct key alias and password defined with the first script

How can I get a list of users from active directory?

Include the System.DirectoryServices.dll, then use the code below:

DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";

foreach (DirectoryEntry child in directoryEntry.Children)
{
    if (child.SchemaClassName == "User")
    {
        userNames += child.Name + Environment.NewLine   ;         
    }

}
MessageBox.Show(userNames);

Can you call Directory.GetFiles() with multiple filters?

There is also a descent solution which seems not to have any memory or performance overhead and be quite elegant:

string[] filters = new[]{"*.jpg", "*.png", "*.gif"};
string[] filePaths = filters.SelectMany(f => Directory.GetFiles(basePath, f)).ToArray();

Drop data frame columns by name

within(df, rm(x))

is probably easiest, or for multiple variables:

within(df, rm(x, y))

Or if you're dealing with data.tables (per How do you delete a column by name in data.table?):

dt[, x := NULL]   # Deletes column x by reference instantly.

dt[, !"x"]   # Selects all but x into a new data.table.

or for multiple variables

dt[, c("x","y") := NULL]

dt[, !c("x", "y")]

Concat a string to SELECT * MySql

You cannot concatenate multiple fields with a string. You need to select a field instand of all (*).

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

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

My solution is a bit funny.I never thought that would it be as easy as save as with UTF-8 codec.I'm using notepad++(v5.6.8).I didn't notice that I saved it with ANSI codec initially. I'm using separate file to place all localized dictionary. I found my solution under 'Encoding' tab from my Notepad++.I select 'Encoding in UTF-8 without BOM' and save it. It works brilliantly.

What is the difference between `git merge` and `git merge --no-ff`?

Graphic answer to this question

Here is a site with a clear explanation and graphical illustration of using git merge --no-ff:

difference between git merge --no-ff and git merge

Until I saw this, I was completely lost with git. Using --no-ff allows someone reviewing history to clearly see the branch you checked out to work on. (that link points to github's "network" visualization tool) And here is another great reference with illustrations. This reference complements the first one nicely with more of a focus on those less acquainted with git.


Basic info for newbs like me

If you are like me, and not a Git-guru, my answer here describes handling the deletion of files from git's tracking without deleting them from the local filesystem, which seems poorly documented but often occurrence. Another newb situation is getting current code, which still manages to elude me.


Example Workflow

I updated a package to my website and had to go back to my notes to see my workflow; I thought it useful to add an example to this answer.

My workflow of git commands:

git checkout -b contact-form
(do your work on "contact-form")
git status
git commit -am  "updated form in contact module"
git checkout master
git merge --no-ff contact-form
git branch -d contact-form
git push origin master

Below: actual usage, including explanations.
Note: the output below is snipped; git is quite verbose.

$ git status
# On branch master
# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   ecc/Desktop.php
#       modified:   ecc/Mobile.php
#       deleted:    ecc/ecc-config.php
#       modified:   ecc/readme.txt
#       modified:   ecc/test.php
#       deleted:    passthru-adapter.igs
#       deleted:    shop/mickey/index.php
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       ecc/upgrade.php
#       ecc/webgility-config.php
#       ecc/webgility-config.php.bak
#       ecc/webgility-magento.php

Notice 3 things from above:
1) In the output you can see the changes from the ECC package's upgrade, including the addition of new files.
2) Also notice there are two files (not in the /ecc folder) I deleted independent of this change. Instead of confusing those file deletions with ecc, I'll make a different cleanup branch later to reflect those files' deletion.
3) I didn't follow my workflow! I forgot about git while I was trying to get ecc working again.

Below: rather than do the all-inclusive git commit -am "updated ecc package" I normally would, I only wanted to add the files in the /ecc folder. Those deleted files weren't specifically part of my git add, but because they already were tracked in git, I need to remove them from this branch's commit:

$ git checkout -b ecc
$ git add ecc/*
$ git reset HEAD passthru-adapter.igs
$ git reset HEAD shop/mickey/index.php
Unstaged changes after reset:
M       passthru-adapter.igs
M       shop/mickey/index.php

$ git commit -m "Webgility ecc desktop connector files; integrates with Quickbooks"

$ git checkout master
D       passthru-adapter.igs
D       shop/mickey/index.php
Switched to branch 'master'
$ git merge --no-ff ecc
$ git branch -d ecc
Deleted branch ecc (was 98269a2).
$ git push origin master
Counting objects: 22, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (14/14), 59.00 KiB, done.
Total 14 (delta 10), reused 0 (delta 0)
To [email protected]:me/mywebsite.git
   8a0d9ec..333eff5  master -> master



Script for automating the above

Having used this process 10+ times in a day, I have taken to writing batch scripts to execute the commands, so I made an almost-proper git_update.sh <branch> <"commit message"> script for doing the above steps. Here is the Gist source for that script.

Instead of git commit -am I am selecting files from the "modified" list produced via git status and then pasting those in this script. This came about because I made dozens of edits but wanted varied branch names to help group the changes.

Execute Python script via crontab

Just use crontab -e and follow the tutorial here.

Look at point 3 for a guide on how to specify the frequency.

Based on your requirement, it should effectively be:

*/10 * * * * /usr/bin/python script.py

Refresh or force redraw the fragment

This worked for me from within Fragment:

Fragment frg = null;
Class fragmentClass;
fragmentClass = MainFragment.class;

try {
    frg = (android.support.v4.app.Fragment)     
    fragmentClass.newInstance();
} catch(Exception ex) {
    ex.printStackTrace();
}

getFragmentManager()
    .beginTransaction()
    .replace(R.id.flContent, frg)
    .commit();

Watch multiple $scope attributes

Starting from AngularJS 1.3 there's a new method called $watchGroup for observing a set of expressions.

$scope.foo = 'foo';
$scope.bar = 'bar';

$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
  // newValues array contains the current values of the watch expressions
  // with the indexes matching those of the watchExpression array
  // i.e.
  // newValues[0] -> $scope.foo 
  // and 
  // newValues[1] -> $scope.bar 
});

Using sed to mass rename files

Using perl rename (a must have in the toolbox):

rename -n 's/0000/000/' F0000*

Remove -n switch when the output looks good to rename for real.

warning There are other tools with the same name which may or may not be able to do this, so be careful.

The rename command that is part of the util-linux package, won't.

If you run the following command (GNU)

$ rename

and you see perlexpr, then this seems to be the right tool.

If not, to make it the default (usually already the case) on Debian and derivative like Ubuntu :

$ sudo apt install rename
$ sudo update-alternatives --set rename /usr/bin/file-rename

For archlinux:

pacman -S perl-rename

For RedHat-family distros:

yum install prename

The 'prename' package is in the EPEL repository.


For Gentoo:

emerge dev-perl/rename

For *BSD:

pkg install gprename

or p5-File-Rename


For Mac users:

brew install rename

If you don't have this command with another distro, search your package manager to install it or do it manually:

cpan -i File::Rename

Old standalone version can be found here


man rename


This tool was originally written by Larry Wall, the Perl's dad.

Tool to Unminify / Decompress JavaScript

I'm not sure if you need source code. There is a free online JavaScript formatter at http://www.blackbeltcoder.com/Resources/JSFormatter.aspx.

SQL Server Profiler - How to filter trace to only display events from one database?

In SQL 2005, you first need to show the Database Name column in your trace. The easiest thing to do is to pick the Tuning template, which has that column added already.

Assuming you have the Tuning template selected, to filter:

  • Click the "Events Selection" tab
  • Click the "Column Filters" button
  • Check Show all Columns (Right Side Down)
  • Select "DatabaseName", click the plus next to Like in the right-hand pane, and type your database name.

I always save the trace to a table too so I can do LIKE queries on the trace data after the fact.

How to get JSON response from http.Get

The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Tracks struct {
    Toptracks []Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  []Attr_info
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []Streamable_info
    Artist     []Artist_info
    Attr       []Track_attr_info
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "&limit=1" // limit data for testing
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var data interface{} // TopTracks
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Output:

Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

It seems like it exists a bug in jQuery reported here : http://bugs.jquery.com/ticket/13183 that breaks the Fancybox script.

Also check https://github.com/fancyapps/fancyBox/issues/485 for further reference.

As a workaround, rollback to jQuery v1.8.3 while either the jQuery bug is fixed or Fancybox is patched.


UPDATE (Jan 16, 2013): Fancybox v2.1.4 has been released and now it works fine with jQuery v1.9.0.

For fancybox v1.3.4- you still need to rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.


UPDATE (Jan 17, 2013): Workaround for users of Fancybox v1.3.4 :

Patch the fancybox js file to make it work with jQuery v1.9.0 as follow :

  1. Open the jquery.fancybox-1.3.4.js file (full version, not pack version) with a text/html editor.
  2. Find around the line 29 where it says :

    isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
    

    and replace it by (EDITED March 19, 2013: more accurate filter):

    isIE6 = navigator.userAgent.match(/msie [6]/i) && !window.XMLHttpRequest,
    

    UPDATE (March 19, 2013): Also replace $.browser.msie by navigator.userAgent.match(/msie [6]/i) around line 615 (and/or replace all $.browser.msie instances, if any), thanks joofow ... that's it!

Or download the already patched version from HERE (UPDATED March 19, 2013 ... thanks fairylee for pointing out the extra closing bracket)

NOTE: this is an unofficial patch and is unsupported by Fancybox's author, however it works as is. You may use it at your own risk ;)

Optionally, you may rather rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.

How to get the file name from a full path using JavaScript?

I use:

var lastPart = path.replace(/\\$/,'').split('\\').pop();

It replaces the last \ so it also works with folders.

Count number of occurrences for each unique value

You should change the query to:

SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col

This vl works correctly.

Where's javax.servlet?

Have you instaled the J2EE? If you installed just de standard (J2SE) it won´t find.

source of historical stock data

THIS ANSWER IS NO LONGER ACCURATE AS THE YAHOO FEED HAS CEASED TO EXIST

Using Yahoo's CSV approach above you can also get historical data! You can reverse engineer the following example:

http://ichart.finance.yahoo.com/table.csv?s=YHOO&d=0&e=28&f=2010&g=d&a=3&b=12&c=1996&ignore=.csv

Essentially:

sn = TICKER
a = fromMonth-1
b = fromDay (two digits)
c = fromYear
d = toMonth-1
e = toDay (two digits)
f = toYear
g = d for day, m for month, y for yearly

The complete list of parameters:

a   Ask
a2  Average Daily Volume
a5  Ask Size
b   Bid
b2  Ask (Real-time)
b3  Bid (Real-time)
b4  Book Value
b6  Bid Size
c   Change & Percent Change
c1  Change
c3  Commission
c6  Change (Real-time)
c8  After Hours Change (Real-time)
d   Dividend/Share
d1  Last Trade Date
d2  Trade Date
e   Earnings/Share
e1  Error Indication (returned for symbol changed / invalid)
e7  EPS Estimate Current Year
e8  EPS Estimate Next Year
e9  EPS Estimate Next Quarter
f6  Float Shares
g   Day's Low
h   Day's High
j   52-week Low
k   52-week High
g1  Holdings Gain Percent
g3  Annualized Gain
g4  Holdings Gain
g5  Holdings Gain Percent (Real-time)
g6  Holdings Gain (Real-time)
i   More Info
i5  Order Book (Real-time)
j1  Market Capitalization
j3  Market Cap (Real-time)
j4  EBITDA
j5  Change From 52-week Low
j6  Percent Change From 52-week Low
k1  Last Trade (Real-time) With Time
k2  Change Percent (Real-time)
k3  Last Trade Size
k4  Change From 52-week High
k5  Percent Change From 52-week High
l   Last Trade (With Time)
l1  Last Trade (Price Only)
l2  High Limit
l3  Low Limit
m   Day's Range
m2  Day's Range (Real-time)
m3  50-day Moving Average
m4  200-day Moving Average
m5  Change From 200-day Moving Average
m6  Percent Change From 200-day Moving Average
m7  Change From 50-day Moving Average
m8  Percent Change From 50-day Moving Average
n   Name
n4  Notes
o   Open
p   Previous Close
p1  Price Paid
p2  Change in Percent
p5  Price/Sales
p6  Price/Book
q   Ex-Dividend Date
r   P/E Ratio
r1  Dividend Pay Date
r2  P/E Ratio (Real-time)
r5  PEG Ratio
r6  Price/EPS Estimate Current Year
r7  Price/EPS Estimate Next Year
s   Symbol
s1  Shares Owned
s7  Short Ratio
t1  Last Trade Time
t6  Trade Links
t7  Ticker Trend
t8  1 yr Target Price
v   Volume
v1  Holdings Value
v7  Holdings Value (Real-time)
w   52-week Range
w1  Day's Value Change
w4  Day's Value Change (Real-time)
x   Stock Exchange
y   Dividend Yield

Matching an optional substring in a regex

(\d+)\s+(\(.*?\))?\s?Z

Note the escaped parentheses, and the ? (zero or once) quantifiers. Any of the groups you don't want to capture can be (?: non-capture groups).

I agree about the spaces. \s is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^ at the front and a $ at the end).

Adding integers to an int array

An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.

int[] num = new int[5];

This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.

num[0] = 1;
num[1] = 2;

The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:

[1,2,0,0,0]

As you can see you set values in it, you don't add them to the end.

If you want to be able to create a list of numbers which you add to, you should use ArrayList.

How to check queue length in Python

Use queue.rear+1 to get the length of the queue

Removing all non-numeric characters from string in Python

Not sure if this is the most efficient way, but:

>>> ''.join(c for c in "abc123def456" if c.isdigit())
'123456'

The ''.join part means to combine all the resulting characters together without any characters in between. Then the rest of it is a list comprehension, where (as you can probably guess) we only take the parts of the string that match the condition isdigit.

How to make inactive content inside a div?

Without using an overlay, you can use pointer-events: none on the div in CSS, but this does not work in IE or Opera.

div.disabled
{
  pointer-events: none;

  /* for "disabled" effect */
  opacity: 0.5;
  background: #CCC;
}

Reference

How to set DOM element as the first child?

2017 version

You can use

targetElement.insertAdjacentElement('afterbegin', newFirstElement)

From MDN :

The insertAdjacentElement() method inserts a given element node at a given position relative to the element it is invoked upon.

position
A DOMString representing the position relative to the element; must be one of the following strings:
beforebegin: Before the element itself.
afterbegin: Just inside the element, before its first child.
beforeend: Just inside the element, after its last child.
afterend: After the element itself.

element
The element to be inserted into the tree.

Also in the family of insertAdjacent there is the sibling methods:

element.insertAdjacentHTML('afterbegin','htmlText') for inject html string directly, like innerHTML but without overide everything , so you can jump oppressive process of document.createElement and even build whole componet with string manipulation process

element.insertAdjacentText for inject sanitize string into element . no more encode/decode

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

Conversion failed when converting date and/or time from character string in SQL SERVER 2008

DECLARE @FromDate DATETIME

SET @FromDate =  'Jan 10 2016 12:00AM'

DECLARE @ToDate DATETIME
SET @ToDate = 'Jan 10 2017 12:00AM'

DECLARE @Dynamic_Qry nvarchar(Max) =''

SET @Dynamic_Qry='SELECT

(CONVERT(DATETIME,(SELECT 
     CASE WHEN (  ''IssueDate''   =''IssueDate'') THEN 
               EMP_DOCUMENT.ISSUE_DATE 
          WHEN (''IssueDate'' =''ExpiryDate'' ) THEN       
               EMP_DOCUMENT.EXPIRY_DATE ELSE EMP_DOCUMENT.APPROVED_ON END   
          CHEKDATE ), 101)  

)FROM CR.EMP_DOCUMENT  as EMP_DOCUMENT WHERE 1=1 

AND  (
      CONVERT(DATETIME,(SELECT 
        CASE WHEN (  ''IssueDate''   =''IssueDate'') THEN
                 EMP_DOCUMENT.ISSUE_DATE 
             WHEN (''IssueDate'' =''ExpiryDate'' ) THEN EMP_DOCUMENT.EXPIRY_DATE 
             ELSE EMP_DOCUMENT.APPROVED_ON END 
             CHEKDATE ), 101)  
) BETWEEN  '''+ CONVERT(CHAR(10), @FromDate, 126) +'''  AND '''+CONVERT(CHAR(10),  @ToDate , 126
)
+'''  
'

print @Dynamic_Qry

EXEC(@Dynamic_Qry) 

Maximum call stack size exceeded on npm install

Happened in docker (node:15-buster) for me.

Remember to use WORKDIR /<folder> so that it doesn't conflict with original npm libraries installed.

The folder can be anything but system folders, so that includes using /.

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

Testing if a site is vulnerable to Sql Injection

SQL injection is the attempt to issue SQL commands to a database through a website interface, to gain other information. Namely, this information is stored database information such as usernames and passwords.

First rule of securing any script or page that attaches to a database instance is Do not trust user input.

Your example is attempting to end a misquoted string in an SQL statement. To understand this, you first need to understand SQL statements. In your example of adding a ' to a paramater, your 'injection' is hoping for the following type of statement:

SELECT username,password FROM users WHERE username='$username'

By appending a ' to that statement, you could then add additional SQL paramaters or queries.: ' OR username --

SELECT username,password FROM users WHERE username='' OR username -- '$username

That is an injection (one type of; Query Reshaping). The user input becomes an injected statement into the pre-written SQL statement.

Generally there are three types of SQL injection methods:

  • Query Reshaping or redirection (above)
  • Error message based (No such user/password)
  • Blind Injections

Read up on SQL Injection, How to test for vulnerabilities, understanding and overcoming SQL injection, and this question (and related ones) on StackOverflow about avoiding injections.

Edit:

As far as TESTING your site for SQL injection, understand it gets A LOT more complex than just 'append a symbol'. If your site is critical, and you (or your company) can afford it, hire a professional pen tester. Failing that, this great exaxmple/proof can show you some common techniques one might use to perform an injection test. There is also SQLMap which can automate some tests for SQL Injection and database take over scenarios.

Repeating a function every few seconds

There are lot of different Timers in the .NET BCL:

When to use which?

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
  • System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
  • System.Windows.Threading.DispatcherTimer, a timer that's integrated into the Dispatcher queue. This timer is processed with a specified priority at a specified time interval.

Source


Some of them needs explicit Start call to begin ticking (for example System.Timers, System.Windows.Forms). And an explicit Stop to finish ticking.

using TimersTimer = System.Timers.Timer;

static void Main(string[] args)
{
    var timer = new TimersTimer(1000);
    timer.Elapsed += (s, e) => Console.WriteLine("Beep");
    Thread.Sleep(1000); //1 second delay
    timer.Start();
    Console.ReadLine();
    timer.Stop();

}

While on the other hand there are some Timers (like: System.Threading) where you don't need explicit Start and Stop calls. (The provided delegate will run a background thread.) Your timer will tick until you or the runtime dispose it.

So, the following two versions will work in the same way:

using ThreadingTimer = System.Threading.Timer;

static void Main(string[] args)
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
    Console.ReadLine();
}
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
    StartTimer();
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

But if your timer disposed then it will stop ticking obviously.

using ThreadingTimer = System.Threading.Timer; 

static void Main(string[] args)
{
    StartTimer();
    GC.Collect(0);
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

Just in case it helps someone, here's what caused this error for me: I needed a procedure to return json but I left out the for json path:

set @jsonout = (SELECT ID, SumLev, Census_GEOID, AreaName, Worksite 
            from CS_GEO G (nolock) 
                join @allids a on g.ID = a.[value] 
            where g.Worksite = @worksite)

When I tried to save the stored procedure, it threw the error. I fixed it by adding for json path to the code at the end of the procedure:

set @jsonout = (SELECT ID, SumLev, Census_GEOID, AreaName, Worksite 
            from CS_GEO G (nolock) 
                join @allids a on g.ID = a.[value] 
            where g.Worksite = @worksite for json path)

How to view log output using docker-compose run?

Unfortunately we need to run docker-compose logs separately from docker-compose run. In order to get this to work reliably we need to suppress the docker-compose run exit status then redirect the log and exit with the right status.

#!/bin/bash
set -euo pipefail
docker-compose run app | tee app.log || failed=yes
docker-compose logs --no-color > docker-compose.log
[[ -z "${failed:-}" ]] || exit 1

Saving awk output to variable

as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.

awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:

variable=$(ps -ef | awk '/port 10 \-/ {print $12}')

variable=`ps -ef | awk '/port 10 \-/ {print $12}'`

The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.

.Net System.Mail.Message adding multiple "To" addresses

Thanks for spotting this I was about to add strings thinking the same as you that they'd get added to end of collection. It appears the params are:

msg.to.Add(<MailAddress>) adds MailAddress to the end of the collection
msg.to.Add(<string>) add a list of emails to the collection

Slightly different actions depending on param type, I think this is pretty bad form i'd have prefered split methods AddStringList of something.

Using :after to clear floating elements

Write like this:

.wrapper:after {
    content: '';
    display: block;
    clear: both;
}

Check this http://jsfiddle.net/EyNnk/1/

Remove Rows From Data Frame where a Row matches a String

Just use the == with the negation symbol (!). If dtfm is the name of your data.frame:

dtfm[!dtfm$C == "Foo", ]

Or, to move the negation in the comparison:

dtfm[dtfm$C != "Foo", ]

Or, even shorter using subset():

subset(dtfm, C!="Foo")

how to show calendar on text box click in html

try to use jquery-ui

<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>

<script>   
    $(function() {
         $( "#calendar" ).datepicker();   
    }); 
</script>

<p>Calendar: <input type="text" id="calendar" /></p>

more

How to change identity column values programmatically?

You can insert new rows with modified values and then delete old rows. Following example change ID to be same as foreign key PersonId

SET IDENTITY_INSERT [PersonApiLogin] ON

INSERT INTO [PersonApiLogin](
       [Id]
      ,[PersonId]
      ,[ApiId]
      ,[Hash]
      ,[Password]
      ,[SoftwareKey]
      ,[LoggedIn]
      ,[LastAccess])
SELECT [PersonId]
      ,[PersonId]
      ,[ApiId]
      ,[Hash]
      ,[Password]
      ,[SoftwareKey]
      ,[LoggedIn]
      ,[LastAccess]
FROM [db304].[dbo].[PersonApiLogin]
GO

DELETE FROM [PersonApiLogin]
WHERE [PersonId] <> ID
GO
SET IDENTITY_INSERT [PersonApiLogin] OFF
GO

combining results of two select statements

Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:

WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
    SELECT tableA.Id, COUNT(tableC.Id)
    FROM tableC
        RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
    GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
                     CompanyImageUrl,NumberOfUsers) AS (
    SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
        tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
    FROM tableA
        INNER JOIN tableB ON tableB.Id = tableA.Owner
        RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
    GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
    ,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
    INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id

After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.

CSS class for pointer cursor

I tried and found out that if you add a class called btn you can get that hand or cursor icon if you hover over the mouse to that element. Try and see.

Example:

<span class="btn">Hovering over must have mouse cursor set to hand or pointer!</span>

Cheers!

Get a resource using getResource()

Instead of explicitly writing the class name you could use

this.getClass().getResource("/unibo/lsb/res/dice.jpg");

Remove pandas rows with duplicate indices

I would suggest using the duplicated method on the Pandas Index itself:

df3 = df3[~df3.index.duplicated(keep='first')]

While all the other methods work, the currently accepted answer is by far the least performant for the provided example. Furthermore, while the groupby method is only slightly less performant, I find the duplicated method to be more readable.

Using the sample data provided:

>>> %timeit df3.reset_index().drop_duplicates(subset='index', keep='first').set_index('index')
1000 loops, best of 3: 1.54 ms per loop

>>> %timeit df3.groupby(df3.index).first()
1000 loops, best of 3: 580 µs per loop

>>> %timeit df3[~df3.index.duplicated(keep='first')]
1000 loops, best of 3: 307 µs per loop

Note that you can keep the last element by changing the keep argument to 'last'.

It should also be noted that this method works with MultiIndex as well (using df1 as specified in Paul's example):

>>> %timeit df1.groupby(level=df1.index.names).last()
1000 loops, best of 3: 771 µs per loop

>>> %timeit df1[~df1.index.duplicated(keep='last')]
1000 loops, best of 3: 365 µs per loop

How can I get href links from HTML using Python?

Look at using the beautiful soup html parsing library.

http://www.crummy.com/software/BeautifulSoup/

You will do something like this:

import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html)
for link in soup.findAll("a"):
    print link.get("href")

How to get the MD5 hash of a file in C++?

A rework of impementation by @D'Nabre for C++. Don't forget to compile with -lcrypto at the end: gcc md5.c -o md5 -lcrypto.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

#include <openssl/md5.h>
using namespace std;

unsigned char result[MD5_DIGEST_LENGTH];

// function to print MD5 correctly
void printMD5(unsigned char* md, long size = MD5_DIGEST_LENGTH) {
    for (int i=0; i<size; i++) {
        cout<< hex << setw(2) << setfill('0') << (int) md[i];
    }
}

int main(int argc, char *argv[]) {

if(argc != 2) {
    cout << "Specify the file..." << endl;
    return 0;
}

ifstream::pos_type fileSize;
char * memBlock;

ifstream file (argv[1], ios::ate);

//check if opened
if (file.is_open() ) { cout<< "Using file\t"<< argv[1]<<endl; }
else {
    cout<< "Unnable to open\t"<< argv[1]<<endl;
    return 0;
}

//get file size & copy file to memory
//~ file.seekg(-1,ios::end); // exludes EOF
fileSize = file.tellg();
cout << "File size \t"<< fileSize << endl;
memBlock = new char[fileSize];
file.seekg(0,ios::beg);
file.read(memBlock, fileSize);
file.close();

//get md5 sum
MD5((unsigned char*) memBlock, fileSize, result);

//~ cout << "MD5_DIGEST_LENGTH = "<< MD5_DIGEST_LENGTH << endl;
printMD5(result);
cout<<endl;

return 0;
}

How can I iterate over an enum?

Something that hasn't been covered in the other answers = if you're using strongly typed C++11 enums, you cannot use ++ or + int on them. In that case, a bit of a messier solution is required:

enum class myenumtype {
  MYENUM_FIRST,
  MYENUM_OTHER,
  MYENUM_LAST
}

for(myenumtype myenum = myenumtype::MYENUM_FIRST;
    myenum != myenumtype::MYENUM_LAST;
    myenum = static_cast<myenumtype>(static_cast<int>(myenum) + 1)) {

  do_whatever(myenum)

}

How to execute a program or call a system command from Python

import os
os.system("your command")

Note that this is dangerous, since the command isn't cleaned. I leave it up to you to google for the relevant documentation on the 'os' and 'sys' modules. There are a bunch of functions (exec* and spawn*) that will do similar things.

Select All as default value for Multivalue parameter

This is rather easy to achieve by making a dataset with a text-query like this:

SELECT 'Item1'
UNION
SELECT 'Item2'
UNION
SELECT 'Item3'
UNION
SELECT 'Item4'
UNION
SELECT 'ItemN'

The query should return all items that can be selected.

Bootstrap 3 Multi-column within a single ul not floating properly

You should try using the Grid Template.

Here's what I've used for a two Column Layout of a <ul>

<ul class="list-group row">
     <li class="list-group-item col-xs-6">Row1</li>
     <li class="list-group-item col-xs-6">Row2</li>
     <li class="list-group-item col-xs-6">Row3</li>
     <li class="list-group-item col-xs-6">Row4</li>
     <li class="list-group-item col-xs-6">Row5</li>
</ul>

This worked for me.

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

What worked for me (I use Java 8 and Tomcat 9 in Eclipse 2019):

pom.xml

    <!-- jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp.jstl</groupId>
        <artifactId>javax.servlet.jsp.jstl-api</artifactId>
        <version>1.2.1</version>
    </dependency>
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>

.jsp file

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>

Removing white space around a saved image in matplotlib

I found something from Arvind Pereira (http://robotics.usc.edu/~ampereir/wordpress/?p=626) and seemed to work for me:

plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)

How to import Angular Material in project?

The MaterialModule was deprecated in the beta3 version with the goal that developers should only import into their applications what they are going to use and thus improve the bundle size.

The developers have now 2 options:

  • Create a custom MyMaterialModule which imports/exports the components that your application requires and can be imported by other (feature) modules in your application.
  • Import directly the individual material modules that a module requires into it.

Take the following as example (extracted from material page)

First approach:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
  imports: [MdButtonModule, MdCheckboxModule],
  exports: [MdButtonModule, MdCheckboxModule],
})
export class MyOwnCustomMaterialModule { }

Then you can import this module into any of yours.

Second approach:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
  ...
  imports: [MdButtonModule, MdCheckboxModule],
  ...
})
export class PizzaPartyAppModule { }

Now you can use the respective material components in all the components declared in PizzaPartyAppModule

It is worth mentioning the following:

  • With the latest version of material, you need to import BrowserAnimationsModule into your main module if you want the animations to work
  • With the latest version developers now need to add @angular/cdk to their package.json (material dependency)
  • Import the material modules always after BrowserModule, as stated by the docs:

Whichever approach you use, be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules.

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

You can flush hosts local MySQL using following command:

mysqladmin -u [username] -p flush-hosts
**** [MySQL password]

or

mysqladmin flush-hosts -u [username] -p
**** [MySQL password]

Though Amazon RDS database server is on network then use the following command as like as flush network MySQL server:

mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts 

In additional suggestion you can permanently solve blocked of many connections error problem by editing my.ini file[Mysql configuration file]

change variables max_connections = 10000;

or

login into MySQL using command line -

mysql -u [username] -p
**** [MySQL password]

put the below command into MySQL window

SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;

check veritable using command-

show variables like "max_connections";
show variables like "max_connect_errors";

How do I set the selenium webdriver get timeout?

Used below code in similar situation

driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);

and embedded driver.get code in a try catch, which solved the issue of loading pages which were taking more than 1 minute.

Get size of a View in React Native

This is the only thing that worked for me:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image
} from 'react-native';

export default class Comp extends Component {

  find_dimesions(layout){
    const {x, y, width, height} = layout;
    console.warn(x);
    console.warn(y);
    console.warn(width);
    console.warn(height);
  }
  render() {
    return (
      <View onLayout={(event) => { this.find_dimesions(event.nativeEvent.layout) }} style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Double tap R on your keyboard to reload,{'\n'}
          Shake or press menu button for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('Comp', () => Comp);

How to kill zombie process

I tried:

ps aux | grep -w Z   # returns the zombies pid
ps o ppid {returned pid from previous command}   # returns the parent
kill -1 {the parent id from previous command}

this will work :)

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

How can I take a screenshot with Selenium WebDriver?

import java.io.File;
import java.io.IOException;

import org.apache.maven.surefire.shade.org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
/**
 * @author Jagdeep Jain
 *
 */
public class ScreenShotMaker {

    // take screen shot on the test failures
    public void takeScreenShot(WebDriver driver, String fileName) {
        File screenShot = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenShot, new File("src/main/webapp/screen-captures/" + fileName + ".png"));

        } catch (IOException ioe) {
            throw new RuntimeException(ioe.getMessage(), ioe);
        }
    }

}

Java8: sum values from specific field of the objects in a list

You can also collect with an appropriate summing collector like Collectors#summingInt(ToIntFunction)

Returns a Collector that produces the sum of a integer-valued function applied to the input elements. If no elements are present, the result is 0.

For example

Stream<Obj> filtered = list.stream().filter(o -> o.field > 10);
int sum = filtered.collect(Collectors.summingInt(o -> o.field));

Checking for empty result (php, pdo, mysql)

Thanks to Marc B's help, here's what worked for me (note: Marc's rowCount() suggestion could work too, but I wasn't comfortable with the possibility of it not working on a different DB or if something changed in mine... also, his select count(*) suggestion would work too, but, I figured because I'd end up getting the data if it existed anyways, so I went this way)

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today',$today, PDO::PARAM_STR);

if(!$sth->execute()) {
    $db = null ;
    exit();
}

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    $this->id_email[] = $row['id_email'] ;
    echo $row['id_email'] ;
}
$db = null ;

if (count($this->id_email) > 0) {
    echo 'not empty';
    return true ;
}
echo 'empty';
return false ;

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.

Proxy Error

The proxy server received an invalid response from an upstream server.
 The proxy server could not handle the request GET /lin/Campaignn.jsp.

As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.

Change div height on button click

Do this:

function changeHeight() {
document.getElementById('chartdiv').style.height = "200px"
}
<button type="button" onClick="changeHeight();"> Click Me!</button>

Android: checkbox listener

Translation of the accepted answer by Chris into Kotlin:

val checkBox: CheckBox = findViewById(R.id.chk)
checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
    // Code here 
}

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

How can I change the class of an element with jQuery>

<script>
$(document).ready(function(){
      $('button').attr('class','btn btn-primary');
}); </script>

SELECT from nothing?

Here is the most complete list of database support of dual from https://blog.jooq.org/tag/dual-table/:

In many other RDBMS, there is no need for dummy tables, as you can issue statements like these:

SELECT 1;
SELECT 1 + 1;
SELECT SQRT(2);

These are the RDBMS, where the above is generally possible:

  • H2
  • MySQL
  • Ingres
  • Postgres
  • SQLite
  • SQL Server
  • Sybase ASE

In other RDBMS, dummy tables are required, like in Oracle. Hence, you’ll need to write things like these:

SELECT 1       FROM DUAL;
SELECT 1 + 1   FROM DUAL;
SELECT SQRT(2) FROM DUAL;

These are the RDBMS and their respective dummy tables:

  • DB2: SYSIBM.DUAL
  • Derby: SYSIBM.SYSDUMMY1
  • H2: Optionally supports DUAL
  • HSQLDB: INFORMATION_SCHEMA.SYSTEM_USERS
  • MySQL: Optionally supports DUAL
  • Oracle: DUAL
  • Sybase SQL Anywhere: SYS.DUMMY

Ingres has no DUAL, but would actually need it as in Ingres you cannot have a WHERE, GROUP BY or HAVING clause without a FROM clause.

Rerender view on browser resize with React

Thank you all for the answers. Here's my React + Recompose. It's a High Order Function that includes the windowHeight and windowWidth properties to the component.

const withDimensions = compose(
 withStateHandlers(
 ({
   windowHeight,
   windowWidth
 }) => ({
   windowHeight: window.innerHeight,
   windowWidth: window.innerWidth
 }), {
  handleResize: () => () => ({
    windowHeight: window.innerHeight,
    windowWidth: window.innerWidth
  })
 }),
 lifecycle({
   componentDidMount() {
   window.addEventListener('resize', this.props.handleResize);
 },
 componentWillUnmount() {
  window.removeEventListener('resize');
 }})
)

In Powershell what is the idiomatic way of converting a string to an int?

For me $numberAsString -as [int] of @Shay Levy is the best practice, I also use [type]::Parse(...) or [type]::TryParse(...)

But, depending on what you need you can just put a string containing a number on the right of an arithmetic operator with a int on the left the result will be an Int32:

PS > $b = "10"
PS > $a = 0 + $b
PS > $a.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

You can use Exception (try/parse) to behave in case of Problem

JavaScript, get date of the next day

Copy-pasted from here: Incrementing a date in JavaScript

Three options for you:

Using just JavaScript's Date object (no libraries):

var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));

Or if you don't mind changing the date in place (rather than creating a new date):

var dt = new Date();
dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));

Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);

Using MomentJS:

var today = moment();
var tomorrow = moment(today).add(1, 'days');

(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)

Using DateJS, but it hasn't been updated in a long time:

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();

Open source PDF library for C/C++ application?

I worked on a project that required a pdf report. After searching for online I found the PoDoFo library. Seemed very robust. I did not need all the features, so I created a wrapper to abstract away some of the complexity. Wasn't too difficult. You can find the library here:

http://podofo.sourceforge.net/

Enjoy!

How to vertically center an image inside of a div element in HTML using CSS?

As I too am constantly being let down by cross-browser CSS, I'd like to offer a JQuery solution here. This takes the height of each image's parent div, divide it by two and set it as a top margin between the image and the div:

$('div img').each(function() {
 m = Math.floor(($(this).parent('div').height() - $(this).height())/2);
 mp = m+"px";
 $(this).css("margin-top",mp);
});

Hide password with "•••••••" in a textField

Programmatically (Swift 4 & 5)

self.passwordTextField.isSecureTextEntry = true

Some projects cannot be imported because they already exist in the workspace error in Eclipse

Another way I just found!

MOVE the project to some other folder and then import and if required copy to workspace

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

How to change package name of Android Project in Eclipse?

Renaming an Application- The Complete Guide

**A) for changing Just the application name
   (App name which is displayed below icon)
    in the Manifest.xml file, in <application tag, 
    android:label="YourAppName"
    then do the same in All the <activity Tags        

  B) For changing EVERYTHING 
   (folder names, Package names, Refrences,app name, etc.)
  *1) Renaming package names in gen folder and manifest.xml
      Right Click on Your project
      Android tools- Rename Application Package

  *2) Renaming package names in src folder 
      Expand src folder, Click on package (Single click) 
      Press Alt+Shift+R
      Check Update references and Rename subpackages      
   3) Renaming the app's main Folder (Optional)
      click on the application's folder (Single click)
      then Press Alt+Shift+R 

   4) Renaming application name- Refer "A)"**

How to "git clone" including submodules?

You have to do two things before a submodule will be filled:

git submodule init 
git submodule update

How can I check if a URL exists via PHP?

Here is a solution that reads only the first byte of source code... returning false if the file_get_contents fails... This will also work for remote files like images.

 function urlExists($url)
{
    if (@file_get_contents($url,false,NULL,0,1))
    {
        return true;
    }
    return false;
}

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

Apparently this is by design. When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage is available, but trying to call setItem throws an exception.

store.js line 73
"QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

What happens is that the window object still exposes localStorage in the global namespace, but when you call setItem, this exception is thrown. Any calls to removeItem are ignored.

I believe the simplest fix (although I haven't tested this cross browser yet) would be to alter the function isLocalStorageNameSupported() to test that you can also set some value.

https://github.com/marcuswestin/store.js/issues/42

function isLocalStorageNameSupported() 
{
    var testKey = 'test', storage = window.sessionStorage;
    try 
    {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return localStorageName in win && win[localStorageName];
    } 
    catch (error) 
    {
        return false;
    }
}

how to stop a running script in Matlab

Consider having multiple matlab sessions. Keep the main session window (the pretty one with all the colours, file manager, command history, workspace, editor etc.) for running stuff that you know will terminate.

Stuff that you are experimenting with, say you are messing with ode suite and you get lots of warnings: matrix singular, because you altered some parameter and didn't predict what would happen, run in a separate session:

dos('matlab -automation -r &')

You can kill that without having to restart the whole of Matlab.

Where are the python modules stored?

  1. Is there a way to obtain a list of Python modules available (i.e. installed) on a machine?

This works for me:

help('modules')
  1. Where is the module code actually stored on my machine?

Usually in /lib/site-packages in your Python folder. (At least, on Windows.)

You can use sys.path to find out what directories are searched for modules.

Convert date formats in bash

#since this was yesterday
date -dyesterday +%Y%m%d

#more precise, and more recommended
date -d'27 JUN 2011' +%Y%m%d

#assuming this is similar to yesterdays `date` question from you 
#http://stackoverflow.com/q/6497525/638649
date -d'last-monday' +%Y%m%d

#going on @seth's comment you could do this
DATE="27 jun 2011"; date -d"$DATE" +%Y%m%d

#or a method to read it from stdin
read -p "  Get date >> " DATE; printf "  AS YYYYMMDD format >> %s"  `date
-d"$DATE" +%Y%m%d`    

#which then outputs the following:
#Get date >> 27 june 2011   
#AS YYYYMMDD format >> 20110627

#if you really want to use awk
echo "27 june 2011" | awk '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}' | bash

#note | bash just redirects awk's output to the shell to be executed
#FS is field separator, in this case you can use $0 to print the line
#But this is useful if you have more than one date on a line

More on Dates

note this only works on GNU date

I have read that:

Solaris version of date, which is unable to support -d can be resolve with replacing sunfreeware.com version of date

How can I account for period (AM/PM) using strftime?

>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM

Try replacing %I with %H.

How to call Stored Procedure in Entity Framework 6 (Code-First)?

Take a look to this link that shows how works the mapping of EF 6 with Stored Procedures to make an Insert, Update and Delete: http://msdn.microsoft.com/en-us/data/dn468673

Addition

Here is a great example to call a stored procedure from Code First:

Lets say you have to execute an Stored Procedure with a single parameter, and that Stored Procedure returns a set of data that match with the Entity States, so we will have this:

var countryIso = "AR"; //Argentina

var statesFromArgentina = context.Countries.SqlQuery(
                                      "dbo.GetStatesFromCountry @p0", countryIso
                                                    );

Now lets say that we whant to execute another stored procedure with two parameters:

var countryIso = "AR"; //Argentina
var stateIso = "RN"; //Río Negro

var citiesFromRioNegro = context.States.SqlQuery(
                            "dbo.GetCitiesFromState @p0, @p1", countryIso, stateIso
                          );

Notice that we are using index-based naming for parameters. This is because Entity Framework will wrap these parameters up as DbParameter objects fro you to avoid any SQL injection issues.

Hope this example helps!

Why use def main()?

if the content of foo.py

print __name__
if __name__ == '__main__':
    print 'XXXX'

A file foo.py can be used in two ways.

  • imported in another file : import foo

In this case __name__ is foo, the code section does not get executed and does not print XXXX.

  • executed directly : python foo.py

When it is executed directly, __name__ is same as __main__ and the code in that section is executed and prints XXXX

One of the use of this functionality to write various kind of unit tests within the same module.

document.getElementById().value and document.getElementById().checked not working for IE

Jin Yong - IE has an issue with polluting the global scope with object references to any DOM elements with a "name" or "id" attribute set on the "initial" page load.

Thus you may have issues due to your variable name.

Try this and see if it works.

var someOtherName="abc";
//  ^^^^^^^^^^^^^
document.getElementById('msg').value = someOtherName;
document.getElementById('sp_100').checked = true;

There is a chance (in your original code) that IE attempts to set the value of the input to a reference to that actual element (ignores the error) but leaves you with no new value.

Keep in mind that in IE6/IE7 case doesn't matter for naming objects. IE believes that "foo" "Foo" and "FOO" are all the same object.

jquery can't get data attribute value

You can change the selector and data attributes as you wish!

 <select id="selectVehicle">
       <option value="1" data-year="2011">Mazda</option>
       <option value="2" data-year="2015">Honda</option>
       <option value="3" data-year="2008">Mercedes</option>
       <option value="4" data-year="2005">Toyota</option>
  </select>

$("#selectVehicle").change(function () {
     alert($(this).find(':selected').data("year"));
});

Here is the working example: https://jsfiddle.net/ed5axgvk/1/

Transferring files over SSH

No, you still need to scp [from] [to] whichever way you're copying

The difference is, you need to scp -p server:serverpath localpath

How do you configure HttpOnly cookies in tomcat / java webapps?

also it should be noted that turning on HttpOnly will break applets that require stateful access back to the jvm.

the Applet http requests will not use the jsessionid cookie and may get assigned to a different tomcat.

PLS-00201 - identifier must be declared

you should give permission on your db

grant execute on (packageName or tableName) to user;

git replace local version with remote version

I would checkout the remote file from the "master" (the remote/origin repository) like this:

git checkout master <FileWithPath>

Example: git checkout master components/indexTest.html

Bootstrap Carousel : Remove auto slide

$(document).ready(function() {
  $('#media').carousel({
    pause: true,
    interval: 40000,
  });
});

By using the above script, you will be able to move the images automaticaly

$(document).ready(function() {
  $('#media').carousel({
    pause: true,
    interval: false,
  });
});

By using the above script, auto-rotation will be blocked because interval is false

JavaScript - onClick to get the ID of the clicked button

If you don't want to pass any arguments to the onclick function, just use event.target to get the clicked element:

<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>

function reply_click()
{
    // event.target is the element that is clicked (button in this case).
    console.log(event.target.id);
}

Convert pandas data frame to series

data = pd.DataFrame({"a":[1,2,3,34],"b":[5,6,7,8]})
new_data = pd.melt(data)
new_data.set_index("variable", inplace=True)

This gives a dataframe with index as column name of data and all data are present in "values" column

Cannot invoke an expression whose type lacks a call signature

Perhaps create a shared Fruit interface that provides isDecayed. fruits is now of type Fruit[] so the type can be explicit. Like this:

interface Fruit {
    isDecayed: boolean;
}

interface Apple extends Fruit {
    color: string;
}

interface Pear extends Fruit {
    weight: number;
}

interface FruitBasket {
    apples: Apple[];
    pears: Pear[];
}


const fruitBasket: FruitBasket = { apples: [], pears: [] };
const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears'; 
const fruits: Fruit[] = fruitBasket[key];

const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);

CSS grid wrapping

I had a similar situation. On top of what you did, I wanted to center my columns in the container while not allowing empty columns to for them left or right:

.grid { 
    display: grid;
    grid-gap: 10px;
    justify-content: center;
    grid-template-columns: repeat(auto-fit, minmax(200px, auto));
}