Programs & Examples On #Wincvs

How can I create a link to a local file on a locally-run web page?

Janky at best

<a href="file://///server/folders/x/x/filename.ext">right click </a></td>

and then right click, select "copy location" option, and then paste into url.

Have log4net use application config file for configuration data

Add a line to your app.config in the configSections element

<configSections>
 <section name="log4net" 
   type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, 
         Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>

Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...

<log4net configSource="Config\Log4Net.config" />

In your application code, when you create the log, write

private static ILog GetLog(string logName)
{
    ILog log = LogManager.GetLogger(logName);
    return log;
}

Getting windbg without the whole WDK?

If you're on Windows 7 x64, the solution provided by Sukesh doesn't work.

I managed to install the debugging tools by downloading the Windows SDK installer for Windows 8 (here), and then choosing "Debugging Tools for Windows" in the installer:

screenshot

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

function amiLoadedInIFrame() {
    try {
         // Introduce a new propery in window.top
         window.top.dummyAttribute = true;
         // If window.dummyAttribute is there.. then window and window.top are same intances
         return !window.dummyAttribute;
    } catch(e) {
         // Exception will be raised when the top is in different domain
         return true;
    }
}

Edit Crystal report file without Crystal Report software

If this is something you are only going to need to do once, have you considered downloading a demo version of Crystal? There's a 30-day trial version available here: http://www.developers.net/businessobjectsshowcase/view/3154

Of course, if you need to edit these files after the 30 day period is over, you would be better off buying Crystal.

Alternatively, if all you need to do is replace a few static literal words, have you tried doing a search and replace in a text editor? (Don't forget to save the original files somewhere safe first!)

Why is setTimeout(fn, 0) sometimes useful?

By calling setTimeout you give the page time to react to the whatever the user is doing. This is particularly helpful for functions run during page load.

Printing long int value in C

Use printf("%ld",a);

Have a look at format specifiers for printf

Java; String replace (using regular expressions)?

Try this:

String str = "5 * x^3 - 6 * x^1 + 1";
String replacedStr = str.replaceAll("\\^(\\d+)", "<sup>\$1</sup>");

Be sure to import java.util.regex.

How do I detect whether a Python variable is a function?

The solutions using hasattr(obj, '__call__') and callable(.) mentioned in some of the answers have a main drawback: both also return True for classes and instances of classes with a __call__() method. Eg.

>>> import collections
>>> Test = collections.namedtuple('Test', [])
>>> callable(Test)
True
>>> hasattr(Test, '__call__')
True

One proper way of checking if an object is a user-defined function (and nothing but a that) is to use isfunction(.):

>>> import inspect
>>> inspect.isfunction(Test)
False
>>> def t(): pass
>>> inspect.isfunction(t)
True

If you need to check for other types, have a look at inspect — Inspect live objects.

How to download python from command-line?

Well if you are getting into a linux machine you can use the package manager of that linux distro.

If you are using Ubuntu just use apt-get search python, check the list and do apt-get install python2.7 (not sure if python2.7 or python-2.7, check the list)

You could use yum in fedora and do the same.

if you want to install it on your windows machine i dont know any package manager, i would download the wget for windows, donwload the package from python.org and install it

What are Makefile.am and Makefile.in?

reference :

Makefile.am -- a user input file to automake

configure.in -- a user input file to autoconf


autoconf generates configure from configure.in

automake gererates Makefile.in from Makefile.am

configure generates Makefile from Makefile.in

For ex:

$]
configure.in Makefile.in
$] sudo autoconf
configure configure.in Makefile.in ... 
$] sudo ./configure
Makefile Makefile.in

"FATAL: Module not found error" using modprobe

The best thing is to actually use the kernel makefile to install the module:

Here is are snippets to add to your Makefile

around the top add:

PWD=$(shell pwd)
VER=$(shell uname -r)
KERNEL_BUILD=/lib/modules/$(VER)/build
# Later if you want to package the module binary you can provide an INSTALL_ROOT
# INSTALL_ROOT=/tmp/install-root

around the end add:

install:
        $(MAKE) -C $(KERNEL_BUILD) M=$(PWD) \
           INSTALL_MOD_PATH=$(INSTALL_ROOT) modules_install

and then you can issue

    sudo make install

this will put it either in /lib/modules/$(uname -r)/extra/

or /lib/modules/$(uname -r)/misc/

and run depmod appropriately

convert pfx format to p12

I had trouble with a .pfx file with openconnect. Renaming didn't solve the problem. I used keytool to convert it to .p12 and it worked.

keytool -importkeystore -destkeystore new.p12 -deststoretype pkcs12 -srckeystore original.pfx

In my case the password for the new file (new.p12) had to be the same as the password for the .pfx file.

Laravel 5 Eloquent where and or in Clauses

You can try to use the following code instead:

 $pro= model_name::where('col_name', '=', 'value')->get();

How many files can I put in a directory?

I respect this doesn't totally answer your question as to how many is too many, but an idea for solving the long term problem is that in addition to storing the original file metadata, also store which folder on disk it is stored in - normalize out that piece of metadata. Once a folder grows beyond some limit you are comfortable with for performance, aesthetic or whatever reason, you just create a second folder and start dropping files there...

Java getHours(), getMinutes() and getSeconds()

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!

How to stop and restart memcached server?

Using root, try something like this:

/etc/init.d/memcached restart

Setting Column width in Apache POI

With Scala there is a nice Wrapper spoiwo

You can do it like this:

Workbook(mySheet.withColumns(
      Column(autoSized = true),
      Column(width = new Width(100, WidthUnit.Character)),
      Column(width = new Width(100, WidthUnit.Character)))
    )

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 8.0 navigate to:

Server > Data Import

A new tab called Administration - Data Import/Restore appears. There you can choose to import a Dump Project Folder or use a specific SQL file according to your needs. Then you must select a schema where the data will be imported to, or you have to click the New... button to type a name for the new schema.

Then you can select the database objects to be imported or just click the Start Import button in the lower right part of the tab area.

Having done that and if the import was successful, you'll need to update the Schema Navigator by clicking the arrow circle icon.

That's it!

For more detailed info, check the MySQL Workbench Manual: 6.5.2 SQL Data Export and Import Wizard

BAT file to map to network drive without running as admin

I tried to create a mapped network driver via 'net use' with admin privilege but failed, it does not show. And if I add it through UI, it disappeared after reboot, now I made that through powershell. So, I think you can run powershell scripts from a .bat file, and the script is

New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Public"

add -persist at the end, you will create a persisted mapped network drive

New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Scripts" -Persist

for more details, refer New-PSDrive - Microsoft Docs

Redirect to a page/URL after alert button is pressed

<head>
<script>
    function myFunction() {
        var x;
        var r = confirm("Do you want to clear data?");
        if (r == true) {
            x = "Your Data is Cleared";
            window.location.href = "firstpage.php";
        }
        else {
            x = "You pressed Cancel!";
        }
        document.getElementById("demo").innerHTML = x;
    }
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>

<p id="demo"></p>
</body>
</html>

This will redirect to new php page.

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

How can I make a weak protocol reference in 'pure' Swift (without @objc)

Update: It looks like the manual has been updated and the example I was referring to has been removed. See the edit to @flainez's answer above.

Original: Using @objc is the right way to do it even if you're not interoperating with Obj-C. It ensures that your protocol is being applied to a class and not an enum or struct. See "Checking for Protocol Conformance" in the manual.

How to Update a Component without refreshing full page - Angular

Angular will automatically update a component when it detects a variable change .

So all you have to do for it to "refresh" is ensure that the header has a reference to the new data. This could be via a subscription within header.component.ts or via an @Input variable...


an example...

main.html

<app-header [header-data]="headerData"></app-header>

main.component.ts

public headerData:int = 0;

ngOnInit(){
    setInterval(()=>{this.headerData++;}, 250);
}

header.html

<p>{{data}}</p>

header.ts

@Input('header-data') data;

In the above example, the header will recieve the new data every 250ms and thus update the component.


For more information about Angular's lifecycle hooks, see: https://angular.io/guide/lifecycle-hooks

Best way to add Activity to an Android project in Eclipse?

There is no tool, that I know of, which is used specifically create activity classes. Just using the 'New Class' option under Eclipse and setting the base class to 'Activity'.

Thought here is a wizard like tool when creating/editing the xml layout that are used by an activity. To use this tool to create a xml layout use the option under 'New' of 'Android XML File'. This tool will allow you to create some of the basic layout of the view.

Servlet for serving static content

There is no need for completely custom implementation of the default servlet in this case, you can use this simple servlet to wrap request to the container's implementation:


package com.example;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class DefaultWrapperServlet extends HttpServlet
{   
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        RequestDispatcher rd = getServletContext().getNamedDispatcher("default");

        HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {
            public String getServletPath() { return ""; }
        };

        rd.forward(wrapped, resp);
    }
}

Git asks for username every time I push

I faced this issue today. If you are facing this issue in November 2020 then you need to update your git version. I received an email telling me about this. Here is what exactly was the email by github team.

We have detected that you recently attempted to authenticate to GitHub using an older version of Git for Windows. GitHub has changed how users authenticate when using Git for Windows, and now requires the use of a web browser to authenticate to GitHub. To be able to login via web browser, users need to update to the latest version of Git for Windows. You can download the latest version at:

If you cannot update Git for Windows to the latest version please see the following link for more information and suggested workarounds:

If you have any questions about these changes or require any assistance, please reach out to GitHub Support and we’ll be happy to assist further.

Thanks, The GitHub Team

How to center a checkbox in a table cell?

Pull out ALL of your in-line CSS, and move it to the head. Then use classes on the cells so you can adjust everything as you like (don't use a name like "center" - you may change it to left 6 months from now...). The alignment answer is still the same - apply it to the <td> NOT the checkbox (that would just center your check :-) )

Using you code...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Alignment test</title>
<style>
table { margin:10px auto; border-collapse:collapse; border:1px solid gray; }
td,th { border:1px solid gray; text-align:left; padding:20px; }
td.opt1 { text-align:center; vertical-align:middle; }
td.opt2 { text-align:right; }
</style>
</head>
<body>

<table>

      <tr>
        <th>Search?</th><th>Field</th><th colspan="2">Search criteria</th><th>Include in report?<br></th>
      </tr>
      <tr>
        <td class="opt1"><input type="checkbox" name="query_myTextEditBox"></td>
        <td>
          myTextEditBox
        </td>
        <td>
           <select size ="1" name="myTextEditBox_compare_operator">
            <option value="=">equals</option>
            <option value="<>">does not equal</option>
           </select>
        </td>
        <td><input type="text" name="myTextEditBox_compare_value"></td>
        <td class="opt2">
          <input type="checkbox" name="report_myTextEditBox" value="checked">
        </td>
      </tr>
    </table>
    </body>
    </html>

What ports does RabbitMQ use?

PORT 4369: Erlang makes use of a Port Mapper Daemon (epmd) for resolution of node names in a cluster. Nodes must be able to reach each other and the port mapper daemon for clustering to work.

PORT 35197 set by inet_dist_listen_min/max Firewalls must permit traffic in this range to pass between clustered nodes

RabbitMQ Management console:

  • PORT 15672 for RabbitMQ version 3.x
  • PORT 55672 for RabbitMQ pre 3.x

PORT 5672 RabbitMQ main port.

For a cluster of nodes, they must be open to each other on 35197, 4369 and 5672.

For any servers that want to use the message queue, only 5672 is required.

Maven: How to rename the war file for the project?

You can use the following in the web module that produces the war:

<build>
  <finalName>bird</finalName>
 . . .
</build>

This leads to a file called bird.war to be created when goal "war:war" is used.

"UnboundLocalError: local variable referenced before assignment" after an if statement

I was facing same issue in my exercise. Although not related, yet might give some reference. I didn't get any error once I placed addition_result = 0 inside function. Hope it helps! Apologize if this answer is not in context.

user_input = input("Enter multiple values separated by comma > ")

def add_numbers(num_list):
    addition_result = 0
    for i in num_list:
        addition_result = addition_result + i
    print(addition_result)

add_numbers(user_input)

Format y axis as percent

This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):

import ...
import matplotlib.ticker as mtick

ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0).

The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None and '%', respectively. decimals=None will automatically set the number of decimal points based on how much of the axes you are showing.

Update

PercentFormatter was introduced into Matplotlib proper in version 2.1.0.

Basic text editor in command prompt?

There is one built into windows 7 in which you can open by clicking the windows and r keys at the same time and then typing edit.com.

I hope this helped

How do I keep two side-by-side divs the same height?

This is a common problem which many have encountered, but luckily some smart minds like Ed Eliot's on his blog have posted their solutions online.

Basically what you do is make both divs/columns very tall by adding a padding-bottom: 100% and then "trick the browser" into thinking they aren't that tall using margin-bottom: -100%. It is better explained by Ed Eliot on his blog, which also includes many examples.

_x000D_
_x000D_
.container {_x000D_
    overflow: hidden;_x000D_
}_x000D_
.column {_x000D_
    float: left;_x000D_
    margin: 20px;_x000D_
    background-color: grey;_x000D_
    padding-bottom: 100%;_x000D_
    margin-bottom: -100%;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
    <div class="column">_x000D_
        Some content!<br>_x000D_
        Some content!<br>_x000D_
        Some content!<br>_x000D_
        Some content!<br>_x000D_
        Some content!<br>_x000D_
    </div>_x000D_
_x000D_
    <div class="column">_x000D_
        Something_x000D_
    </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert char array to single int?

Use sscanf

/* sscanf example */
#include <stdio.h>

int main ()
{
  char sentence []="Rudolph is 12 years old";
  char str [20];
  int i;

  sscanf (sentence,"%s %*s %d",str,&i);
  printf ("%s -> %d\n",str,i);

  return 0;
}

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

Free Barcode API for .NET

I do recommend BarcodeLibrary

Here is a small piece of code of how to use it.

        BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
        {
            IncludeLabel = true,
            Alignment = AlignmentPositions.CENTER,
            Width = 300,
            Height = 100,
            RotateFlipType = RotateFlipType.RotateNoneFlipNone,
            BackColor = Color.White,
            ForeColor = Color.Black,
        };

        Image img = barcode.Encode(TYPE.CODE128B, "123456789");

Split string into string array of single characters

Simple!!
one line:

 var res = test.Select(x => new string(x, 1)).ToArray();

UPDATE multiple tables in MySQL using LEFT JOIN

                DECLARE @cols VARCHAR(max),@colsUpd VARCHAR(max), @query VARCHAR(max),@queryUpd VARCHAR(max), @subQuery VARCHAR(max)
DECLARE @TableNameTest NVARCHAR(150)
SET @TableNameTest = @TableName+ '_Staging';
SELECT  @colsUpd = STUF  ((SELECT DISTINCT '], T1.[' + name,']=T2.['+name+'' FROM sys.columns
                 WHERE object_id = (
                                    SELECT top 1 object_id 
                                      FROM sys.objects
                                     WHERE name = ''+@TableNameTest+''
                                    )
                and name not in ('Action','Record_ID')
                FOR XML PATH('')
            ), 1, 2, ''
        ) + ']'


  Select @queryUpd ='Update T1
SET '+@colsUpd+'
FROM '+@TableName+' T1
INNER JOIN '+@TableNameTest+' T2
ON T1.Record_ID = T2.Record_Id
WHERE T2.[Action] = ''Modify'''
EXEC (@queryUpd)

Native query with named parameter fails with "Not all named parameters have been set"

I use EclipseLink. This JPA allows the following way for the native queries:

Query q = em.createNativeQuery("SELECT * FROM mytable where username = ?username");
q.setParameter("username", "test");
q.getResultList();

How to convert String to DOM Document object in java?

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.

this works well for me even though the XML structure is complex.

And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.

The main problem might not come from the attributes.

Using python map and other functional tools

import itertools

foos=[1.0, 2.0, 3.0, 4.0, 5.0]
bars=[1, 2, 3]

print zip(foos, itertools.cycle([bars]))

Zero-pad digits in string

Solution using str_pad:

str_pad($digit,2,'0',STR_PAD_LEFT);

Benchmark on php 5.3

Result str_pad : 0.286863088608

Result sprintf : 0.234171152115

Code:

$start = microtime(true);
for ($i=0;$i<100000;$i++) {
    str_pad(9,2,'0',STR_PAD_LEFT);
    str_pad(15,2,'0',STR_PAD_LEFT);
    str_pad(100,2,'0',STR_PAD_LEFT);
}
$end = microtime(true);
echo "Result str_pad : ",($end-$start),"\n";

$start = microtime(true);
for ($i=0;$i<100000;$i++) {
    sprintf("%02d", 9);
    sprintf("%02d", 15);
    sprintf("%02d", 100);
}
$end = microtime(true);
echo "Result sprintf : ",($end-$start),"\n";

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

You can use this tool to create appropriate c# classes:

http://jsonclassgenerator.codeplex.com/

and when you will have classes created you can simply convert string to object:

    public static T ParseJsonObject<T>(string json) where T : class, new()
    {
        JObject jobject = JObject.Parse(json);
        return JsonConvert.DeserializeObject<T>(jobject.ToString());
    }

Here that classes: http://ge.tt/2KGtbPT/v/0?c

Just fix namespaces.

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

PDO does support this (as of 2020). Just do a query() call on a PDO object as usual, separating queries by ; and then nextRowset() to step to the next SELECT result, if you have multiple. Resultsets will be in the same order as the queries. Obviously think about the security implications - so don't accept user supplied queries, use parameters, etc. I use it with queries generated by code for example.

$statement = $connection->query($query);
do {
  $data[] = $statement->fetchAll(PDO::FETCH_ASSOC);
} while ($statement->nextRowset());

Replacing some characters in a string with another character

Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _:

$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN

Notice that the +(pattern) pattern requires extended pattern matching, turned on with

shopt -s extglob

Alternatively, with the -s ("squeeze") option of tr:

$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN

How to add property to a class dynamically?

Here is the simple example to create property object programmatically.

#!/usr/bin/python3

class Counter:
    def __init__(self):
        cls = self.__class__
        self._count = 0
        cls.count = self.count_ref()

    def count_get(self):
        print(f'count_get: {self._count}')
        return self._count

    def count_set(self, value):
        self._count = value
        print(f'count_set: {self._count}')

    def count_del(self):
        print(f'count_del: {self._count}')

    def count_ref(self):
        cls = self.__class__
        return property(fget=cls.count_get, fset=cls.count_set, fdel=cls.count_del)

counter = Counter()

counter.count
for i in range(5):
    counter.count = i
del counter.count

'''
output
======
count_get: 0
count_set: 0
count_set: 1
count_set: 2
count_set: 3
count_set: 4
count_del: 4
'''

Github Push Error: RPC failed; result=22, HTTP code = 413

For those who use IIS 7 to host a git http/https endpoint:

You need to increase your uploadReadAheadSize.

Launch Internet Information Services (IIS) Manager

  1. Expand the Server field

  2. Expand Sites

  3. Select the site you want to make the modification for.

  4. In the Features section, double click Configuration Editor

  5. Under Section select: system.webServer > serverRuntime

  6. Modify the uploadReadAheadSize section (The value must be between 0 and 2147483647.)

  7. Click Apply

  8. Restart the Website

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

I had the same issue. after adding below code to my app.js file it fixed.

var cors = require('cors')
app.use(cors());

Using CRON jobs to visit url?

Here is simple example. you can use it like

wget -q -O - http://example.com/backup >/dev/null 2>&1

and in start you can add your option like (*****). Its up to your system requirements either you want to run it every minute or hours etc.

How do I find the length of an array?

std::vector has a method size() which returns the number of elements in the vector.

(Yes, this is tongue-in-cheek answer)

Using Get-childitem to get a list of files modified in the last 3 days

Very similar to previous responses, but the is from the current directory, looks at any file and only for ones that are 4 days old. This is what I needed for my research and the above answers were all very helpful. Thanks.

Get-ChildItem -Path . -Recurse| ? {$_.LastWriteTime -gt (Get-Date).AddDays(-4)}

Laravel 5: Display HTML with Blade

By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

According to the doc, you must do the following to render your html in your Blade files:

{!! $text !!}

Be very careful when echoing content that is supplied by users of your application. You should typically use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.

How to show multiline text in a table cell

Wrap the content in a <pre> (pre-formatted text) tag

<pre>hello ,
my name is x.</pre>

Android: making a fullscreen application

According to this document, add the following code to onCreate

getWindow().getDecorView().setSystemUiVisibility(SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
        SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION   | 
        SYSTEM_UI_FLAG_LAYOUT_STABLE | SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

When should the xlsm or xlsb formats be used?

They're all similar in that they're essentially zip files containing the actual file components. You can see the contents just by replacing the extension with .zip and opening them up. The difference with xlsb seems to be that the components are not XML-based but are in a binary format: supposedly this is beneficial when working with large files.

https://blogs.msdn.microsoft.com/dmahugh/2006/08/22/new-binary-file-format-for-spreadsheets/

How do I send a JSON string in a POST request in Go

I'm not familiar with napping, but using Golang's net/http package works fine (playground):

func main() {
    url := "http://restapi3.apiary.io/notes"
    fmt.Println("URL:>", url)

    var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
}

Is it possible to use argsort in descending order?

You can use the flip commands numpy.flipud() or numpy.fliplr() to get the indexes in descending order after sorting using the argsort command. Thats what I usually do.

Can jQuery provide the tag name?

I think you cannot use the nodeName in jQuery since nodeName is a DOM property and jQuery itself do not have a either a nodeName function or property. But based on the respondent who first mentioned about this nodeName stuff, this is how I was able to resolve the problem:

this.attr("id", "rnd" + this.attr("nodeName") + "_" + i.toString());

NOTE: this here is a jQuery object.

Replacing .NET WebBrowser control with a better browser, like Chrome?

Geckofx and Webkit.net were both promising at first, but they didn't keep up to date with Firefox and Chrome respectively while as Internet Explorer improved, so did the Webbrowser control, though it behaves like IE7 by default regardless of what IE version you have but that can be fixed by going into the registry and change it to IE9 allowing HTML5.

ORA-01653: unable to extend table by in tablespace ORA-06512

You could also turn on autoextend for the whole database using this command:

ALTER DATABASE DATAFILE 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\SYSTEM.DBF'
AUTOEXTEND ON NEXT 1M MAXSIZE 1024M;

Just change the filepath to point to your system.dbf file.

Credit Here

How to prevent default event handling in an onclick method?

In my opinion the answer is wrong! He asked for event.preventDefault(); when you simply return false; it calls event.preventDefault(); AND event.stopPropagation(); as well!

You can solve it by this:

<a href="#" onclick="callmymethod(event, 24)">Call</a>
function callmymethod(e, myVal){
    //doing custom things with myVal

    //here I want to prevent default
    e = e || window.event;
    e.preventDefault();
}

What is the strict aliasing rule?

A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to uint32_ts or uint16_ts). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.

So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:

typedef struct Msg
{
    unsigned int a;
    unsigned int b;
} Msg;

void SendWord(uint32_t);

int main(void)
{
    // Get a 32-bit buffer from the system
    uint32_t* buff = malloc(sizeof(Msg));
    
    // Alias that buffer through message
    Msg* msg = (Msg*)(buff);
    
    // Send a bunch of messages    
    for (int i = 0; i < 10; ++i)
    {
        msg->a = i;
        msg->b = i+1;
        SendWord(buff[0]);
        SendWord(buff[1]);   
    }
}

The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a compatible type or one of the other types allowed by C 2011 6.5 paragraph 71 is undefined behavior. Unfortunately, you can still code this way, maybe get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code.

(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)

To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of buff every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load buff[0] and buff[1] into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of buff could change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.

Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.

void SendMessage(uint32_t* buff, size_t size32)
{
    for (int i = 0; i < size32; ++i) 
    {
        SendWord(buff[i]);
    }
}

And rewrote our earlier loop to take advantage of this convenient function

for (int i = 0; i < 10; ++i)
{
    msg->a = i;
    msg->b = i+1;
    SendMessage(buff, 2);
}

The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If SendMessage is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.

So how do I get around this?

  • Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.

      union {
          Msg msg;
          unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];
      };
    
  • You can disable strict aliasing in your compiler (f[no-]strict-aliasing in gcc))

  • You can use char* for aliasing instead of your system's word. The rules allow an exception for char* (including signed char and unsigned char). It's always assumed that char* aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.

Beginner beware

This is only one potential minefield when overlaying two types onto each other. You should also learn about endianness, word alignment, and how to deal with alignment issues through packing structs correctly.

Footnote

1 The types that C 2011 6.5 7 allows an lvalue to access are:

  • a type compatible with the effective type of the object,
  • a qualified version of a type compatible with the effective type of the object,
  • a type that is the signed or unsigned type corresponding to the effective type of the object,
  • a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
  • a character type.

Call JavaScript function on DropDownList SelectedIndexChanged Event:

You can use the ScriptManager.RegisterStartupScript(); to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();, you can do this:

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
 //----or alternatively and to be more proper
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}

To be exact for you, do this...

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}

Javascript replace with reference to matched group?

You can use replace instead of gsub.

"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")

Redirect all output to file in Bash

That part is written to stderr, use 2> to redirect it. For example:

foo > stdout.txt 2> stderr.txt

or if you want in same file:

foo > allout.txt 2>&1

Note: this works in (ba)sh, check your shell for proper syntax

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

You can have better performance by using the following method:

SELECT COUNT(1) FROM (SELECT /*+FIRST_ROWS*/ column_name 
FROM table_name 
WHERE column_name = 'xxxxx' AND ROWNUM = 1);

Is it necessary to assign a string to a variable before comparing it to another?

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:

NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];

How to calculate number of days between two dates

I made a quick re-usable function in ES6 using Moment.js.

_x000D_
_x000D_
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {_x000D_
  const getDateAsArray = (date) => {_x000D_
    return moment(date.split(/\D+/), date_format);_x000D_
  }_x000D_
  return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;_x000D_
}_x000D_
_x000D_
console.log(getDaysDiff('2019-10-01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019/10/01', '2019/10/30'));_x000D_
console.log(getDaysDiff('2019.10-01', '2019.10 30'));_x000D_
console.log(getDaysDiff('2019 10 01', '2019 10 30'));_x000D_
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));_x000D_
_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019'));_x000D_
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
_x000D_
_x000D_
_x000D_

How to fix Error: laravel.log could not be opened?

This solution is specific for laravel 5.5

You have to change permissions to a few folders: chmod -R -777 storage/logs chmod -R -777 storage/framework for the above folders 775 or 765 did not work for my project

chmod -R 775 bootstrap/cache 

Also the ownership of the project folder should be as follows (current user):(web server user)

Converting HTML element to string in JavaScript / JQuery

(document.body.outerHTML).constructor will return String. (take off .constructor and that's your string)

That aughta do it :)

The static keyword and its various uses in C++

In order to clarify the question, I would rather categorize the usage of 'static' keyword in three different forms:

(A). variables

(B). functions

(C). member variables/functions of classes

the explanation follows below for each of the sub headings:

(A) 'static' keyword for variables

This one can be little tricky however if explained and understood properly, it's pretty straightforward.

To explain this, first it is really useful to know about the scope, duration and linkage of variables, without which things are always difficult to see through the murky concept of staic keyword

1. Scope : Determines where in the file, the variable is accessible. It can be of two types: (i) Local or Block Scope. (ii) Global Scope

2. Duration : Determines when a variable is created and destroyed. Again it's of two types: (i) Automatic Storage Duration (for variables having Local or Block scope). (ii) Static Storage Duration (for variables having Global Scope or local variables (in a function or a in a code block) with static specifier).

3. Linkage: Determines whether a variable can be accessed (or linked ) in another file. Again ( and luckily) it is of two types: (i) Internal Linkage (for variables having Block Scope and Global Scope/File Scope/Global Namespace scope) (ii) External Linkage (for variables having only for Global Scope/File Scope/Global Namespace Scope)

Let's refer an example below for better understanding of plain global and local variables (no local variables with static storage duration) :

//main file
#include <iostream>

int global_var1; //has global scope
const global_var2(1.618); //has global scope

int main()
{
//these variables are local to the block main.
//they have automatic duration, i.e, they are created when the main() is 
//  executed and destroyed, when main goes out of scope
 int local_var1(23);
 const double local_var2(3.14);

 {
/* this is yet another block, all variables declared within this block are 
 have local scope limited within this block. */
// all variables declared within this block too have automatic duration, i.e, 
/*they are created at the point of definition within this block,
 and destroyed as soon as this block ends */
   char block_char1;
   int local_var1(32) //NOTE: this has been re-declared within the block, 
//it shadows the local_var1 declared outside

 std::cout << local_var1 <<"\n"; //prints 32

  }//end of block
  //local_var1 declared inside goes out of scope

 std::cout << local_var1 << "\n"; //prints 23

 global_var1 = 29; //global_var1 has been declared outside main (global scope)
 std::cout << global_var1 << "\n"; //prints 29
 std::cout << global_var2 << "\n"; //prints 1.618

 return 0;
}  //local_var1, local_var2 go out of scope as main ends
//global_var1, global_var2 go out of scope as the program terminates 
//(in this case program ends with end of main, so both local and global
//variable go out of scope together

Now comes the concept of Linkage. When a global variable defined in one file is intended to be used in another file, the linkage of the variable plays an important role.

The Linkage of global variables is specified by the keywords: (i) static , and, (ii) extern

( Now you get the explanation )

static keyword can be applied to variables with local and global scope, and in both the cases, they mean different things. I will first explain the usage of 'static' keyword in variables with global scope ( where I also clarify the usage of keyword 'extern') and later the for those with local scope.

1. Static Keyword for variables with global scope

Global variables have static duration, meaning they don't go out of scope when a particular block of code (for e.g main() ) in which it is used ends . Depending upon the linkage, they can be either accessed only within the same file where they are declared (for static global variable), or outside the file even outside the file in which they are declared (extern type global variables)

In the case of a global variable having extern specifier, and if this variable is being accessed outside the file in which it has been initialized, it has to be forward declared in the file where it's being used, just like a function has to be forward declared if it's definition is in a file different from where it's being used.

In contrast, if the global variable has static keyword, it cannot be used in a file outside of which it has been declared.

(see example below for clarification)

eg:

//main2.cpp
 static int global_var3 = 23;  /*static global variable, cannot be                            
                                accessed in anyother file */
 extern double global_var4 = 71; /*can be accessed outside this file                  linked to main2.cpp */
 int main() { return 0; }

main3.cpp

//main3.cpp
#include <iostream>

int main()
{
   extern int gloabl_var4; /*this variable refers to the gloabal_var4
                            defined in the main2.cpp file */
  std::cout << global_var4 << "\n"; //prints 71;

  return 0;
}

now any variable in c++ can be either a const or a non-const and for each 'const-ness' we get two case of default c++ linkage, in case none is specified:

(i) If a global variable is non-const, its linkage is extern by default, i.e, the non-const global variable can be accessed in another .cpp file by forward declaration using the extern keyword (in other words, non const global variables have external linkage ( with static duration of course)). Also usage of extern keyword in the original file where it has been defined is redundant. In this case to make a non-const global variable inaccessible to external file, use the specifier 'static' before the type of the variable.

(ii) If a global variable is const, its linkage is static by default, i.e a const global variable cannot be accessed in a file other than where it is defined, (in other words, const global variables have internal linkage (with static duration of course)). Also usage of static keyword to prevent a const global variable from being accessed in another file is redundant. Here, to make a const global variable have an external linkage, use the specifier 'extern' before the type of the variable

Here's a summary for global scope variables with various linkages

//globalVariables1.cpp 

// defining uninitialized vairbles
int globalVar1; //  uninitialized global variable with external linkage 
static int globalVar2; // uninitialized global variable with internal linkage
const int globalVar3; // error, since const variables must be initialized upon declaration
const int globalVar4 = 23; //correct, but with static linkage (cannot be accessed outside the file where it has been declared*/
extern const double globalVar5 = 1.57; //this const variable ca be accessed outside the file where it has been declared

Next we investigate how the above global variables behave when accessed in a different file.

//using_globalVariables1.cpp (eg for the usage of global variables above)

// Forward declaration via extern keyword:
 extern int globalVar1; // correct since globalVar1 is not a const or static
 extern int globalVar2; //incorrect since globalVar2 has internal linkage
 extern const int globalVar4; /* incorrect since globalVar4 has no extern 
                         specifier, limited to internal linkage by
                         default (static specifier for const variables) */
 extern const double globalVar5; /*correct since in the previous file, it 
                           has extern specifier, no need to initialize the
                       const variable here, since it has already been
                       legitimately defined perviously */

2. Static Keyword for variables with Local Scope

Updates (August 2019) on static keyword for variables in local scope

This further can be subdivided in two categories :

(i) static keyword for variables within a function block, and (ii) static keyword for variables within a unnamed local block.

(i) static keyword for variables within a function block.

Earlier, I mentioned that variables with local scope have automatic duration, i.e they come to exist when the block is entered ( be it a normal block, be it a function block) and cease to exist when the block ends, long story short, variables with local scope have automatic duration and automatic duration variables (and objects) have no linkage meaning they are not visible outside the code block.

If static specifier is applied to a local variable within a function block, it changes the duration of the variable from automatic to static and its life time is the entire duration of the program which means it has a fixed memory location and its value is initialized only once prior to program start up as mentioned in cpp reference(initialization should not be confused with assignment)

lets take a look at an example.

//localVarDemo1.cpp    
 int localNextID()
{
  int tempID = 1;  //tempID created here
  return tempID++; //copy of tempID returned and tempID incremented to 2
} //tempID destroyed here, hence value of tempID lost

int newNextID()
{
  static int newID = 0;//newID has static duration, with internal linkage
  return newID++; //copy of newID returned and newID incremented by 1
}  //newID doesn't get destroyed here :-)


int main()
{
  int employeeID1 = localNextID();  //employeeID1 = 1
  int employeeID2 = localNextID();  // employeeID2 = 1 again (not desired)
  int employeeID3 = newNextID(); //employeeID3 = 0;
  int employeeID4 = newNextID(); //employeeID4 = 1;
  int employeeID5 = newNextID(); //employeeID5 = 2;
  return 0;
}

Looking at the above criterion for static local variables and static global variables, one might be tempted to ask, what the difference between them could be. While global variables are accessible at any point in within the code (in same as well as different translation unit depending upon the const-ness and extern-ness), a static variable defined within a function block is not directly accessible. The variable has to be returned by the function value or reference. Lets demonstrate this by an example:

//localVarDemo2.cpp 

//static storage duration with global scope 
//note this variable can be accessed from outside the file
//in a different compilation unit by using `extern` specifier
//which might not be desirable for certain use case.
static int globalId = 0;

int newNextID()
{
  static int newID = 0;//newID has static duration, with internal linkage
  return newID++; //copy of newID returned and newID incremented by 1
}  //newID doesn't get destroyed here


int main()
{
    //since globalId is accessible we use it directly
  const int globalEmployee1Id = globalId++; //globalEmployeeId1 = 0;
  const int globalEmployee2Id = globalId++; //globalEmployeeId1 = 1;

  //const int employeeID1 = newID++; //this will lead to compilation error since newID++ is not accessible direcly. 
  int employeeID2 = newNextID(); //employeeID3 = 0;
  int employeeID2 = newNextID(); //employeeID3 = 1;

  return 0;
}

More explaination about choice of static global and static local variable could be found on this stackoverflow thread

(ii) static keyword for variables within a unnamed local block.

static variables within a local block (not a function block) cannot be accessed outside the block once the local block goes out of scope. No caveats to this rule.

    //localVarDemo3.cpp 
    int main()
    {

      {
          const static int static_local_scoped_variable {99};
      }//static_local_scoped_variable goes out of scope

      //the line below causes compilation error
      //do_something is an arbitrary function
      do_something(static_local_scoped_variable);
      return 0;
    }

C++11 introduced the keyword constexpr which guarantees the evaluation of an expression at compile time and allows compiler to optimize the code. Now if the value of a static const variable within a scope is known at compile time, the code is optimized in a manner similar to the one with constexpr. Here's a small example

I recommend readers also to look up the difference between constexprand static const for variables in this stackoverflow thread. this concludes my explanation for the static keyword applied to variables.

B. 'static' keyword used for functions

in terms of functions, the static keyword has a straightforward meaning. Here, it refers to linkage of the function Normally all functions declared within a cpp file have external linkage by default, i.e a function defined in one file can be used in another cpp file by forward declaration.

using a static keyword before the function declaration limits its linkage to internal , i.e a static function cannot be used within a file outside of its definition.

C. Staitc Keyword used for member variables and functions of classes

1. 'static' keyword for member variables of classes

I start directly with an example here

#include <iostream>

class DesignNumber
{
  private:

      static int m_designNum;  //design number
      int m_iteration;     // number of iterations performed for the design

  public:
    DesignNumber() {     }  //default constructor

   int  getItrNum() //get the iteration number of design
   {
      m_iteration = m_designNum++;
      return m_iteration;
   }
     static int m_anyNumber;  //public static variable
};
int DesignNumber::m_designNum = 0; // starting with design id = 0
                     // note : no need of static keyword here
                     //causes compiler error if static keyword used
int DesignNumber::m_anyNumber = 99; /* initialization of inclass public 
                                    static member  */
enter code here

int main()
{
   DesignNumber firstDesign, secondDesign, thirdDesign;
   std::cout << firstDesign.getItrNum() << "\n";  //prints 0
   std::cout << secondDesign.getItrNum() << "\n"; //prints 1
   std::cout << thirdDesign.getItrNum() << "\n";  //prints 2

   std::cout << DesignNumber::m_anyNumber++ << "\n";  /* no object
                                        associated with m_anyNumber */
   std::cout << DesignNumber::m_anyNumber++ << "\n"; //prints 100
   std::cout << DesignNumber::m_anyNumber++ << "\n"; //prints 101

   return 0;
}

In this example, the static variable m_designNum retains its value and this single private member variable (because it's static) is shared b/w all the variables of the object type DesignNumber

Also like other member variables, static member variables of a class are not associated with any class object, which is demonstrated by the printing of anyNumber in the main function

const vs non-const static member variables in class

(i) non-const class static member variables In the previous example the static members (both public and private) were non constants. ISO standard forbids non-const static members to be initialized in the class. Hence as in previous example, they must be initalized after the class definition, with the caveat that the static keyword needs to be omitted

(ii) const-static member variables of class this is straightforward and goes with the convention of other const member variable initialization, i.e the const static member variables of a class can be initialized at the point of declaration and they can be initialized at the end of the class declaration with one caveat that the keyword const needs to be added to the static member when being initialized after the class definition.

I would however, recommend to initialize the const static member variables at the point of declaration. This goes with the standard C++ convention and makes the code look cleaner

for more examples on static member variables in a class look up the following link from learncpp.com http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

2. 'static' keyword for member function of classes

Just like member variables of classes can ,be static, so can member functions of classes. Normal member functions of classes are always associated with a object of the class type. In contrast, static member functions of a class are not associated with any object of the class, i.e they have no *this pointer.

Secondly since the static member functions of the class have no *this pointer, they can be called using the class name and scope resolution operator in the main function (ClassName::functionName(); )

Thirdly static member functions of a class can only access static member variables of a class, since non-static member variables of a class must belong to a class object.

for more examples on static member functions in a class look up the following link from learncpp.com

http://www.learncpp.com/cpp-tutorial/812-static-member-functions/

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

I got this same error when installing to an actual device. More information and a solution to loading the missing libraries to the device can be found at the following site:

Fixing the INSTALL_FAILED_MISSING_SHARED_LIBRARY Error

To set this up correctly, there are 2 key files that need to be copied to the system:

com.google.android.maps.xml

com.google.android.maps.jar

These files are located in the any of these google app packs:

http://android.d3xt3...0120-signed.zip

http://goo-inside.me...0120-signed.zip

http://android.local...0120-signed.zip

These links no longer work, but you can find the files in the android sdk if you have Google Maps API v1

After unzipping any of these files, you want to copy the files to your system, like-ah-so:

adb remount

adb push system/etc/permissions/com.google.android.maps.xml /system/etc/permissions

adb push system/framework/com.google.android.maps.jar /system/framework

adb reboot

How to use timer in C?

May be this examples help to you

#include <stdio.h>
#include <time.h>
#include <stdlib.h>


/*
    Implementation simple timeout

    Input: count milliseconds as number

    Usage:
        setTimeout(1000) - timeout on 1 second
        setTimeout(10100) - timeout on 10 seconds and 100 milliseconds
 */
void setTimeout(int milliseconds)
{
    // If milliseconds is less or equal to 0
    // will be simple return from function without throw error
    if (milliseconds <= 0) {
        fprintf(stderr, "Count milliseconds for timeout is less or equal to 0\n");
        return;
    }

    // a current time of milliseconds
    int milliseconds_since = clock() * 1000 / CLOCKS_PER_SEC;

    // needed count milliseconds of return from this timeout
    int end = milliseconds_since + milliseconds;

    // wait while until needed time comes
    do {
        milliseconds_since = clock() * 1000 / CLOCKS_PER_SEC;
    } while (milliseconds_since <= end);
}


int main()
{

    // input from user for time of delay in seconds
    int delay;
    printf("Enter delay: ");
    scanf("%d", &delay);

    // counter downtime for run a rocket while the delay with more 0
    do {
        // erase the previous line and display remain of the delay
        printf("\033[ATime left for run rocket: %d\n", delay);

        // a timeout for display
        setTimeout(1000);

        // decrease the delay to 1
        delay--;

    } while (delay >= 0);

    // a string for display rocket
    char rocket[3] = "-->";

    // a string for display all trace of the rocket and the rocket itself
    char *rocket_trace = (char *) malloc(100 * sizeof(char));

    // display trace of the rocket from a start to the end
    int i;
    char passed_way[100] = "";
    for (i = 0; i <= 50; i++) {
        setTimeout(25);
        sprintf(rocket_trace, "%s%s", passed_way, rocket);
        passed_way[i] = ' ';
        printf("\033[A");
        printf("| %s\n", rocket_trace);
    }

    // erase a line and write a new line
    printf("\033[A");
    printf("\033[2K");
    puts("Good luck!");

    return 0;
}

Compile file, run and delete after (my preference)

$ gcc timeout.c -o timeout && ./timeout && rm timeout

Try run it for yourself to see result.

Notes:

Testing environment

$ uname -a
Linux wlysenko-Aspire 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
$ gcc --version
gcc (Ubuntu 4.8.5-2ubuntu1~14.04.1) 4.8.5
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Exporting PDF with jspdf not rendering CSS

As I know jsPDF is not working with CSS and the same issue I was facing.

To solve this issue, I used Html2Canvas. Just Add HTML2Canvas JS and then use pdf.addHTML() instead of pdf.fromHTML().

Here's my code (no other code):

 var pdf = new jsPDF('p', 'pt', 'letter');
 pdf.addHTML($('#ElementYouWantToConvertToPdf')[0], function () {
     pdf.save('Test.pdf');
 });

Best of Luck!

Edit: Refer to this line in case you didn't find .addHTML()

Get int from String, also containing letters, in Java

Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?

Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.

If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.

How to open warning/information/error dialog in Swing?

JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....

Have a look on this tutorial on how to make dialogs.

Best way to log POST data in Apache?

You can also use the built-in forensic log feature.

php static function

After trying examples (PHP 5.3.5), I found that in both cases of defining functions you can't use $this operator to work on class functions. So I couldn't find a difference in them yet. :(

Why "no projects found to import"?

One solution to this is to use Maven. From the project root folder do mvn eclipse:clean followed by mvn eclipse:eclipse. This will generate the .project and .classpath files required by eclipse.

How to convert a plain object into an ES6 Map?

The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:

Converting an Object to a Map

The new Map() constructor accepts an iterable of entries. With Object.entries, you can easily convert from Object to Map:

const obj = { foo: 'bar', baz: 42 }; 
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

Execute Stored Procedure from a Function

Functions are not allowed to have side-effects such as altering table contents.

Stored Procedures are.

If a function called a stored procedure, the function would become able to have side-effects.


So, sorry, but no, you can't call a stored procedure from a function.

showing that a date is greater than current date

For those that want a nice conditional:

DECLARE @MyDate DATETIME  = 'some date in future' --example  DateAdd(day,5,GetDate())

IF @MyDate < DATEADD(DAY,1,GETDATE())
    BEGIN
        PRINT 'Date NOT greater than today...'
END
ELSE 
    BEGIN
       PRINT 'Date greater than today...'
END 

How to format x-axis time scale values in Chart.js v2

You could format the dates before you add them to your array. That is how I did. I used AngularJS

//convert the date to a standard format

var dt = new Date(date);

//take only the date and month and push them to your label array

$rootScope.charts.mainChart.labels.push(dt.getDate() + "-" + (dt.getMonth() + 1));

Use this array in your chart presentation

C++ for each, pulling from vector elements

For next examples assumed that you use C++11. Example with ranged-based for loops:

for (auto &attack : m_attack) // access by reference to avoid copying
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

You should use const auto &attack depending on the behavior of makeDamage().

You can use std::for_each from standard library + lambdas:

std::for_each(m_attack.begin(), m_attack.end(),
        [](Attack * attack)
        {
            if (attack->m_num == input)
            {
                attack->makeDamage();
            }
        }
);

If you are uncomfortable using std::for_each, you can loop over m_attack using iterators:

for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

Use m_attack.cbegin() and m_attack.cend() to get const iterators.

Using generic std::function objects with member functions in one class

You can avoid std::bind doing this:

std::function<void(void)> f = [this]-> {Foo::doSomething();}

Make Https call using HttpClient

When connect to https I got this error too, I add this line before HttpClient httpClient = new HttpClient(); and connect successfully:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

I know it from This Answer and Another Similar Anwser and the comment mentions:

This is a hack useful in development so putting a #if DEBUG #endif statement around it is the least you should do to make this safer and stop this ending up in production

Besides, I didn't try the method in Another Answer that use new X509Certificate() or new X509Certificate2() to make a Certificate, I'm not sure simply create by new() will work or not.

EDIT: Some References:

Create a Self-Signed Server Certificate in IIS 7

Import and Export SSL Certificates in IIS 7

Convert .pfx to .cer

Best practices for using ServerCertificateValidationCallback

I find value of Thumbprint is equal to x509certificate.GetCertHashString():

Retrieve the Thumbprint of a Certificate

Getting and removing the first character of a string

substring is definitely best, but here's one strsplit alternative, since I haven't seen one yet.

> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"

or equivalently

> unlist(strsplit(x, ''))[1]
## [1] "h"

And you can paste the rest of the string back together.

> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"

How to run SUDO command in WinSCP to transfer files from Windows to linux

I know this is old, but it is actually very possible.

  • Go to your WinSCP profile (Session > Sites > Site Manager)

  • Click on Edit > Advanced... > Environment > SFTP

  • Insert sudo su -c /usr/lib/sftp-server in "SFTP Server" (note this path might be different in your system)

  • Save and connect

Source

AWS Ubuntu 18.04: enter image description here

configure Git to accept a particular self-signed server certificate for a particular https remote

OSX User adjustments.

Following the steps of the Accepted answer worked for me with a small addition when configuring on OSX.

I put the cert.pem file in a directory under my OSX logged in user and thus caused me to adjust the location for the trusted certificate.

Configure git to trust this certificate:

$ git config --global http.sslCAInfo $HOME/git-certs/cert.pem

How to switch to another domain and get-aduser

get-aduser -Server "servername" -Identity %username% -Properties *

get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *

These work when you have the username. Also less to type than using the -filter property.

EDIT: Formatting.

Quoting backslashes in Python string literals

Use a raw string:

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'

Note that although it looks wrong, it's actually right. There is only one backslash in the string foo.

This happens because when you just type foo at the prompt, python displays the result of __repr__() on the string. This leads to the following (notice only one backslash and no quotes around the printed string):

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:

>>> foo = r'baz \'
  File "<stdin>", line 1
    foo = r'baz \'
                 ^  
SyntaxError: EOL while scanning single-quoted string

Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:

>>> foo = 'baz \\'
>>> print(foo)
baz \

However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath() function:

myfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)

This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.

round a single column in pandas

If you are doing machine learning and use tensorflow, many float are of 'float32', not 'float64', and none of the methods mentioned in this thread likely to work. You will have to first convert to float64 first.

x.astype('float')

before round(...).

How to center text vertically with a large font-awesome icon?

I just had to do this myself, you need to do it the other way around.

  • do not play with the vertical-align of your text
  • play with the vertical align of the font-awesome icon
<div>
  <span class="icon icon-2x icon-camera" style=" vertical-align: middle;"></span>
  <span class="my-text">hello world</span>
</div>

Of course you could not use inline styles and target it with your own css class. But this works in a copy paste fashion.

See here: Vertical alignment of text and icon in button

If it were up to me however, I would not use the icon-2x. And simply specify the font-size myself, as in the following

<div class='my-fancy-container'>
    <span class='my-icon icon-file-text'></span>
    <span class='my-text'>Hello World</span>
</div>
.my-icon {
    vertical-align: middle;
    font-size: 40px;
}

.my-text {
    font-family: "Courier-new";
}

.my-fancy-container {
    border: 1px solid #ccc;
    border-radius: 6px;
    display: inline-block;
    margin: 60px;
    padding: 10px;
}

for a working example, please see JsFiddle

How do I center content in a div using CSS?

Update 2020:

There are several options available*:

*Disclaimer: This list may not be complete.

Using Flexbox
Nowadays, we can use flexbox. It is quite a handy alternative to the css-transform option. I would use this solution almost always. If it is just one element maybe not, but for example if I had to support an array of data e.g. rows and columns and I want them to be relatively centered in the very middle.

_x000D_
_x000D_
.flexbox {
  display: flex;
  height: 100px;
  flex-flow: row wrap;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  /* default => flex: 0 1 auto */
  background-color: #fff;
  border: 1px dotted #333;
  box-sizing: border-box;
}
_x000D_
<div class="flexbox">
  <div class="item">I am centered in the middle.</div>
  <div class="item">I am centered in the middle, too.</div>
</div>
_x000D_
_x000D_
_x000D_


Using CSS 2D-Transform
This is still a good option, was also the accepted solution back in 2015. It is very slim and simple to apply and does not mess with the layouting of other elements.

_x000D_
_x000D_
.boxes {
  position: relative;
}

.box {
  position: relative;
  display: inline-block;
  float: left;
  width: 200px;
  height: 200px;
  font-weight: bold;
  color: #333;
  margin-right: 10px;
  margin-bottom: 10px;
  background-color: #eaeaea;
}

.h-center {
  text-align: center;
}

.v-center span {
  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translate(0, -50%);
}
_x000D_
<div class="boxes">
  <div class="box h-center">horizontally centered lorem ipsun dolor sit amet</div>
  <div class="box v-center"><span>vertically centered lorem ipsun dolor sit amet lorem ipsun dolor sit amet</span></div>
  <div class="box h-center v-center"><span>horizontally and vertically centered lorem ipsun dolor sit amet</span></div>
</div>
_x000D_
_x000D_
_x000D_

Note: This does also work with :after and :before pseudo-elements.


Using Grid
This might just be an overkill, but it depends on your DOM. If you want to use grid anyway, then why not. It is very powerful alternative and you are really maximum flexible with the design.

Note: To align the items vertically we use flexbox in combination with grid. But we could also use display: grid on the items.

_x000D_
_x000D_
.grid {
  display: grid;
  width: 400px;
  grid-template-rows: 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dotted #333;
  box-sizing: border-box;
}

.item-large {
  height: 80px;
}
_x000D_
<div class="grid">
  <div class="item">Item 1</div>
  <div class="item item-large">Item 2</div>
  <div class="item">Item 3</div>
</div>
_x000D_
_x000D_
_x000D_


Further reading:

CSS article about grid
CSS article about flexbox
CSS article about centering without flexbox or grid

Load arrayList data into JTable

You can do something like what i did with my List< Future< String > > or any other Arraylist, Type returned from other class called PingScan that returns List> because it implements service executor. Anyway the code down note that you can use foreach and retrieve data from the List.

 PingScan p = new PingScan();
 List<Future<String>> scanResult = p.checkThisIP(jFormattedTextField1.getText(), jFormattedTextField2.getText());
                for (final Future<String> f : scanResult) {
                    try {
                        if (f.get() instanceof String) {
                            String ip = f.get();
                            Object[] data = {ip};
                            tableModel.addRow(data);
                        }
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

if you want to go via SSMS on the object explorer window, right click on the object you want to drop, do view dependencies.

Select option padding not working in chrome

That's not work on optionentry because it's a "system" generated drop-down menu but you can set the padding of a select.

Just reset the box-sizing property to content-box in your CSS.

The default value of select is border-box.

select {
 box-sizing: content-box;
 padding: 5px 0;
}

Use IntelliJ to generate class diagram

Now there is an official way to add "PlantUML integration" plugin to your JetBrains product.

Installation steps please refer: https://stackoverflow.com/a/53387418/5320704

How to regex in a MySQL query

In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*'). See here:

SQL Function

Description


REGEXP_LIKE

This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.

...

REGEXP_REPLACE

This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.

...

REGEXP_INSTR

This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.

...

REGEXP_SUBSTR

This function returns the actual substring matching the regular expression pattern you specify.

(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$' for a beginning (^) and end ($) match, e.g.: '^regex.*$'.)

How to load CSS Asynchronously

The trick to triggering an asynchronous stylesheet download is to use a <link> element and set an invalid value for the media attribute (I'm using media="none", but any value will do). When a media query evaluates to false, the browser will still download the stylesheet, but it won't wait for the content to be available before rendering the page.

<link rel="stylesheet" href="css.css" media="none">

Once the stylesheet has finished downloading the media attribute must be set to a valid value so the style rules will be applied to the document. The onload event is used to switch the media property to all:

<link rel="stylesheet" href="css.css" media="none" onload="if(media!='all')media='all'">

This method of loading CSS will deliver useable content to visitors much quicker than the standard approach. Critical CSS can still be served with the usual blocking approach (or you can inline it for ultimate performance) and non-critical styles can be progressively downloaded and applied later in the parsing / rendering process.

This technique uses JavaScript, but you can cater for non-JavaScript browsers by wrapping the equivalent blocking <link> elements in a <noscript> element:

<link rel="stylesheet" href="css.css" media="none" onload="if(media!='all')media='all'"><noscript><link rel="stylesheet" href="css.css"></noscript>

You can see the operation in www.itcha.edu.sv

enter image description here

Source in http://keithclark.co.uk/

Regular expression to match standard 10 digit phone number

Above regex is a slight modification of @Francis Gagnon.

Objective : To detect any possible pattern a user can share their US phone number


Version 1:

^\s*(?:\+?(\d{1,3}))?[\W\D\s]*(\d[\W\D\s]*?\d[\D\W\s]*?\d)[\W\D\s]*(\d[\W\D\s]*?\d[\D\W\s]*?\d)[\W\D\s]*(\d[\W\D\s]*?\d[\D\W\s]*?\d[\W\D\s]*?\d)(?: *x(\d+))?\s*$

Test it over here Codepen: https://codepen.io/kiranbhattarai/pen/NWKMXQO

Explanation of the regex : https://regexr.com/4kt5j


Version 2:

\s*(?:\+?(\d{1,3}))?[\W\D\s]^|()*(\d[\W\D\s]*?\d[\D\W\s]*?\d)[\W\D\s]*(\d[\W\D\s]*?\d[\D\W\s]*?\d)[\W\D\s]*(\d[\W\D\s]*?\d[\D\W\s]*?\d[\W\D\s]*?\d)(?: *x(\d+))?\s*$

What is in it: The test cases can be a part of the string. In version one the test cases should be a start of a line to work.

Codepen: https://codepen.io/kiranbhattarai/pen/GRKGNGG

Explanation of the regex : https://regexr.com/4kt9n


If you can find a pattern that can fail please do comment i will fix it.

Test Cases: Pass

8 0   0  4  4  4  5   55 5
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
800 555 1234x5678
8005551234 x5678
1    800    555-1234
1----800----555-1234
800 (555) 1234
800(555)1234
8 0 0 5 5 5 1 2 3 4
8.0.0.5.5.5.1.2.3.4
8-0-0-5-5-5-1-2-3-4
(8)005551234
(80)05551234
8(00)5551234
8@0@0@5551234
8/0/0/5/5/5/1/2/3/4
8*0*0*5*5*5*1*2*3*4
8:0:0:5:5:5:1:2:3:4
8,0,0,5,5,5,1,2,3,4
800,555,1234
800:555:1234
1-718-444-1122
718-444-1122
(718)-444-1122
17184441122
7184441122
718.444.1122
1718.444.1122
1-123-456-7890
1 123-456-7890
1 (123) 456-7890
1 123 456 7890
1.123.456.7890
+91 (123) 456-7890
18005551234
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
18001234567
1 800 123 4567
1-800-123-4567
+18001234567
+1 800 123 4567
+1 (800) 123 4567
1(800)1234567
+1800 1234567
1.8001234567
1.800.123.4567
+1 (800) 123-4567
18001234567
1 800 123 4567
+1 800 123-4567
+86 800 123 4567
1-800-123-4567
1 (800) 123-4567
(800)123-4567
(800) 123-4567
(800)1234567
800-123-4567
800.123.4567
1231231231
123-1231231
123123-1231
123-123 1231
123 123-1231
123-123-1231
(123)123-1231
(123) 123-1231
(123) 123 1231
+99 1234567890
+991234567890
(555) 444-6789
555-444-6789
555.444.6789
555 444 6789
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1.800.555.1234
+1.800.555.1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
(003) 555-1212
(103) 555-1212
(911) 555-1212
18005551234
1 800 555 1234
+86 800-555-1234
1 (800) 555-1234

How can I get my Twitter Bootstrap buttons to right align?

Sorry for replying to an older already answered question, but I thought I'd point out a couple of reasons that your jsfiddle does not work, in case others check it out and wonder why the pull-right class as described in the accepted answer doesn't work there.

  1. the url to the bootstrap.css file is invalid. (perhaps it worked when you asked the question).
  2. you should add the attribute: type="button" to your input element, or it won't be rendered as a button - it will be rendered as an input box. Better yet, use the <button> element instead.
  3. Additionally, because pull-right uses floats, you will get some staggering of the button layout because each LI does not have enough height to accommodate the height of the button. Adding some line-height or min-height css to the LI would address that.

working fiddle: http://jsfiddle.net/3ejqufp6/

<ul>
  <li>One <input type="button" class="btn pull-right" value="test"/></li>
  <li>Two <input type="button" class="btn pull-right" value="test2"/></li>
</ul>

(I also added a min-width to the buttons as I couldn't stand the look of a ragged right-justified look to the buttons because of varying widths :) )

Linq to Sql: Multiple left outer joins

I figured out how to use multiple left outer joins in VB.NET using LINQ to SQL:

Dim db As New ContractDataContext()

Dim query = From o In db.Orders _
            Group Join v In db.Vendors _
            On v.VendorNumber Equals o.VendorNumber _
            Into ov = Group _
            From x In ov.DefaultIfEmpty() _
            Group Join s In db.Status _
            On s.Id Equals o.StatusId Into os = Group _
            From y In os.DefaultIfEmpty() _
            Where o.OrderNumber >= 100000 And o.OrderNumber <= 200000 _
            Select Vendor_Name = x.Name, _
                   Order_Number = o.OrderNumber, _
                   Status_Name = y.StatusName

Close a MessageBox after several seconds

Try the following approach:

AutoClosingMessageBox.Show("Text", "Caption", 1000);

Where the AutoClosingMessageBox class implemented as following:

public class AutoClosingMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    AutoClosingMessageBox(string text, string caption, int timeout) {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        using(_timeoutTimer)
            MessageBox.Show(text, caption);
    }
    public static void Show(string text, string caption, int timeout) {
        new AutoClosingMessageBox(text, caption, timeout);
    }
    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

Update: If you want to get the return value of the underlying MessageBox when user selects something before the timeout you can use the following version of this code:

var userResult = AutoClosingMessageBox.Show("Yes or No?", "Caption", 1000, MessageBoxButtons.YesNo);
if(userResult == System.Windows.Forms.DialogResult.Yes) { 
    // do something
}
...
public class AutoClosingMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    DialogResult _result;
    DialogResult _timerResult;
    AutoClosingMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        _timerResult = timerResult;
        using(_timeoutTimer)
            _result = MessageBox.Show(text, caption, buttons);
    }
    public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        return new AutoClosingMessageBox(text, caption, timeout, buttons, timerResult)._result;
    }
    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
        _result = _timerResult;
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

Yet another Update

I have checked the @Jack's case with YesNo buttons and discovered that the approach with sending the WM_CLOSE message does not work at all.
I will provide a fix in the context of the separate AutoclosingMessageBox library. This library contains redesigned approach and, I believe, can be useful to someone.
It also available via NuGet package:

Install-Package AutoClosingMessageBox

Release Notes (v1.0.0.2):
- New Show(IWin32Owner) API to support most popular scenarios (in the context of #1 );
- New Factory() API to provide full control on MessageBox showing;

Difference between break and continue statement

To prevent anything from execution if a condition is met one should use the continue and to get out of the loop if a condition is met one should use the break.

For example in the below mentioned code.

 for(int i=0;i<5;i++){

        if(i==3){

           continue;

        }
       System.out.println(i);
     }

The above code will print the result : 0 1 2 4

NOw consider this code

 for(int i=0;i<5;i++){


            if(i==3){

                break;

            }
            System.out.println(i);
         }

This code will print 0 1 2

That is the basic difference in the continue and break.

Dump all tables in CSV format using 'mysqldump'

This command will create two files in /path/to/directory table_name.sql and table_name.txt.

The SQL file will contain the table creation schema and the txt file will contain the records of the mytable table with fields delimited by a comma.

mysqldump -u username -p -t  -T/path/to/directory dbname table_name --fields-terminated-by=','

How to make HTML Text unselectable

The full modern solution to your problem is purely CSS-based, but note that older browsers won't support it, in which cases you'd need to fallback to solutions such as the others have provided.

So in pure CSS:

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;

However the mouse cursor will still change to a caret when over the element's text, so you add to that:

cursor: default;

Modern CSS is pretty elegant.

json_decode to array

json_decode support second argument, when it set to TRUE it will return an Array instead of stdClass Object. Check the Manual page of json_decode function to see all the supported arguments and its details.

For example try this:

$json_string = 'http://www.example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, TRUE); // Set second argument as TRUE
print_r($obj['Result']); // Now this will works!

How to make a progress bar

Infinitive progress bar using pure Javascript

<div id="container" style="width:100%; height:5px; border:1px solid black;">
  <div id="progress-bar" style="width:10%;background-color: green; height:5px;"></div>
</div>

<script>
  var width = 0;
  window.onload = function(e){ 
    setInterval(function () {
        width = width >= 100 ? 0 : width+5;  
        document.getElementById('progress-bar').style.width = width + '%'; }, 200);            
  }
</script>

Example http://fiddle.jshell.net/1kmum4du/

Adding HTML entities using CSS content

You have to use the escaped unicode :

Like

.breadcrumbs a:before {
    content: '\0000a0';
}

More info on : http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

Untrack files from git temporarily

you could keep your files untracked after

git rm -r --cached <file>

add your files with

git add -u

them push or do whatever you want.

jQuery Upload Progress and AJAX file upload

Here are some options for using AJAX to upload files:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

Combining the results of two SQL queries as separate columns

how to club the 4 query's as a single query

show below query

  1. total number of cases pending + 2.cases filed during this month ( base on sysdate) + total number of cases (1+2) + no. cases disposed where nse= disposed + no. of cases pending (other than nse <> disposed)

nsc = nature of case

report is taken on 06th of every month

( monthly report will be counted from 05th previous month to 05th present of present month)

How do I remove my IntelliJ license in 2019.3?

To remove the license key:

  1. Find the IntelliJ configuration directory
  2. Find the .key license file
  3. Remove or rename the .key license file

In my case on a Windows 7 machine I could find this license key in C:\Users\you\.IntelliJIdea13\config\idea13.key

psql: could not connect to server: No such file or directory (Mac OS X)

I removed /usr/lib from the LD_LIBRARY_PATH and it worked. I was working in dockerfile postgres:alpine.

What is the difference between parseInt() and Number()?

Because none mentioned, when using Number and parseInt with numeric separator, they also behave differently:

const num1 = 5_0; // 50
const num2 = Number(5_0); // 50
const num3 = Number("5_0"); // NaN
const num4 = parseInt(5_0); // 50
const num5 = parseInt("5_0"); // 5

How to edit the size of the submit button on a form?

That's easy! First, give your button an id such as <input type="button" value="I am a button!" id="myButton" /> Then, for height, and width, use CSS code:

.myButton {
    width: 100px;
    height: 100px;
}

You could also do this CSS:

input[type="button"] {
    width: 100px;
    height: 100px;
}

But that would affect all the buttons on the Page.

Working example - JSfiddle

Postgresql: password authentication failed for user "postgres"

Answer given is almost correct just missing some pointers which i'll be taking care of in my solution

First make sure your user have a sudo access if not you can use the below command to add your user as sudo user :-

sudo adduser <username> sudo

The change will take effect the next time the user logs in.

i) Now go to sudo vim /etc/postgresql/<your_postgres_version>/main/pg_hba.conf file and look for line that says :

local   all             postgres                                md5 #peer

and comment that. Just below that line there must be a commented line that says:

local   all             postgres                                peer

or for older versions it'll be :-

local   all         postgres                          ident

Uncomment that line.

ii) Now restart the postgres by using any of these commands :-

sudo /etc/init.d/postgresql restart

OR

sudo service postgresql restart

iii) Now you can simply log into postgres using the following command :

sudo -u postgres psql

iv) once you're in you can create any operation you want to in my case i wanted to create a new database you can do the same using below command :

CREATE DATABASE airflow_replica;

Radio Buttons "Checked" Attribute Not Working

This might be it:

Is there a bug with radio buttons in jQuery 1.9.1?

In short: Don't use attr() but prop() for checking radio buttons. God I hate JS...

How to use Typescript with native ES6 Promises

I had to downgrade @types/core-js to 9.36 to get it to work with "target": "es5" set in my tsconfig.

"@types/core-js": "0.9.36",

Getting date format m-d-Y H:i:s.u from milliseconds

I benched a few different ways:

1) microtime + sscanf + date:

sscanf(microtime(), '0.%6s00 %s', $usec, $sec);
$date = date('Y-m-d H:i:s.', $sec) . $usec;

I'm not sure why microtime() returns 10 chars (0.dddddd00) for the microseconds part but maybe someone can tell me ?

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { sscanf(microtime(), '0.%6s00 %s', $usec, $sec); $date = date('Y-m-d H:i:s.', $sec) . $usec; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "22372.335910797 ms" // macOS PHP 5.6.30
string(18) "16772.964000702 ms" // Linux PHP 5.4.16
string(18) "10382.229089737 ms" // Linux PHP 7.3.11 (same linux box as above)

2) DateTime::createFromFormat + Datetime->format:

$now = new DateTime('NOW');
$date = $now->format('Y-m-d H:i:s.u');

not working in PHP 5.x ...

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = new DateTime('NOW'); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "45801.825046539 ms" // macOS PHP 5.6.30 (ms not working)
string(18) "21180.155038834 ms" // Linux PHP 5.4.16 (ms not working)
string(18) "11879.796028137 ms" // Linux PHP 7.3.11 (same linux box as above)

3) gettimeofday + date:

$time = gettimeofday();
$date = date('Y-m-d H:i:s.', $time['sec']) . $time['usec'];

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $time = gettimeofday(); $date = date('Y-m-d H:i:s.', $time['sec']) . $time['usec']; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "23706.788063049 ms" // macOS PHP 5.6.30
string(18) "14984.534025192 ms" // Linux PHP 5.4.16
string(18) "7799.1390228271 ms" // Linux PHP 7.3.11 (same linux box as above)

4) microtime + number_format + DateTime::createFromFormat + DateTime->format:

$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
$date = $now->format('Y-m-d H:i:s.u');

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', '')); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "83326.496124268 ms" // macOS PHP 5.6.30
string(18) "61982.603788376 ms" // Linux PHP 5.4.16
string(16) "19107.1870327 ms" // Linux PHP 7.3.11 (same linux box as above)

5) microtime + sprintf + DateTime::createFromFormat + DateTime->format:

$now = DateTime::createFromFormat('U.u', sprintf('%.6f', microtime(true)));
$date = $now->format('Y-m-d H:i:s.u');

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = DateTime::createFromFormat('U.u', sprintf('%.6f', microtime(true))); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "79387.331962585 ms" // macOS PHP 5.6.30
string(18) "60734.437942505 ms" // Linux PHP 5.4.16
string(18) "18594.941139221 ms" // Linux PHP 7.3.11 (same linux box as above)

ASP.NET MVC: What is the purpose of @section?

It lets you define a @Section of code in your template that you can then include in other files. For example, a sidebar defined in the template, could be referenced in another included view.

//This could be used to render a @Section defined as @Section SideBar { ...
@RenderSection("SideBar", required: false);

Hope this helps.

How do I declare a model class in my Angular 2 component using TypeScript?

I realize this is a somewhat older question, but I just wanted to point out that you've add the model variable to your test widget class incorrectly. If you need a Model variable, you shouldn't be trying to pass it in through the component constructor. You are only intended to pass services or other types of injectables that way. If you are instantiating your test widget inside of another component and need to pass a model object as, I would recommend using the angular core OnInit and Input/Output design patterns.

As an example, your code should really look something like this:

import { Component, Input, OnInit } from "@angular/core";
import { YourModelLoadingService } from "../yourModuleRootFolderPath/index"

class Model {
    param1: string;
}

@Component({
    selector: "testWidget",
    template: "<div>This is a test and {{model.param1}} is my param.</div>",
    providers: [ YourModelLoadingService ]
})

export class testWidget implements OnInit {
    @Input() model: Model; //Use this if you want the parent component instantiating this
        //one to be able to directly set the model's value
    private _model: Model; //Use this if you only want the model to be private within
        //the component along with a service to load the model's value
    constructor(
        private _yourModelLoadingService: YourModelLoadingService //This service should
        //usually be provided at the module level, not the component level
    ) {}

    ngOnInit() {
        this.load();
    }

    private load() {
        //add some code to make your component read only,
        //possibly add a busy spinner on top of your view
        //This is to avoid bugs as well as communicate to the user what's
        //actually going on

        //If using the Input model so the parent scope can set the contents of model,
        //add code an event call back for when model gets set via the parent
        //On event: now that loading is done, disable read only mode and your spinner
        //if you added one

        //If using the service to set the contents of model, add code that calls your
        //service's functions that return the value of model
        //After setting the value of model, disable read only mode and your spinner
        //if you added one. Depending on if you leverage Observables, or other methods
        //this may also be done in a callback
    }
}

A class which is essentially just a struct/model should not be injected, because it means you can only have a single shared instanced of that class within the scope it was provided. In this case, that means a single instance of Model is created by the dependency injector every time testWidget is instantiated. If it were provided at the module level, you would only have a single instance shared among all components and services within that module.

Instead, you should be following standard Object Oriented practices and creating a private model variable as part of the class, and if you need to pass information into that model when you instantiate the instance, that should be handled by a service (injectable) provided by the parent module. This is how both dependency injection and communication is intended to be performed in angular.

Also, as some of the other mentioned, you should be declaring your model classes in a separate file and importing the class.

I would strongly recommend going back to the angular documentation reference and reviewing the basics pages on the various annotations and class types: https://angular.io/guide/architecture

You should pay particular attention to the sections on Modules, Components and Services/Dependency Injection as these are essential to understanding how to use Angular on an architectural level. Angular is a very architecture heavy language because it is so high level. Separation of concerns, dependency injection factories and javascript versioning for browser comparability are mainly handled for you, but you have to use their application architecture correctly or you'll find things don't work as you expect.

How to convert QString to std::string?

An alternative to the proposed:

QString qs;
std::string current_locale_text = qs.toLocal8Bit().constData();

could be:

QString qs;
std::string current_locale_text = qPrintable(qs);

See qPrintable documentation, a macro delivering a const char * from QtGlobal.

How to set up Spark on Windows?

The guide by Ani Menon (thx!) almost worked for me on windows 10, i just had to get a newer winutils.exe off that git (currently hadoop-2.8.1): https://github.com/steveloughran/winutils

Android emulator failed to allocate memory 8

In the AVD setup: Change the CPU/ABI option to MIPS. It worked for me

Timestamp Difference In Hours for PostgreSQL

postgresql get seconds difference between timestamps

SELECT (
    (extract (epoch from (
        '2012-01-01 18:25:00'::timestamp - '2012-01-01 18:25:02'::timestamp
                         )
             )
    )
)::integer

which prints:

-2

Because the timestamps are two seconds apart. Take the number and divide by 60 to get minutes, divide by 60 again to get hours.

What's better at freeing memory with PHP: unset() or $var = null

unset is not actually a function, but a language construct. It is no more a function call than a return or an include.

Aside from performance issues, using unset makes your code's intent much clearer.

Provide schema while reading csv file as a dataframe

In pyspark 2.4 onwards, you can simply use header parameter to set the correct header:

data = spark.read.csv('data.csv', header=True)

Similarly, if using scala you can use header parameter as well.

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Hardware

If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).

Software

threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).

Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).

Now a simple case: processing a 512x512 image

Suppose we want one thread to process one pixel (i,j).

We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)

It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.

dim3 threadsPerBlock(8, 8);  // 64 threads

and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.

dim3 numBlocks(imageWidth/threadsPerBlock.x,  /* for instance 512/8 = 64*/
              imageHeight/threadsPerBlock.y); 

The kernel is launched like this:

myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );       

Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.

In the kernel the pixel (i,j) to be processed by a thread is calculated this way:

uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;

Difference between id and name attributes in HTML

Based on personal experiences and according to the W3 Schools description for attributes:

ID is a Global Attribute and applies to virtually all elements in HTML. It is used to uniquely identify elements on the Web page, and its value is mostly accessed from the frontend (typically through JavaScript or jQuery).

name is an attribute that is useful to specific elements (such as form elements, etc) in HTML. Its value is mostly sent to the backend for processing.

https://www.w3schools.com/tags/ref_attributes.asp

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

How to export collection to CSV in MongoDB?

works for me remoting to a docker container with mongo:4.2.6

mongoexport -h mongodb:27017 --authenticationDatabase=admin -u username -p password -d database -c collection -q {"created_date": { "$gte": { "$date": "2020-08-03T00:00:00.000Z" }, "$lt": { "$date": "2020-08-09T23:59:59.999Z" } } } --fields=somefield1,somefield2 --type=csv --out=/archive.csv

remove empty lines from text file with PowerShell

You can't do replacing, you have to replace SOMETHING with SOMETHING, and you neither have both.

Bootstrap Carousel Full Screen

You can do it without forcing html and body to me 100% height. Use view port height instead. And with mouse wheel control too.

_x000D_
_x000D_
function debounce(func, wait, immediate) {_x000D_
  var timeout;_x000D_
  return function() {_x000D_
    var context = this,_x000D_
      args = arguments;_x000D_
    var later = function() {_x000D_
      timeout = null;_x000D_
      if (!immediate) func.apply(context, args);_x000D_
    };_x000D_
    var callNow = immediate && !timeout;_x000D_
    clearTimeout(timeout);_x000D_
    timeout = setTimeout(later, wait);_x000D_
    if (callNow) func.apply(context, args);_x000D_
  };_x000D_
}_x000D_
_x000D_
var slider = document.getElementById("demo");_x000D_
var onScroll = debounce(function(direction) {_x000D_
  //console.log(direction);_x000D_
  if (direction == false) {_x000D_
   $('.carousel-control-next').click();_x000D_
  } else {_x000D_
   $('.carousel-control-prev').click();_x000D_
  }_x000D_
}, 100, true);_x000D_
_x000D_
slider.addEventListener("wheel", function(e) {_x000D_
  e.preventDefault();_x000D_
  var delta;_x000D_
  if (event.wheelDelta) {_x000D_
    delta = event.wheelDelta;_x000D_
  } else {_x000D_
    delta = -1 * event.deltaY;_x000D_
  }_x000D_
_x000D_
  onScroll(delta >= 0);_x000D_
});
_x000D_
.carousel-item {_x000D_
  height: 100vh;_x000D_
  background: #212121;_x000D_
}_x000D_
_x000D_
.carousel-control-next,_x000D_
.carousel-control-prev {_x000D_
  width: 8% !important;_x000D_
}_x000D_
_x000D_
.carousel-item.active,_x000D_
.carousel-item-left,_x000D_
.carousel-item-right {_x000D_
  display: flex !important;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.carousel-item h1 {_x000D_
    color: #fff;_x000D_
    font-size: 72px;_x000D_
    padding: 0 10%;_x000D_
 }
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div id="demo" class="carousel slide" data-ride="carousel" data-interval="false">_x000D_
_x000D_
  <!-- The slideshow -->_x000D_
  <div class="carousel-inner">_x000D_
    <div class="carousel-item active">_x000D_
      <h1 class="display-1 text-center">Lorem ipsum dolor sit amet adipisicing</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
      <h1 class="display-1 text-center">Inventore omnis odio, dolore culpa atque?</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
     <h1 class="display-1 text-center">Lorem ipsum dolor sit</h1>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <!-- Left and right controls -->_x000D_
  <a class="carousel-control-prev" href="#demo" data-slide="prev">_x000D_
    <span class="carousel-control-prev-icon"></span>_x000D_
  </a>_x000D_
  <a class="carousel-control-next" href="#demo" data-slide="next">_x000D_
    <span class="carousel-control-next-icon"></span>_x000D_
  </a>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Recursive directory listing in DOS

You can use various options with FINDSTR to remove the lines do not want, like so:

DIR /S | FINDSTR "\-" | FINDSTR /VI DIR

Normal output contains entries like these:

28-Aug-14  05:14 PM    <DIR>          .
28-Aug-14  05:14 PM    <DIR>          ..

You could remove these using the various filtering options offered by FINDSTR. You can also use the excellent unxutils, but it converts the output to UNIX by default, so you no longer get CR+LF; FINDSTR offers the best Windows option.

Postgres manually alter sequence

this worked for me:

SELECT pg_catalog.setval('public.hibernate_sequence', 3, true);

Testing Spring's @RequestBody using Spring MockMVC

the following works for me,

  mockMvc.perform(
            MockMvcRequestBuilders.post("/api/test/url")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(asJsonString(createItemForm)))
            .andExpect(status().isCreated());

  public static String asJsonString(final Object obj) {
    try {
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

How to open a WPF Popup when another control is clicked, using XAML markup only?

The following approach is the same as Helge Klein's, except that the popup closes automatically when you click anywhere outside the Popup (including the ToggleButton itself):

<ToggleButton x:Name="Btn" IsHitTestVisible="{Binding ElementName=Popup, Path=IsOpen, Mode=OneWay, Converter={local:BoolInverter}}">
    <TextBlock Text="Click here for popup!"/>
</ToggleButton>

<Popup IsOpen="{Binding IsChecked, ElementName=Btn}" x:Name="Popup" StaysOpen="False">
    <Border BorderBrush="Black" BorderThickness="1" Background="LightYellow">
        <CheckBox Content="This is a popup"/>
    </Border>
</Popup>

"BoolInverter" is used in the IsHitTestVisible binding so that when you click the ToggleButton again, the popup closes:

public class BoolInverter : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool)
            return !(bool)value;
        return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Convert(value, targetType, parameter, culture);
    }
}

...which shows the handy technique of combining IValueConverter and MarkupExtension in one.

I did discover one problem with this technique: WPF is buggy when two popups are on the screen at the same time. Specifically, if your toggle button is on the "overflow popup" in a toolbar, then there will be two popups open after you click it. You may then find that the second popup (your popup) will stay open when you click anywhere else on your window. At that point, closing the popup is difficult. The user cannot click the ToggleButton again to close the popup because IsHitTestVisible is false because the popup is open! In my app I had to use a few hacks to mitigate this problem, such as the following test on the main window, which says (in the voice of Louis Black) "if the popup is open and the user clicks somewhere outside the popup, close the friggin' popup.":

PreviewMouseDown += (s, e) =>
{
    if (Popup.IsOpen)
    {
        Point p = e.GetPosition(Popup.Child);
        if (!IsInRange(p.X, 0, ((FrameworkElement)Popup.Child).ActualWidth) ||
            !IsInRange(p.Y, 0, ((FrameworkElement)Popup.Child).ActualHeight))
            Popup.IsOpen = false;
    }
};
// Elsewhere...
public static bool IsInRange(int num, int lo, int hi) => 
    num >= lo && num <= hi;

How to get the public IP address of a user in C#

On MVC 5 you can use this:

string cIpAddress = Request.UserHostAddress; //Gets the client ip address

or

string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address

What are the pros and cons of parquet format compared to other formats?

Tom's answer is quite detailed and exhaustive but you may also be interested in this simple study about Parquet vs Avro done at Allstate Insurance, summarized here:

"Overall, Parquet showed either similar or better results on every test [than Avro]. The query-performance differences on the larger datasets in Parquet’s favor are partly due to the compression results; when querying the wide dataset, Spark had to read 3.5x less data for Parquet than Avro. Avro did not perform well when processing the entire dataset, as suspected."

How to compare values which may both be null in T-SQL

Along the same lines as @Eric's answer, but without using a 'NULL' symbol.

(Field1 = Field2) OR (ISNULL(Field1, Field2) IS NULL)

This will be true only if both values are non-NULL, and equal each other, or both values are NULL

Passing data between different controller action methods

I prefer to use this instead of TempData

public class Home1Controller : Controller 
{
    [HttpPost]
    public ActionResult CheckBox(string date)
    {
        return RedirectToAction("ActionName", "Home2", new { Date =date });
    }
}

and another controller Action is

public class Home2Controller : Controller 
{
    [HttpPost]
    Public ActionResult ActionName(string Date)
    {
       // do whatever with Date
       return View();
    }
}

it is too late but i hope to be helpful for any one in the future

MySQL: Fastest way to count number of rows

EXPLAIN SELECT id FROM .... did the trick for me. and I could see the number of rows under rows column of the result.

Calling Non-Static Method In Static Method In Java

Constructor is a special method which in theory is the "only" non-static method called by any static method. else its not allowed.

Failed to build gem native extension — Rails install

The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.

sudo apt-get install ruby-all-dev

worked for me.

How to dump raw RTSP stream to file?

With this command I had poor image quality

ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -vcodec copy -acodec copy -f mp4 -y MyVideoFFmpeg.mp4

With this, almost without delay, I got good image quality.

ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -b 900k -vcodec copy -r 60 -y MyVdeoFFmpeg.avi

Image convert to Base64

<input type="file" onchange="getBaseUrl()">
function getBaseUrl ()  {
    var file = document.querySelector('input[type=file]')['files'][0];
    var reader = new FileReader();
    var baseString;
    reader.onloadend = function () {
        baseString = reader.result;
        console.log(baseString); 
    };
    reader.readAsDataURL(file);
}

Applying a single font to an entire website with CSS

The universal selector * refers to all elements, this css will do it for you:

*{
  font-family:Algerian;
}

But unfortunately if you are using FontAwesome icons, or any Icons that require their own font family, this will simply destroy the icons and they will not show the required view.

To avoid this you can use the :not selector, a sample of fontawesome icon is <i class="fa fa-bluetooth"></i>, so simply you can use:

*:not(i){
  font-family:Algerian;
}

this will apply this family to all elements in the document except the elements with the tag name <i>, you can also do it for classes:

*:not(.fa){
  font-family:Algerian;
}

this will apply this family to all elements in the document except the elements with the class "fa" which refers to fontawesome default class, you can also target more than one class like this:

*:not(i):not(.fa):not(.YourClassName){
  font-family:Algerian;
}

In javascript, how do you search an array for a substring match

For a fascinating examination of some of the alternatives and their efficiency, see John Resig's recent posts:

(The problem discussed there is slightly different, with the haystack elements being prefixes of the needle and not the other way around, but most solutions are easy to adapt.)

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You need to encode your parameter's values before concatenating them to URL.
Backslash \ is special character which have to be escaped as %5C

Escaping example:

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);

The result is http://host.com?param=param%5Cwith%5Cbackslash which is properly formatted url string.

Fatal error: Call to undefined function imap_open() in PHP

if you are on linux, edit the /etc/php/php.ini (or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment

;extension=imap.so

so that it becomes like this:

extension=imap.so

Then, restart the apache by

# /etc/rc.d/httpd restart

Preferred method to store PHP arrays (json_encode vs serialize)

If you are caching information that you will ultimately want to "include" at a later point in time, you may want to try using var_export. That way you only take the hit in the "serialize" and not in the "unserialize".

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

System images are pre-installed Android operating systems, and are only used by emulators. If you use your real Android device for debugging, you no longer need them, so you can remove them all.

The cleanest way to remove them is using SDK Manager. Open up SDK Manager and uncheck those system images and then apply.

Also feel free to remove other components (e.g. old SDK levels) that are of no use.

generate model using user:references vs user_id:integer

how does rails know that user_id is a foreign key referencing user?

Rails itself does not know that user_id is a foreign key referencing user. In the first command rails generate model Micropost user_id:integer it only adds a column user_id however rails does not know the use of the col. You need to manually put the line in the Micropost model

class Micropost < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :microposts
end

the keywords belongs_to and has_many determine the relationship between these models and declare user_id as a foreign key to User model.

The later command rails generate model Micropost user:references adds the line belongs_to :user in the Micropost model and hereby declares as a foreign key.

FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models/tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using software like MySql Workbench you find that there is no relationship threads drawn between the models. Like in the following pic enter image description here

However, if you use the later method you find that you migration file looks like:

def change
    create_table :microposts do |t|
      t.references :user, index: true

      t.timestamps null: false
    end
    add_foreign_key :microposts, :users

Now the foreign key is set at the database level. and you can generate proper EER diagrams. enter image description here

How to check if any flags of a flag combination are set?

I created a simple extension method that does not need a check on Enum types:

public static bool HasAnyFlag(this Enum value, Enum flags)
{
    return
        value != null && ((Convert.ToInt32(value) & Convert.ToInt32(flags)) != 0);
}

It also works on nullable enums. The standard HasFlag method does not, so I created an extension to cover that too.

public static bool HasFlag(this Enum value, Enum flags)
{
    int f = Convert.ToInt32(flags);

    return
        value != null && ((Convert.ToInt32(value) & f) == f);
}

A simple test:

[Flags]
enum Option
{
    None = 0x00,
    One = 0x01,
    Two = 0x02,
    Three = One | Two,
    Four = 0x04
}

[TestMethod]
public void HasAnyFlag()
{
    Option o1 = Option.One;
    Assert.AreEqual(true, o1.HasAnyFlag(Option.Three));
    Assert.AreEqual(false, o1.HasFlag(Option.Three));

    o1 |= Option.Two;
    Assert.AreEqual(true, o1.HasAnyFlag(Option.Three));
    Assert.AreEqual(true, o1.HasFlag(Option.Three));
}

[TestMethod]
public void HasAnyFlag_NullableEnum()
{
    Option? o1 = Option.One;
    Assert.AreEqual(true, o1.HasAnyFlag(Option.Three));
    Assert.AreEqual(false, o1.HasFlag(Option.Three));

    o1 |= Option.Two;
    Assert.AreEqual(true, o1.HasAnyFlag(Option.Three));
    Assert.AreEqual(true, o1.HasFlag(Option.Three));
}

Enjoy!

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

New functionality in the framework and support libs allow exactly this. There are three 'pieces of the puzzle':

  1. Using Toolbar so that you can embed your action bar into your view hierarchy.
  2. Making DrawerLayout fitsSystemWindows so that it is layed out behind the system bars.
  3. Disabling Theme.Material's normal status bar coloring so that DrawerLayout can draw there instead.

I'll assume that you will use the new appcompat.

First, your layout should look like this:

<!-- The important thing to note here is the added fitSystemWindows -->
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!-- Your normal content view -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- We use a Toolbar so that our drawer can be displayed
             in front of the action bar -->
        <android.support.v7.widget.Toolbar  
            android:id="@+id/my_awesome_toolbar"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:minHeight="?attr/actionBarSize"
            android:background="?attr/colorPrimary" />

        <!-- The rest of your content view -->

    </LinearLayout>

    <!-- Your drawer view. This can be any view, LinearLayout
         is just an example. As we have set fitSystemWindows=true
         this will be displayed under the status bar. -->
    <LinearLayout
        android:layout_width="304dp"
        android:layout_height="match_parent"
        android:layout_gravity="left|start"
        android:fitsSystemWindows="true">

        <!-- Your drawer content -->

    </LinearLayout>

</android.support.v4.widget.DrawerLayout>

Then in your Activity/Fragment:

public void onCreate(Bundled savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Your normal setup. Blah blah ...

    // As we're using a Toolbar, we should retrieve it and set it
    // to be our ActionBar
    Toolbar toolbar = (...) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);

    // Now retrieve the DrawerLayout so that we can set the status bar color.
    // This only takes effect on Lollipop, or when using translucentStatusBar
    // on KitKat.
    DrawerLayout drawerLayout = (...) findViewById(R.id.my_drawer_layout);
    drawerLayout.setStatusBarBackgroundColor(yourChosenColor);
}

Then you need to make sure that the DrawerLayout is visible behind the status bar. You do that by changing your values-v21 theme:

values-v21/themes.xml

<style name="Theme.MyApp" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:windowTranslucentStatus">true</item>
</style>

Note: If a <fragment android:name="fragments.NavigationDrawerFragment"> is used instead of

<LinearLayout
    android:layout_width="304dp"
    android:layout_height="match_parent"
    android:layout_gravity="left|start"
    android:fitsSystemWindows="true">

    <!-- Your drawer content -->

</LinearLayout>

the actual layout, the desired effect will be achieved if you call fitsSystemWindows(boolean) on a view that you return from onCreateView method.

@Override
public View onCreateView(LayoutInflater inflater, 
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View mDrawerListView = inflater.inflate(
        R.layout.fragment_navigation_drawer, container, false);
    mDrawerListView.setFitsSystemWindows(true);
    return mDrawerListView;
}

Sum values in a column based on date

Use a column to let each date be shown as month number; another column for day number:

      A      B       C         D
   -----  ----- ----------- --------
1     8      6    8/6/2010   12.70
2     8      7    8/7/2010   10.50
3     8      7    8/7/2010    7.10
4     8      9    8/9/2010   10.50
5     8     10   8/10/2010   15.00

The formula for A1 is =Month(C1)

The formula for B1 is =Day(C1)

For Month sums, put the month number next to each month:

      E      F         G     
   -----  ----- -------------  
1     7    July   $1,000,010 
2     8     Aug   $1,200,300 

The formula for G1 is =SumIf($A$1:$A$100, E1, $D$1:$D$100). This is a portable formula; just copy it down.

Total for the day will be be a bit more complicated, but you can probably see how to do it.

How to access html form input from asp.net code behind

Edit: thought of something else.

You say you're creating a form dynamically - do you really mean a <form> and its contents 'cause asp.net takes issue with multiple forms on a page and it's already creating one uberform for you.

How do you convert WSDLs to Java classes using Eclipse?

Options are:

Read through the above links before taking a call

What is the "-->" operator in C/C++?

Utterly geek, but I will be using this:

#define as ;while

int main(int argc, char* argv[])
{
    int n = atoi(argv[1]);
    do printf("n is %d\n", n) as ( n --> 0);
    return 0;
}

How do I save a String to a text file using Java?

Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:

static void writeStringToFile(File file, String data) 

which allows you to write text to a file in one method call:

FileUtils.writeStringToFile(new File("test.txt"), "Hello File");

You might also want to consider specifying the encoding for the file as well.

Converting a date in MySQL from string field

SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...

How can I do SELECT UNIQUE with LINQ?

var uniqueColors = (from dbo in database.MainTable 
                    where dbo.Property == true
                    select dbo.Color.Name).Distinct();

How to programmatically determine the current checked out Git branch

I'm trying for the simplest and most self-explanatory method here:

git status | grep "On branch" | cut -c 11-

How to remove multiple deleted files in Git repository

git add -u 

updates all your changes

How to use the CSV MIME-type?

You are not specifying a language or framework, but the following header is used for file downloads:

"Content-Disposition: attachment; filename=abc.csv"

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

A simple inline JavaScript confirm would suffice:

<form onsubmit="return confirm('Do you really want to submit the form?');">

No need for an external function unless you are doing validation, which you can do something like this:

<script>
function validate(form) {

    // validation code here ...


    if(!valid) {
        alert('Please correct the errors in the form!');
        return false;
    }
    else {
        return confirm('Do you really want to submit the form?');
    }
}
</script>
<form onsubmit="return validate(this);">

How do I view / replay a chrome network debugger har file saved with content?

There is an HAR Viewer developed by Jan Odvarko that you can use. You either use the online version at

Or download the source-code at https://github.com/janodvarko/harviewer.

EDIT: Chrome 62 DevTools include HAR import functionality. https://developers.google.com/web/updates/2017/08/devtools-release-notes#har-imports

Why is Event.target not Element in Typescript?

Typescript 3.2.4

For retrieving property you must cast target to appropriate data type:

e => console.log((e.target as Element).id)

How to access site running apache server over lan without internet connection

Open httpd.conf of Apache server (backup first) Look for the the following : Listen

Change the line to

Listen *:80

Still in httpd.conf, look for the following (or similar):

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
    Deny from all
</Directory>

Change this block to :

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
    #Deny from all
</Directory>

Save httpd.conf and restart apache

Open port 80 of the server such that everyone can access your server.

Open Control Panel >> System and Security >> Windows Firewall then click on “Advance Setting” and then select “Inbound Rules” from the left panel and then click on “Add Rule…”. Select “PORT” as an option from the list and then in the next screen select “TCP” protocol and enter port number “80” under “Specific local port” then click on the ”Next” button and select “Allow the Connection” and then give the general name and description to this port and click Done.

Restart WAMP and access your machine in LAN or WAN.

How to remove elements/nodes from angular.js array

For anyone returning to this question. The correct "Angular Way" to remove items from an array is with $filter. Just inject $filter into your controller and do the following:

$scope.items = $filter('filter')($scope.items, {name: '!ted'})

You don't need to load any additional libraries or resort to Javascript primitives.

clearing a char array c

You should use memset. Setting just the first element won't work, you need to set all elements - if not, how could you set only the first element to 0?

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

Find duplicate values in R

You could use table, i.e.

n_occur <- data.frame(table(vocabulary$id))

gives you a data frame with a list of ids and the number of times they occurred.

n_occur[n_occur$Freq > 1,]

tells you which ids occurred more than once.

vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]

returns the records with more than one occurrence.

How to update the value stored in Dictionary in C#?

This may work for you:

Scenario 1: primitive types

string keyToMatchInDict = "x";
int newValToAdd = 1;
Dictionary<string,int> dictToUpdate = new Dictionary<string,int>{"x",1};

if(!dictToUpdate.ContainsKey(keyToMatchInDict))
   dictToUpdate.Add(keyToMatchInDict ,newValToAdd );
else
   dictToUpdate[keyToMatchInDict] = newValToAdd; //or you can do operations such as ...dictToUpdate[keyToMatchInDict] += newValToAdd;

Scenario 2: The approach I used for a List as Value

int keyToMatch = 1;
AnyObject objInValueListToAdd = new AnyObject("something for the Ctor")
Dictionary<int,List<AnyObject> dictToUpdate = new Dictionary<int,List<AnyObject>(); //imagine this dict got initialized before with valid Keys and Values...

if(!dictToUpdate.ContainsKey(keyToMatch))
   dictToUpdate.Add(keyToMatch,new List<AnyObject>{objInValueListToAdd});
else
   dictToUpdate[keyToMatch] = objInValueListToAdd;

Hope it's useful for someone in need of help.

Is Safari on iOS 6 caching $.ajax results?

I found one workaround that makes me curious as to why it works. Before reading Tadej's answer concerning ASP.NET web service, I was trying to come up with something that would work.

And I'm not saying that it's a good solution, but I just wanted to document it here.

main page: includes a JavaScript function, checkStatus(). The method calls another method which uses a jQuery AJAX call to update the html content. I used setInterval to call checkStatus(). Of course, I ran into the caching problem.

Solution: use another page to call the update.

On the main page, I set a boolean variable, runUpdate, and added the following to the body tag:

<iframe src="helper.html" style="display: none; visibility: hidden;"></iframe>

In the of helper.html:

<meta http-equiv="refresh" content="5">
<script type="text/javascript">
    if (parent.runUpdate) { parent.checkStatus(); }
</script>

So, if checkStatus() is called from the main page, I get the cached content. If I call checkStatus from the child page, I get updated content.

How can I change Eclipse theme?

Update December 2012 (19 months later):

The blog post "Jin Mingjian: Eclipse Darker Theme" mentions this GitHub repo "eclipse themes - darker":

enter image description here

The big fun is that, the codes are minimized by using Eclipse4 platform technologies like dependency injection.
It proves that again, the concise codes and advanced features could be achieved by contributing or extending with the external form (like library, framework).
New language is not necessary just for this kind of purpose.


Update July 2012 (14 months later):

With the latest Eclipse4.2 (June 2012, "Juno") release, you can implement what I originally described below: a CSS-based fully dark theme for Eclipse.
See the article by Lars Vogel in "Eclipse 4 is beautiful – Create your own Eclipse 4 theme":

Eclipse fully dark theme

If you want to play with it, you only need to write a plug-in, create a CSS file and use the org.eclipse.e4.ui.css.swt.theme extension point to point to your file.
If you export your plug-in, place it in the “dropins” folder of your Eclipse installation and your styling is available.


Original answer: August 2011

With Eclipse 3.x, theme is only for the editors, as you can see in the site "Eclipse Color Themes".
Anything around that is managed by windows system colors.
That is what you need to change to have any influence on Eclipse global colors around editors.

Eclipse 4 will provide much advance theme options: See "Eclipse 4.0 – So you can theme me Part 1" and "Eclipse 4.0 RCP: Dynamic CSS Theme Switching".

dark theme

How to convert C++ Code to C

While you can do OO in C (e.g. by adding a theType *this first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).

I would suggest at least looking at a re-design to compare how this would work out.

Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?

How to call a method after bean initialization is complete?

You can use something like:

<beans>
    <bean id="myBean" class="..." init-method="init"/>
</beans>

This will call the "init" method when the bean is instantiated.

scikit-learn random state in splitting dataset

If you don't specify the random_state in your code, then every time you run(execute) your code a new random value is generated and the train and test datasets would have different values each time.

However, if a fixed value is assigned like random_state = 0 or 1 or 42 then no matter how many times you execute your code the result would be the same .i.e, same values in train and test datasets.

Is it possible to move/rename files in Git and maintain their history?

I followed this multi-step process to move code to the parent directory and retained history.

Step 0: Created a branch 'history' from 'master' for safekeeping

Step 1: Used git-filter-repo tool to rewrite history. This command below moved folder 'FolderwithContentOfInterest' to one level up and modified the relevant commit history

git filter-repo --path-rename ParentFolder/FolderwithContentOfInterest/:FolderwithContentOfInterest/ --force

Step 2: By this time the GitHub repository lost its remote repository path. Added remote reference

git remote add origin [email protected]:MyCompany/MyRepo.git

Step 3: Pull information on repository

git pull

Step 4: Connect the local lost branch with the origin branch

git branch --set-upstream-to=origin/history history

Step 5: Address merge conflict for the folder structure if prompted

Step 6: Push!!

git push

Note: The modified history and moved folder appear to already be committed. enter code here

Done. Code moves to the parent / desired directory keeping history intact!

Lombok is not generating getter and setter

In mac os lombok will not be able to find eclipse location. please click on specify location and go to the eclipse installed folder you can find the eclipse.ini file select that

enter image description here

Kubernetes pod gets recreated when deleted

Instead of trying to figure out whether it is a deployment, deamonset, statefulset... or what (in my case it was a replication controller that kept spanning new pods :) In order to determine what it was that kept spanning up the image I got all the resources with this command:

kubectl get all

Of course you could also get all resources from all namespaces:

kubectl get all --all-namespaces

or define the namespace you would like to inspect:

kubectl get all -n NAMESPACE_NAME

Once I saw that the replication controller was responsible for my trouble I deleted it:

kubectl delete replicationcontroller/CONTROLLER_NAME

Solve Cross Origin Resource Sharing with Flask

I might be a late on this question but below steps fixed the issue

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

How can I enable CORS on Django REST Framework

In case anyone is getting back to this question and deciding to write their own middleware, this is a code sample for Django's new style middleware -

class CORSMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response["Access-Control-Allow-Origin"] = "*"

        return response

PHP AES encrypt / decrypt

Please use an existing secure PHP encryption library

It's generally a bad idea to write your own cryptography unless you have experience breaking other peoples' cryptography implementations.

None of the examples here authenticate the ciphertext, which leaves them vulnerable to bit-rewriting attacks.

If you can install PECL extensions, libsodium is even better

<?php
// PECL libsodium 0.2.1 and newer

/**
 * Encrypt a message
 * 
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 */
function safeEncrypt($message, $key)
{
    $nonce = \Sodium\randombytes_buf(
        \Sodium\CRYPTO_SECRETBOX_NONCEBYTES
    );

    return base64_encode(
        $nonce.
        \Sodium\crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
}

/**
 * Decrypt a message
 * 
 * @param string $encrypted - message encrypted with safeEncrypt()
 * @param string $key - encryption key
 * @return string
 */
function safeDecrypt($encrypted, $key)
{   
    $decoded = base64_decode($encrypted);
    $nonce = mb_substr($decoded, 0, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    return \Sodium\crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
}    

Then to test it out:

<?php
// This refers to the previous code block.
require "safeCrypto.php"; 

// Do this once then store it somehow:
$key = \Sodium\randombytes_buf(\Sodium\CRYPTO_SECRETBOX_KEYBYTES);
$message = 'We are all living in a yellow submarine';

$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

This can be used in any situation where you are passing data to the client (e.g. encrypted cookies for sessions without server-side storage, encrypted URL parameters, etc.) with a reasonably high degree of certainty that the end user cannot decipher or reliably tamper with it.

Since libsodium is cross-platform, this also makes it easier to communicate with PHP from, e.g. Java applets or native mobile apps.


Note: If you specifically need to add encrypted cookies powered by libsodium to your app, my employer Paragon Initiative Enterprises is developing a library called Halite that does all of this for you.

Javascript date.getYear() returns 111 in 2011?

From what I've read on Mozilla's JS pages, getYear is deprecated. As pointed out many times, getFullYear() is the way to go. If you're really wanting to use getYear() add 1900 to it.

var now = new Date(),
    year = now.getYear() + 1900;

What is the difference between an abstract function and a virtual function?

From a C++ background, C# virtual corresponds to C++ virtual, while C# abstract methods corresponds to C++ pure virtual function

How can I make a CSS table fit the screen width?

table { width: 100%; }

Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.

$("#tableid").width($(window).width());

If not, use this snippet

<style>
    body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
    <tr>
        <td>Just a Test
        </td>
    </tr>
</table>

You will notice that the width is perfectly covering the page.

The main thing is too nullify the margin and padding as I have shown at the body, then you are set.

Animate the transition between fragments

You need to use the new android.animation framework (object animators) with FragmentTransaction.setCustomAnimations as well as FragmentTransaction.setTransition.

Here's an example on using setCustomAnimations from ApiDemos' FragmentHideShow.java:

ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);

and here's the relevant animator XML from res/animator/fade_in.xml:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:interpolator/accelerate_quad"
    android:valueFrom="0"
    android:valueTo="1"
    android:propertyName="alpha"
    android:duration="@android:integer/config_mediumAnimTime" />

Note that you can combine multiple animators using <set>, just as you could with the older animation framework.


EDIT: Since folks are asking about slide-in/slide-out, I'll comment on that here.

Slide-in and slide-out

You can of course animate the translationX, translationY, x, and y properties, but generally slides involve animating content to and from off-screen. As far as I know there aren't any transition properties that use relative values. However, this doesn't prevent you from writing them yourself. Remember that property animations simply require getter and setter methods on the objects you're animating (in this case views), so you can just create your own getXFraction and setXFraction methods on your view subclass, like this:

public class MyFrameLayout extends FrameLayout {
    ...
    public float getXFraction() {
        return getX() / getWidth(); // TODO: guard divide-by-zero
    }

    public void setXFraction(float xFraction) {
        // TODO: cache width
        final int width = getWidth();
        setX((width > 0) ? (xFraction * width) : -9999);
    }
    ...
}

Now you can animate the 'xFraction' property, like this:

res/animator/slide_in.xml:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:valueFrom="-1.0"
    android:valueTo="0"
    android:propertyName="xFraction"
    android:duration="@android:integer/config_mediumAnimTime" />

Note that if the object you're animating in isn't the same width as its parent, things won't look quite right, so you may need to tweak your property implementation to suit your use case.