Programs & Examples On #Filechannel

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

If all above solutions is not working and In case of your project was working fine and now getting this issue, then try this,

  • go to android studio setting.
  • select gradle under build,execution.
  • then again just set path of gradle user home (C:/Users/%user_name%/.gradle/wrapper/dists/gradle-6.5-bin)
  • just rebuild again, this helps me.

Java NIO FileChannel versus FileOutputstream performance / usefulness

I tested the performance of FileInputStream vs. FileChannel for decoding base64 encoded files. In my experients I tested rather large file and traditional io was alway a bit faster than nio.

FileChannel might have had an advantage in prior versions of the jvm because of synchonization overhead in several io related classes, but modern jvm are pretty good at removing unneeded locks.

java get file size efficiently

The benchmark given by GHad measures lots of other stuff (such as reflection, instantiating objects, etc.) besides getting the length. If we try to get rid of these things then for one call I get the following times in microseconds:

   file sum___19.0, per Iteration___19.0
    raf sum___16.0, per Iteration___16.0
channel sum__273.0, per Iteration__273.0

For 100 runs and 10000 iterations I get:

   file sum__1767629.0, per Iteration__1.7676290000000001
    raf sum___881284.0, per Iteration__0.8812840000000001
channel sum___414286.0, per Iteration__0.414286

I did run the following modified code giving as an argument the name of a 100MB file.

import java.io.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;

public class FileSizeBench {

  private static File file;
  private static FileChannel channel;
  private static RandomAccessFile raf;

  public static void main(String[] args) throws Exception {
    int runs = 1;
    int iterations = 1;

    file = new File(args[0]);
    channel = new FileInputStream(args[0]).getChannel();
    raf = new RandomAccessFile(args[0], "r");

    HashMap<String, Double> times = new HashMap<String, Double>();
    times.put("file", 0.0);
    times.put("channel", 0.0);
    times.put("raf", 0.0);

    long start;
    for (int i = 0; i < runs; ++i) {
      long l = file.length();

      start = System.nanoTime();
      for (int j = 0; j < iterations; ++j)
        if (l != file.length()) throw new Exception();
      times.put("file", times.get("file") + System.nanoTime() - start);

      start = System.nanoTime();
      for (int j = 0; j < iterations; ++j)
        if (l != channel.size()) throw new Exception();
      times.put("channel", times.get("channel") + System.nanoTime() - start);

      start = System.nanoTime();
      for (int j = 0; j < iterations; ++j)
        if (l != raf.length()) throw new Exception();
      times.put("raf", times.get("raf") + System.nanoTime() - start);
    }
    for (Map.Entry<String, Double> entry : times.entrySet()) {
        System.out.println(
            entry.getKey() + " sum: " + 1e-3 * entry.getValue() +
            ", per Iteration: " + (1e-3 * entry.getValue() / runs / iterations));
    }
  }
}

How does the communication between a browser and a web server take place?

The links for specifications of each aspect of the question is as follows:

  • GET, POST verbs (among others) - The HTTP Specification exhaustively discusses all aspects of HTTP communication (the protocol for communication between the web server and the browser). It explains the Request message and Response message protocols.

  • Cookies - are set by attaching a Set-Cookie HTTP Header to the HTTP response.

  • QueryStrings - are the part of the URL in the HTTP request that follow the first occurrence of a "?" character. The linked specification is for section 3.4 of the URI specification.

  • Sessions - HTTP is a synchronous, stateless protocol. Sessions, or the illusion of state, can be created by (1) using cookies to store state data as plain text on the client's computer, (2) passing data-values in the URL and querystring of the request, (3) submitting POST requests with a collection of values that may indicate state and, (4) storing state information by a server-side persistence mechanism that is retrieved by a session-key (the session key is resolved from either the cookie, URL/Querystring or POST value collection.

An explanation of HTTP can go on for days, but I have attempted to provide a concise yet conceptually complete answer, and include the appropriate links for further reading of official specifications.

Travel/Hotel API's?

In my search for hotel APIs I have found only one API giving unrestricted open access to their hotel database and allowing you to book their hotels:

Expedia's EAN http://developer.ean.com/

You need to sign for their affiliate program, which is very easy. You get immediate access to their hotel databases plus you can make availability/booking requests with several response options, including JSON, which is more convenient and lightweight than the (unfortunately) more widespread XML.

As you immediately access their API, you can start developing and testing, but still need their approval to launch the site, basically to make sure it provides the needed quality and security, which is reasonable.

They also offer "deep linking", i.e. you may customize your requests by adding parameters. Then if it sufficient for your purpose (for mine it is not), you don't even need to store their content on your server.


I have also signed for HotelsCombined program: (link removed as this site doesn't seem to let me put more links)

However, they do not immediately allow you to use their API even for testing. From their answer:

"Apologies for the inconvenience caused, but it’s simply a business decision to limit access to our rich hotel content. Please kindly check back within the next 2-3 months, where we will be able to judge your traffic, and in turn judge your status on standard data feeds."


I have also signed for Booking.com affiliate program: (link removed as this site doesn't seem to let me put more links)

Unfortunately, again, they limit access, from their answer: "Please do note that, since there's a high amount of time and cost involved in the XML integration, we are only able to offer the XML integration to a small amount of partners with a high potential."


I did not explore Tripadvisor as they seem only to offer top 10 hotels and only as widgets, but most importantly for me, they wouldn't allow booking through them.

I've checked the hotelbase.org mentioned above, they have very extensive list but not as rich as by Expedia, also they don't seem to have images and don't allow booking either.

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

SQL INSERT INTO from multiple tables

Here is an example if multiple tables don't have common Id, you can create yourself, I use 1 as commonId to create common id so that I can inner join them:

Insert Into #TempResult
select CountA, CountB, CountC  from

(
select Count(A_Id) as CountA, 1 as commonId from tableA
  where ....
  and  ...
  and   ...
) as tempA

inner join
(
select Count(B_Id) as CountB, 1 as commonId from tableB
  where ...
  and ...
  and  ...
 ) as tempB

on tempA.commonId = tempB.commonId

inner join
(
select Count(C_ID) as CountC, 1 as commonId from tableC
where ...
and   ...
) as tempC

on tmepB.commonId = tempC.commonId

--view insert result
select * from #TempResult

Most efficient way to check for DBNull and then assign to a variable?

You should use the method:

Convert.IsDBNull()

Considering it's built-in to the Framework, I would expect this to be the most efficient.

I'd suggest something along the lines of:

int? myValue = (Convert.IsDBNull(row["column"]) ? null : (int?) Convert.ToInt32(row["column"]));

And yes, the compiler should cache it for you.

The value violated the integrity constraints for the column

You can replace the values "null" from the original file & field/column.

How do I mock a class without an interface?

If worse comes to worse, you can create an interface and adapter pair. You would change all uses of ConcreteClass to use the interface instead, and always pass the adapter instead of the concrete class in production code.

The adapter implements the interface, so the mock can also implement the interface.

It's more scaffolding than just making a method virtual or just adding an interface, but if you don't have access to the source for the concrete class it can get you out of a bind.

Design Android EditText to show error message as described by google

reVerse's answer is great but it didn't point out how to remove the floating error tooltip kind of thing

You'll need edittext.setError(null) to remove that.
Also, as someone pointed out, you don't need TextInputLayout.setErrorEnabled(true)

Layout

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter something" />
</android.support.design.widget.TextInputLayout>

Code

TextInputLayout til = (TextInputLayout) editText.getParent();
til.setError("Your input is not valid...");
editText.setError(null);

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

Just another possible source of the problem!

I found out that in my case it was the following resource block that caused it:

<project>
    <build>
        <resources>
            <resource>
                <directory>${basedir}/../some-folder</directory>
                <targetPath>outputFolder</targetPath>
            </resource>
        <resources>
    </build>
</project>

It included a folder from the project folder (the eclipse project is a subfolder of the versioned project folder).

In my case, I could remove the error by removing the block and replacing it with a call to the Build helper Maven plugin:

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>build-helper-maven-plugin</artifactId>
            <version>1.9.1</version>
            <executions>
                <execution>
                    <id>my-own-very-cool-id-for-this-step</id>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>add-resource</goal>
                    </goals>
                    <configuration>
                        <resources>
                            <resource>
                                <directory>${basedir}/../some-folder</directory>
                                <targetPath>outputFolder</targetPath>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

T-SQL: Export to new Excel file

This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

How to open an external file from HTML

Try formatting the link like this (looks hellish, but it works in Firefox 3 under Vista for me) :

<a href="file://///SERVER/directory/file.ext">file.ext</a>

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

They are the same thing. If you use the set transaction isolation level statement, it will apply to all the tables in the connection, so if you only want a nolock on one or two tables use that; otherwise use the other.

Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider snapshot or serializable hints instead.

How to determine if a number is positive or negative?

Integers are trivial; this you already know. The deep problem is how to deal with floating-point values. At that point, you've got to know a bit more about how floating point values actually work.

The key is Double.doubleToLongBits(), which lets you get at the IEEE representation of the number. (The method's really a direct cast under the hood, with a bit of magic for dealing with NaN values.) Once a double has been converted to a long, you can just use 0x8000000000000000L as a mask to select the sign bit; if zero, the value is positive, and if one, it's negative.

How to read multiple Integer values from a single line of input in Java?

Scanner has a method called hasNext():

    Scanner scanner = new Scanner(System.in);

    while(scanner.hasNext())
    {
        System.out.println(scanner.nextInt());
    }

Inline instantiation of a constant List

You are looking for a simple code, like this:

    List<string> tagList = new List<string>(new[]
    {
         "A"
        ,"B"
        ,"C"
        ,"D"
        ,"E"
    });

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

ORA-00979 not a group by expression

You must put all columns of the SELECT in the GROUP BY or use functions on them which compress the results to a single value (like MIN, MAX or SUM).

A simple example to understand why this happens: Imagine you have a database like this:

FOO BAR
0   A
0   B

and you run SELECT * FROM table GROUP BY foo. This means the database must return a single row as result with the first column 0 to fulfill the GROUP BY but there are now two values of bar to chose from. Which result would you expect - A or B? Or should the database return more than one row, violating the contract of GROUP BY?

How to read fetch(PDO::FETCH_ASSOC);

/* Design Pattern "table-data gateway" */

class Gateway
{
    protected $connection = null;

    public function __construct()
    {
        $this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
    }

    public function loadAll()
    {
        $sql = 'SELECT * FROM users';
        $rows = $this->connection->query($sql);

        return $rows;
    }

    public function loadById($id)
    {
        $sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
        $result = $this->connection->query($sql);

        return $result->fetch(PDO::FETCH_ASSOC);
        // http://php.net/manual/en/pdostatement.fetch.php //                   
    }
}

/* Print all row with column 'user_id' only */

$gateway  = new Gateway();
$users    = $gateway->loadAll();

$no = 1;
foreach ($users as $key => $value) {
    echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
    $no++;
}

/* Print user_id = 1 with all column */

$user = $gateway->loadById(1);

$no = 1;
foreach ($user as $key => $value) {
    echo $no . '. ' . $key . ' => ' . $value . '<br />';
    $no++;
}

/* Print user_id = 1 with column 'email and password' */

$user = $gateway->loadById(1);

echo $user['email'];
echo $user['password'];

Joining pairs of elements of a list

You can use slice notation with steps:

>>> x = "abcdefghijklm"
>>> x[0::2] #0. 2. 4...
'acegikm'
>>> x[1::2] #1. 3. 5 ..
'bdfhjl'
>>> [i+j for i,j in zip(x[::2], x[1::2])] # zip makes (0,1),(2,3) ...
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']

Same logic applies for lists too. String lenght doesn't matter, because you're simply adding two strings together.

Use multiple custom fonts using @font-face?

You simply add another @font-face rule:

@font-face {
    font-family: CustomFont;
    src: url('CustomFont.ttf');
}

@font-face {
    font-family: CustomFont2;
    src: url('CustomFont2.ttf');
}

If your second font still doesn't work, make sure you're spelling its typeface name and its file name correctly, your browser caches are behaving, your OS isn't messing around with a font of the same name, etc.

How do you use a variable in a regular expression?

This self calling function will iterate over replacerItems using an index, and change replacerItems[index] globally on the string with each pass.

  const replacerItems = ["a", "b", "c"];    

    function replacer(str, index){
          const item = replacerItems[index];
          const regex = new RegExp(`[${item}]`, "g");
          const newStr = str.replace(regex, "z");
          if (index < replacerItems.length - 1) {
            return replacer(newStr, index + 1);
          }
          return newStr;
    }

// console.log(replacer('abcdefg', 0)) will output 'zzzdefg'

How to sort a data frame by date

You can use order() to sort date data.

# Sort date ascending order
d[order(as.Date(d$V3, format = "%d/%m/%Y")),]

# Sort date descending order
d[rev(order(as.Date(d$V3, format = "%d/%m/%y"))),]

Hope this helps,

Link to my quora answer https://qr.ae/TWngCe

Thanks

Creating a BAT file for python script

Here's how you can put both batch code and the python one in single file:

0<0# : ^
''' 
@echo off
echo batch code
python "%~f0" %*
exit /b 0
'''

print("python code")

the ''' respectively starts and ends python multi line comments.

0<0# : ^ is more interesting - due to redirection priority in batch it will be interpreted like :0<0# ^ by the batch script which is a label which execution will be not displayed on the screen. The caret at the end will escape the new line and second line will be attached to the first line.For python it will be 0<0 statement and a start of inline comment.

The credit goes to siberia-man

How to determine the installed webpack version

Version Installed:

Using webpack CLI: (--version, -v Show version number [boolean])

webpack --version

or:

webpack -v

Using npm list command:

npm list webpack

Results in name@version-range:

<projectName>@<projectVersion> /path/to/project
+-- webpack@<version-range>

Using yarn list command:

yarn list webpack

How to do it programmatically?

Webpack 2 introduced Configuration Types.

Instead of exporting a configuration object, you may return a function which accepts an environment as argument. When running webpack, you may specify build environment keys via --env, such as --env.production or --env.platform=web.

We will use a build environment key called --env.version.

webpack --env.version $(webpack --version)

or:

webpack --env.version $(webpack -v)

For this to work we will need to do two things:

Change our webpack.config.js file and use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

-module.exports = {
+module.exports = function(env) {
+  return {
    plugins: [
      new webpack.DefinePlugin({
+        WEBPACK_VERSION: JSON.stringify(env.version) //<version-range>
      })
    ]
+  };
};

Now we can access the global constant like so:

console.log(WEBPACK_VERSION);

Latest version available:

Using npm view command will return the latest version available on the registry:

npm view [<@scope>/]<name>[@<version>] [<field>[.<subfield>]...]


For webpack use:

npm view webpack version

How to change values in a tuple?

EDIT: This doesn't work on tuples with duplicate entries yet!!

Based on Pooya's idea:

If you are planning on doing this often (which you shouldn't since tuples are inmutable for a reason) you should do something like this:

def modTupByIndex(tup, index, ins):
    return tuple(tup[0:index]) + (ins,) + tuple(tup[index+1:])

print modTupByIndex((1,2,3),2,"a")

Or based on Jon's idea:

def modTupByIndex(tup, index, ins):
    lst = list(tup)
    lst[index] = ins
    return tuple(lst)

print modTupByIndex((1,2,3),1,"a")

Where does Chrome store cookies?

For Google chrome Version 56.0.2924.87 (Latest Release) cookies are found inside profile1 folder.

If you browse that you can find variety of information.

There is a separate file called "Cookies". Also the Cache folder is inside this folder.

Path : C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Profile 1

Remember to replace user_name.

For Version 61.0.3163.100
Path : C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Default

Inside this folder there is Cookies file and Cache folder.

Webdriver findElements By xpath

Instead of

css=#container

use

css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)

Hex to ascii string conversion

you need to take 2 (hex) chars at the same time... then calculate the int value and after that make the char conversion like...

char d = (char)intValue;

do this for every 2chars in the hex string

this works if the string chars are only 0-9A-F:

#include <stdio.h>
#include <string.h>

int hex_to_int(char c){
        int first = c / 16 - 3;
        int second = c % 16;
        int result = first*10 + second;
        if(result > 9) result--;
        return result;
}

int hex_to_ascii(char c, char d){
        int high = hex_to_int(c) * 16;
        int low = hex_to_int(d);
        return high+low;
}

int main(){
        const char* st = "48656C6C6F3B";
        int length = strlen(st);
        int i;
        char buf = 0;
        for(i = 0; i < length; i++){
                if(i % 2 != 0){
                        printf("%c", hex_to_ascii(buf, st[i]));
                }else{
                        buf = st[i];
                }
        }
}

How to put a link on a button with bootstrap?

You can just simply add the following code;

<a class="btn btn-primary" href="http://localhost:8080/Home" role="button">Home Page</a>

iOS change navigation bar title font and color

Try this:

NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIColor whiteColor],NSForegroundColorAttributeName,
                                [UIColor whiteColor],NSBackgroundColorAttributeName,nil];
self.navigationController.navigationBar.titleTextAttributes = textAttributes;

How to track down a "double free or corruption" error

With modern C++ compilers you can use sanitizers to track.

Sample example :

My program:

$cat d_free.cxx 
#include<iostream>

using namespace std;

int main()

{
   int * i = new int();
   delete i;
   //i = NULL;
   delete i;
}

Compile with address sanitizers :

# g++-7.1 d_free.cxx -Wall -Werror -fsanitize=address -g

Execute :

# ./a.out 
=================================================================
==4836==ERROR: AddressSanitizer: attempting double-free on 0x602000000010 in thread T0:
    #0 0x7f35b2d7b3c8 in operator delete(void*, unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140
    #1 0x400b2c in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:11
    #2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
    #3 0x400a08  (/media/sf_shared/jkr/cpp/d_free/a.out+0x400a08)

0x602000000010 is located 0 bytes inside of 4-byte region [0x602000000010,0x602000000014)
freed by thread T0 here:
    #0 0x7f35b2d7b3c8 in operator delete(void*, unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140
    #1 0x400b1b in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:9
    #2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)

previously allocated by thread T0 here:
    #0 0x7f35b2d7a040 in operator new(unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:80
    #1 0x400ac9 in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:8
    #2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)

SUMMARY: AddressSanitizer: double-free /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140 in operator delete(void*, unsigned long)
==4836==ABORTING

To learn more about sanitizers you can check this or this or any modern c++ compilers (e.g. gcc, clang etc.) documentations.

Can someone explain Microsoft Unity?

MSDN has a Developer's Guide to Dependency Injection Using Unity that may be useful.

The Developer's Guide starts with the basics of what dependency injection is, and continues with examples of how to use Unity for dependency injection. As of the February 2014 the Developer's Guide covers Unity 3.0, which was released in April 2013.

Setting up Gradle for api 26 (Android)

you must add in your MODULE-LEVEL build.gradle file with:

//module-level build.gradle file
repositories {
    maven {
        url 'https://maven.google.com'

    }
}

see: Google's Maven repository

I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url 'https://maven.google.com'}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:

//project-level build.gradle file
allprojects {
 repositories {
    jcenter()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
  }
}

UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0

Using other keys for the waitKey() function of opencv

The answer that works on Ubuntu18, python3, opencv 3.2.0 is similar to the one above. But with the change in line cv2.waitKey(0). that means the program waits until a button is pressed.

With this code I found the key value for the arrow buttons: arrow up (82), down (84), arrow left(81) and Enter(10) and etc..

import cv2
img = cv2.imread('sof.jpg') # load a dummy image
while(1):
    cv2.imshow('img',img)
    k = cv2.waitKey(0)
    if k==27:    # Esc key to stop
        break
    elif k==-1:  # normally -1 returned,so don't print it
        continue
    else:
        print k # else print its value

Open Redis port for remote connections

For me, I needed to do the following:

1- Comment out bind 127.0.0.1

2- Change protected-mode to no

3- Protect my server with iptables (https://www.digitalocean.com/community/tutorials/how-to-implement-a-basic-firewall-template-with-iptables-on-ubuntu-14-04)

Run a JAR file from the command line and specify classpath

Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar

Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

Then execute it with

java -jar MyJar.jar

How to prevent ENTER keypress to submit a web form?

I've spent some time making this cross browser for IE8,9,10, Opera 9+, Firefox 23, Safari (PC) and Safari(MAC)

JSFiddle Example: http://jsfiddle.net/greatbigmassive/ZyeHe/

Base code - Call this function via "onkeypress" attached to your form and pass "window.event" into it.

function stopEnterSubmitting(e) {
    if (e.keyCode == 13) {
        var src = e.srcElement || e.target;
        if (src.tagName.toLowerCase() != "textarea") {
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }
        }
    }
}

Differences between hard real-time, soft real-time, and firm real-time?

Consider a task that inputs data from the serial port. When new data arrives the serial port triggers an event. When the software services that event, it reads and processes the new data. The serial port has a hardware to store incoming data (2 on the MSP432, 16 on the TM4C123) such that if the buffer is full and more data arrives, the new data is lost. Is this system hard, firm, or soft real time?

It is hard real time because if the response is late, data may be lost.


Consider a hearing aid that inputs sounds from a microphone, manipulates the sound data, and then outputs the data to a speaker. The system usually has small and bounded jitter, but occasionally other tasks in the hearing aid cause some data to be late, causing a noise pulse on the speaker. Is this system hard, firm or soft real time?

It is firm real time because it causes an error that can be perceived but the effect is harmless and does not significantly alter the quality of the experience.


Consider a task that outputs data to a printer. When the printer is idle the printer triggers an event. When the software services that event, it sends more data to the printer. Is this system hard, firm or soft real time?

It is soft real time because the faster it responses the better, but the value of the system (bandwidth is amount of data printed per second) diminishes with latency.

UTAustinX: UT.RTBN.12.01x Realtime Bluetooth Networks

How do you do block comments in YAML?

Emacs has comment-dwim (Do What I Mean) - just select the block and do a:

M-;

It's a toggle - use it to comment AND uncomment blocks.

If you don't have yaml-mode installed you will need to tell Emacs to use the hash character (#).

How to disable phone number linking in Mobile Safari?

My experience is the same as some others mentioned. The meta tag...

<meta name = "format-detection" content = "telephone=no">

...works when the website is running in Mobile Safari (i.e., with chrome) but stops working when run as a webapp (i.e., is saved to home screen and runs without chrome).

My less-than-ideal solution is to insert the values into input fields...

<input type="text" readonly="readonly" style="border:none;" value="3105551212">

It's less than ideal because, despite the border being set to none, iOS renders a multi-pixel gray bar above the field. But, it's better than seeing the number as a link.

How to use a findBy method with comparative criteria

$criteria = new \Doctrine\Common\Collections\Criteria();
    $criteria->where($criteria->expr()->gt('id', 'id'))
        ->setMaxResults(1)
        ->orderBy(array("id" => $criteria::DESC));

$results = $articlesRepo->matching($criteria);

how to prevent css inherit

While this isn't currently available, this fascinating article discusses the use of the Shadow DOM, which is a technique used by browsers to limit how far cascading style sheets cascade, so to speak. He doesn't provide any APIs, as it seems that there are no current libraries able to provide access to this part of the DOM, but it's worth a look. There are links to mailing lists at the bottom of the article if this intrigues you.

Use bash to find first folder name that contains a string

for example:

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print | head -n1)
echo "$dir1"

or (For the better shell solution see Adrian Frühwirth's answer)

for dir1 in *
do
    [[ -d "$dir1" && "$dir1" =~ foo ]] && break
    dir1=        #fix based on comment
done
echo "$dir1"

or

dir1=$(find . -type d -maxdepth 1 -print | grep 'foo' | head -n1)
echo "$dir1"

Edited head -n1 based on @ hek2mgl comment

Next based on @chepner's comments

dir1=$(find . -type d -maxdepth 1 -print | grep -m1 'foo')

or

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)

Import module from subfolder

Set your PYTHONPATH environment variable. For example like this PYTHONPATH=.:.. (for *nix family).

Also you can manually add your current directory (src in your case) to pythonpath:

import os
import sys
sys.path.insert(0, os.getcwd())

How to set socket timeout in C when making multiple connections?

connect timeout has to be handled with a non-blocking socket (GNU LibC documentation on connect). You get connect to return immediately and then use select to wait with a timeout for the connection to complete.

This is also explained here : Operation now in progress error on connect( function) error.

int wait_on_sock(int sock, long timeout, int r, int w)
{
    struct timeval tv = {0,0};
    fd_set fdset;
    fd_set *rfds, *wfds;
    int n, so_error;
    unsigned so_len;

    FD_ZERO (&fdset);
    FD_SET  (sock, &fdset);
    tv.tv_sec = timeout;
    tv.tv_usec = 0;

    TRACES ("wait in progress tv={%ld,%ld} ...\n",
            tv.tv_sec, tv.tv_usec);

    if (r) rfds = &fdset; else rfds = NULL;
    if (w) wfds = &fdset; else wfds = NULL;

    TEMP_FAILURE_RETRY (n = select (sock+1, rfds, wfds, NULL, &tv));
    switch (n) {
    case 0:
        ERROR ("wait timed out\n");
        return -errno;
    case -1:
        ERROR_SYS ("error during wait\n");
        return -errno;
    default:
        // select tell us that sock is ready, test it
        so_len = sizeof(so_error);
        so_error = 0;
        getsockopt (sock, SOL_SOCKET, SO_ERROR, &so_error, &so_len);
        if (so_error == 0)
            return 0;
        errno = so_error;
        ERROR_SYS ("wait failed\n");
        return -errno;
    }
}

How to force an entire layout View refresh?

Just call the activity again itself using the intent. For example to refresh the layout of MainActivity, do like this:

startActivity(new Intent(MainActivity.this, MainActivity.class));

Why does Git treat this text file as a binary file?

I have had same problem. I found the thread when I search solution on google, still I don't find any clue. But I think I found the reason after studying, the below example will explain clearly my clue.

    echo "new text" > new.txt
    git add new.txt
    git commit -m "dummy"

for now, the file new.txt is considered as a text file.

    echo -e "newer text\000" > new.txt
    git diff

you will get this result

diff --git a/new.txt b/new.txt
index fa49b07..410428c 100644
Binary files a/new.txt and b/new.txt differ

and try this

git diff -a

you will get below

    diff --git a/new.txt b/new.txt
    index fa49b07..9664e3f 100644
    --- a/new.txt
    +++ b/new.txt
    @@ -1 +1 @@
    -new file
    +newer text^@

Best equivalent VisualStudio IDE for Mac to program .NET/C#

Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.

How to remove backslash on json_encode() function?

Simpler way would be

$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

First set delegate in viewDidLoad:

self.navigationController.interactivePopGestureRecognizer.delegate = self;

And then disable gesture when pushing:

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [super pushViewController:viewController animated:animated];
    self.interactivePopGestureRecognizer.enabled = NO;
}

And enable in viewDidDisappear:

self.navigationController.interactivePopGestureRecognizer.enabled = YES;

Also, add UINavigationControllerDelegate to your view controller.

How does EL empty operator work in JSF?

Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable using not empty operator on my dataModel that extends javax.faces.model.ListDataModel

Code sample:

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;

public class EntityDataModel extends ListDataModel<Entity> implements
        Collection<Entity>, SelectableDataModel<Entity>, Serializable {

    public EntityDataModel(List<Entity> data) { super(data); }

    @Override
    public Entity getRowData(String rowKey) {
        // In a real app, a more efficient way like a query by rowKey should be
        // implemented to deal with huge data
        List<Entity> entitys = (List<Entity>) getWrappedData();
        for (Entity entity : entitys) {
            if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
        }
        return null;
    }

    @Override
    public Object getRowKey(Entity entity) {
        return entity.getId();
    }

    @Override
    public boolean isEmpty() {
        List<Entity> entity = (List<Entity>) getWrappedData();
        return (entity == null) || entity.isEmpty();
    }
    // ... other not implemented methods of Collection...
}

Insert entire DataTable into database at once instead of row by row?

Consider this approach, you don't need a for loop:

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
    bulkCopy.DestinationTableName = 
        "dbo.BulkCopyDemoMatchingColumns";

    try
    {
        // Write from the source to the destination.
        bulkCopy.WriteToServer(ExitingSqlTableName);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

How do I write to the console from a Laravel Controller?

In Laravel 6 there is a channel called 'stderr'. See config/logging.php:

'stderr' => [
    'driver' => 'monolog',
    'handler' => StreamHandler::class,
    'formatter' => env('LOG_STDERR_FORMATTER'),
    'with' => [
        'stream' => 'php://stderr',
    ],
],

In your controller:

use Illuminate\Support\Facades\Log;

Log::channel('stderr')->info('Something happened!');

How to access the first property of a Javascript object?

if someone prefers array destructuring

const [firstKey] = Object.keys(object);

How can I generate Javadoc comments in Eclipse?

Shift-Alt-J is a useful keyboard shortcut in Eclipse for creating Javadoc comment templates.

Invoking the shortcut on a class, method or field declaration will create a Javadoc template:

public int doAction(int i) {
    return i;
}

Pressing Shift-Alt-J on the method declaration gives:

/**
 * @param i
 * @return
 */
public int doAction(int i) {
    return i;
}

How to declare empty list and then add string in scala?

As everyone already mentioned, this is not the best way of using lists in Scala...

scala> val list = scala.collection.mutable.MutableList[String]()
list: scala.collection.mutable.MutableList[String] = MutableList()

scala> list += "hello"
res0: list.type = MutableList(hello)

scala> list += "world"
res1: list.type = MutableList(hello, world)

scala> list mkString " "
res2: String = hello world

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

The answer are accepted but one thing you could also do is to define the libraries from your project structure. What you can do is :

  1. Comment all the libraries in which problem is coming
  2. Goto your project structure
  3. Add libraries from there and it'll sync automatically and the problem goes off.
  4. If problem persists try looking from the error log that what library is it demanding after following all the above 3 steps.

What happens is the predefined libraries as off now now I'm taking the appcompat:26.0.0-alpha1 it uses the older version of the things when you add something new and tries to resolve it with the old stuffs. When you add it from your project structure, it'll add the same thing but with the new stuffs to resolve it. Your problem would be resolved.

Using python PIL to turn a RGB image into a pure black and white image

Another option (which is useful e.g. for scientific purposes when you need to work with segmentation masks) is simply apply a threshold:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Binarize (make it black and white) an image with Python."""

from PIL import Image
from scipy.misc import imsave
import numpy


def binarize_image(img_path, target_path, threshold):
    """Binarize an image."""
    image_file = Image.open(img_path)
    image = image_file.convert('L')  # convert image to monochrome
    image = numpy.array(image)
    image = binarize_array(image, threshold)
    imsave(target_path, image)


def binarize_array(numpy_array, threshold=200):
    """Binarize a numpy array."""
    for i in range(len(numpy_array)):
        for j in range(len(numpy_array[0])):
            if numpy_array[i][j] > threshold:
                numpy_array[i][j] = 255
            else:
                numpy_array[i][j] = 0
    return numpy_array


def get_parser():
    """Get parser object for script xy.py."""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    parser = ArgumentParser(description=__doc__,
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument("-i", "--input",
                        dest="input",
                        help="read this file",
                        metavar="FILE",
                        required=True)
    parser.add_argument("-o", "--output",
                        dest="output",
                        help="write binarized file hre",
                        metavar="FILE",
                        required=True)
    parser.add_argument("--threshold",
                        dest="threshold",
                        default=200,
                        type=int,
                        help="Threshold when to show white")
    return parser


if __name__ == "__main__":
    args = get_parser().parse_args()
    binarize_image(args.input, args.output, args.threshold)

It looks like this for ./binarize.py -i convert_image.png -o result_bin.png --threshold 200:

enter image description here

How to get Current Timestamp from Carbon in Laravel 5

You can try this if you want date time string:

use Carbon\Carbon;
$current_date_time = Carbon::now()->toDateTimeString(); // Produces something like "2019-03-11 12:25:00"

If you want timestamp, you can try:

use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like 1552296328

See the official Carbon documentation here.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

It took me few hours to solved this because all off the settings that I found here about this error were the same but it still didn't work. The problem was tha I had a folder in my web service from which the file should be send to WinCE device, after converting that folder to an application with Classic.NetAppPool it started to work.

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

It is not possible to write the implementation of a template class in a separate cpp file and compile. All the ways to do so, if anyone claims, are workarounds to mimic the usage of separate cpp file but practically if you intend to write a template class library and distribute it with header and lib files to hide the implementation, it is simply not possible.

To know why, let us look at the compilation process. The header files are never compiled. They are only preprocessed. The preprocessed code is then clubbed with the cpp file which is actually compiled. Now if the compiler has to generate the appropriate memory layout for the object it needs to know the data type of the template class.

Actually it must be understood that template class is not a class at all but a template for a class the declaration and definition of which is generated by the compiler at compile time after getting the information of the data type from the argument. As long as the memory layout cannot be created, the instructions for the method definition cannot be generated. Remember the first argument of the class method is the 'this' operator. All class methods are converted into individual methods with name mangling and the first parameter as the object which it operates on. The 'this' argument is which actually tells about size of the object which incase of template class is unavailable for the compiler unless the user instantiates the object with a valid type argument. In this case if you put the method definitions in a separate cpp file and try to compile it the object file itself will not be generated with the class information. The compilation will not fail, it would generate the object file but it won't generate any code for the template class in the object file. This is the reason why the linker is unable to find the symbols in the object files and the build fails.

Now what is the alternative to hide important implementation details? As we all know the main objective behind separating interface from implementation is hiding implementation details in binary form. This is where you must separate the data structures and algorithms. Your template classes must represent only data structures not the algorithms. This enables you to hide more valuable implementation details in separate non-templatized class libraries, the classes inside which would work on the template classes or just use them to hold data. The template class would actually contain less code to assign, get and set data. Rest of the work would be done by the algorithm classes.

I hope this discussion would be helpful.

Clang vs GCC - which produces faster binaries?

Here are some up-to-date albeit narrow findings of mine with GCC 4.7.2 and Clang 3.2 for C++.

UPDATE: GCC 4.8.1 v clang 3.3 comparison appended below.

UPDATE: GCC 4.8.2 v clang 3.4 comparison is appended to that.

I maintain an OSS tool that is built for Linux with both GCC and Clang, and with Microsoft's compiler for Windows. The tool, coan, is a preprocessor and analyser of C/C++ source files and codelines of such: its computational profile majors on recursive-descent parsing and file-handling. The development branch (to which these results pertain) comprises at present around 11K LOC in about 90 files. It is coded, now, in C++ that is rich in polymorphism and templates and but is still mired in many patches by its not-so-distant past in hacked-together C. Move semantics are not expressly exploited. It is single-threaded. I have devoted no serious effort to optimizing it, while the "architecture" remains so largely ToDo.

I employed Clang prior to 3.2 only as an experimental compiler because, despite its superior compilation speed and diagnostics, its C++11 standard support lagged the contemporary GCC version in the respects exercised by coan. With 3.2, this gap has been closed.

My Linux test harness for current coan development processes roughly 70K sources files in a mixture of one-file parser test-cases, stress tests consuming 1000s of files and scenario tests consuming < 1K files. As well as reporting the test results, the harness accumulates and displays the totals of files consumed and the run time consumed in coan (it just passes each coan command line to the Linux time command and captures and adds up the reported numbers). The timings are flattered by the fact that any number of tests which take 0 measurable time will all add up to 0, but the contribution of such tests is negligible. The timing stats are displayed at the end of make check like this:

coan_test_timer: info: coan processed 70844 input_files.
coan_test_timer: info: run time in coan: 16.4 secs.
coan_test_timer: info: Average processing time per input file: 0.000231 secs.

I compared the test harness performance as between GCC 4.7.2 and Clang 3.2, all things being equal except the compilers. As of Clang 3.2, I no longer require any preprocessor differentiation between code tracts that GCC will compile and Clang alternatives. I built to the same C++ library (GCC's) in each case and ran all the comparisons consecutively in the same terminal session.

The default optimization level for my release build is -O2. I also successfully tested builds at -O3. I tested each configuration 3 times back-to-back and averaged the 3 outcomes, with the following results. The number in a data-cell is the average number of microseconds consumed by the coan executable to process each of the ~70K input files (read, parse and write output and diagnostics).

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 231 | 237 |0.97 |
----------|-----|-----|-----|
Clang-3.2 | 234 | 186 |1.25 |
----------|-----|-----|------
GCC/Clang |0.99 | 1.27|

Any particular application is very likely to have traits that play unfairly to a compiler's strengths or weaknesses. Rigorous benchmarking employs diverse applications. With that well in mind, the noteworthy features of these data are:

  1. -O3 optimization was marginally detrimental to GCC
  2. -O3 optimization was importantly beneficial to Clang
  3. At -O2 optimization, GCC was faster than Clang by just a whisker
  4. At -O3 optimization, Clang was importantly faster than GCC.

A further interesting comparison of the two compilers emerged by accident shortly after those findings. Coan liberally employs smart pointers and one such is heavily exercised in the file handling. This particular smart-pointer type had been typedef'd in prior releases for the sake of compiler-differentiation, to be an std::unique_ptr<X> if the configured compiler had sufficiently mature support for its usage as that, and otherwise an std::shared_ptr<X>. The bias to std::unique_ptr was foolish, since these pointers were in fact transferred around, but std::unique_ptr looked like the fitter option for replacing std::auto_ptr at a point when the C++11 variants were novel to me.

In the course of experimental builds to gauge Clang 3.2's continued need for this and similar differentiation, I inadvertently built std::shared_ptr<X> when I had intended to build std::unique_ptr<X>, and was surprised to observe that the resulting executable, with default -O2 optimization, was the fastest I had seen, sometimes achieving 184 msecs. per input file. With this one change to the source code, the corresponding results were these;

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 234 | 234 |1.00 |
----------|-----|-----|-----|
Clang-3.2 | 188 | 187 |1.00 |
----------|-----|-----|------
GCC/Clang |1.24 |1.25 |

The points of note here are:

  1. Neither compiler now benefits at all from -O3 optimization.
  2. Clang beats GCC just as importantly at each level of optimization.
  3. GCC's performance is only marginally affected by the smart-pointer type change.
  4. Clang's -O2 performance is importantly affected by the smart-pointer type change.

Before and after the smart-pointer type change, Clang is able to build a substantially faster coan executable at -O3 optimisation, and it can build an equally faster executable at -O2 and -O3 when that pointer-type is the best one - std::shared_ptr<X> - for the job.

An obvious question that I am not competent to comment upon is why Clang should be able to find a 25% -O2 speed-up in my application when a heavily used smart-pointer-type is changed from unique to shared, while GCC is indifferent to the same change. Nor do I know whether I should cheer or boo the discovery that Clang's -O2 optimization harbours such huge sensitivity to the wisdom of my smart-pointer choices.

UPDATE: GCC 4.8.1 v clang 3.3

The corresponding results now are:

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.1 | 442 | 443 |1.00 |
----------|-----|-----|-----|
Clang-3.3 | 374 | 370 |1.01 |
----------|-----|-----|------
GCC/Clang |1.18 |1.20 |

The fact that all four executables now take a much greater average time than previously to process 1 file does not reflect on the latest compilers' performance. It is due to the fact that the later development branch of the test application has taken on lot of parsing sophistication in the meantime and pays for it in speed. Only the ratios are significant.

The points of note now are not arrestingly novel:

  • GCC is indifferent to -O3 optimization
  • clang benefits very marginally from -O3 optimization
  • clang beats GCC by a similarly important margin at each level of optimization.

Comparing these results with those for GCC 4.7.2 and clang 3.2, it stands out that GCC has clawed back about a quarter of clang's lead at each optimization level. But since the test application has been heavily developed in the meantime one cannot confidently attribute this to a catch-up in GCC's code-generation. (This time, I have noted the application snapshot from which the timings were obtained and can use it again.)

UPDATE: GCC 4.8.2 v clang 3.4

I finished the update for GCC 4.8.1 v Clang 3.3 saying that I would stick to the same coan snaphot for further updates. But I decided instead to test on that snapshot (rev. 301) and on the latest development snapshot I have that passes its test suite (rev. 619). This gives the results a bit of longitude, and I had another motive:

My original posting noted that I had devoted no effort to optimizing coan for speed. This was still the case as of rev. 301. However, after I had built the timing apparatus into the coan test harness, every time I ran the test suite the performance impact of the latest changes stared me in the face. I saw that it was often surprisingly big and that the trend was more steeply negative than I felt to be merited by gains in functionality.

By rev. 308 the average processing time per input file in the test suite had well more than doubled since the first posting here. At that point I made a U-turn on my 10 year policy of not bothering about performance. In the intensive spate of revisions up to 619 performance was always a consideration and a large number of them went purely to rewriting key load-bearers on fundamentally faster lines (though without using any non-standard compiler features to do so). It would be interesting to see each compiler's reaction to this U-turn,

Here is the now familiar timings matrix for the latest two compilers' builds of rev.301:

coan - rev.301 results

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 428 | 428 |1.00 |
----------|-----|-----|-----|
Clang-3.4 | 390 | 365 |1.07 |
----------|-----|-----|------
GCC/Clang | 1.1 | 1.17|

The story here is only marginally changed from GCC-4.8.1 and Clang-3.3. GCC's showing is a trifle better. Clang's is a trifle worse. Noise could well account for this. Clang still comes out ahead by -O2 and -O3 margins that wouldn't matter in most applications but would matter to quite a few.

And here is the matrix for rev. 619.

coan - rev.619 results

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 210 | 208 |1.01 |
----------|-----|-----|-----|
Clang-3.4 | 252 | 250 |1.01 |
----------|-----|-----|------
GCC/Clang |0.83 | 0.83|

Taking the 301 and the 619 figures side by side, several points speak out.

  • I was aiming to write faster code, and both compilers emphatically vindicate my efforts. But:

  • GCC repays those efforts far more generously than Clang. At -O2 optimization Clang's 619 build is 46% faster than its 301 build: at -O3 Clang's improvement is 31%. Good, but at each optimization level GCC's 619 build is more than twice as fast as its 301.

  • GCC more than reverses Clang's former superiority. And at each optimization level GCC now beats Clang by 17%.

  • Clang's ability in the 301 build to get more leverage than GCC from -O3 optimization is gone in the 619 build. Neither compiler gains meaningfully from -O3.

I was sufficiently surprised by this reversal of fortunes that I suspected I might have accidentally made a sluggish build of clang 3.4 itself (since I built it from source). So I re-ran the 619 test with my distro's stock Clang 3.3. The results were practically the same as for 3.4.

So as regards reaction to the U-turn: On the numbers here, Clang has done much better than GCC at at wringing speed out of my C++ code when I was giving it no help. When I put my mind to helping, GCC did a much better job than Clang.

I don't elevate that observation into a principle, but I take the lesson that "Which compiler produces the better binaries?" is a question that, even if you specify the test suite to which the answer shall be relative, still is not a clear-cut matter of just timing the binaries.

Is your better binary the fastest binary, or is it the one that best compensates for cheaply crafted code? Or best compensates for expensively crafted code that prioritizes maintainability and reuse over speed? It depends on the nature and relative weights of your motives for producing the binary, and of the constraints under which you do so.

And in any case, if you deeply care about building "the best" binaries then you had better keep checking how successive iterations of compilers deliver on your idea of "the best" over successive iterations of your code.

How do I create a master branch in a bare Git repository?

By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.

https://git-scm.com/docs

How to search and replace text in a file?

Late answer, but this is what I use to find and replace inside a text file:

with open("test.txt") as r:
  text = r.read().replace("THIS", "THAT")
with open("test.txt", "w") as w:
  w.write(text)

DEMO

How to make in CSS an overlay over an image?

You can achieve this with this simple CSS/HTML:

.image-container {
    position: relative;
    width: 200px;
    height: 300px;
}
.image-container .after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    color: #FFF;
}
.image-container:hover .after {
    display: block;
    background: rgba(0, 0, 0, .6);
}

HTML

<div class="image-container">
    <img src="http://lorempixel.com/300/200" />
    <div class="after">This is some content</div>
</div>

Demo: http://jsfiddle.net/6Mt3Q/


UPD: Here is one nice final demo with some extra stylings.

_x000D_
_x000D_
.image-container {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
}_x000D_
.image-container img {display: block;}_x000D_
.image-container .after {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    display: none;_x000D_
    color: #FFF;_x000D_
}_x000D_
.image-container:hover .after {_x000D_
    display: block;_x000D_
    background: rgba(0, 0, 0, .6);_x000D_
}_x000D_
.image-container .after .content {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    font-family: Arial;_x000D_
    text-align: center;_x000D_
    width: 100%;_x000D_
    box-sizing: border-box;_x000D_
    padding: 5px;_x000D_
}_x000D_
.image-container .after .zoom {_x000D_
    color: #DDD;_x000D_
    font-size: 48px;_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    margin: -30px 0 0 -19px;_x000D_
    height: 50px;_x000D_
    width: 45px;_x000D_
    cursor: pointer;_x000D_
}_x000D_
.image-container .after .zoom:hover {_x000D_
    color: #FFF;_x000D_
}
_x000D_
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="image-container">_x000D_
    <img src="http://lorempixel.com/300/180" />_x000D_
    <div class="after">_x000D_
        <span class="content">This is some content. It can be long and span several lines.</span>_x000D_
        <span class="zoom">_x000D_
            <i class="fa fa-search"></i>_x000D_
        </span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I convert a C# List<string[]> to a Javascript array?

Many way to Json Parse but i have found most effective way to

 @model  List<string[]>

     <script>

         function DataParse() {
             var model = '@Html.Raw(Json.Encode(Model))';
             var data = JSON.parse(model);  

            for (i = 0; i < data.length; i++) {
            ......
             }

     </script>

Should I use != or <> for not equal in T-SQL?

The ANSI SQL Standard defines <> as the "not equal to" operator,

http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt (5.2 <token> and <separator>)

There is no != operator according to the ANSI/SQL 92 standard.

SyntaxError: expected expression, got '<'

I got this type question on Django, and My issue is forget to add static to the <script> tag.

Such as in my template:

<script  type="text/javascript"  src="css/layer.js"></script>

I should add the static to it like this:

<script type="text/javascript" src="{% static 'css/layer.js' %}" ></script>

Order Bars in ggplot2 bar graph

If the chart columns come from a numeric variable as in the dataframe below, you can use a simpler solution:

ggplot(df, aes(x = reorder(Colors, -Qty, sum), y = Qty)) 
+ geom_bar(stat = "identity")  

The minus sign before the sort variable (-Qty) controls the sort direction (ascending/descending)

Here's some data for testing:

df <- data.frame(Colors = c("Green","Yellow","Blue","Red","Yellow","Blue"),  
                 Qty = c(7,4,5,1,3,6)
                )

**Sample data:**
  Colors Qty
1  Green   7
2 Yellow   4
3   Blue   5
4    Red   1
5 Yellow   3
6   Blue   6

When I found this thread, that was the answer I was looking for. Hope it's useful for others.

What are callee and caller saved registers?

I'm not really sure if this adds anything but,

Caller saved means that the caller has to save the registers because they will be clobbered in the call and have no choice but to be left in a clobbered state after the call returns (for instance, the return value being in eax for cdecl. It makes no sense for the return value to be restored to the value before the call by the callee, because it is a return value).

Callee saved means that the callee has to save the registers and then restore them at the end of the call because they have the guarantee to the caller of containing the same values after the function returns, and it is possible to restore them, even if they are clobbered at some point during the call.

The issue with the above definition though is that for instance on Wikipedia cdecl, it says eax, ecx and edx are caller saved and rest are callee saved, this suggests that the caller must save all 3 of these registers, when it might not if none of these registers were used by the caller in the first place. In which case caller 'saved' becomes a misnomer, but 'call clobbered' still correctly applies. This is the same with 'the rest' being called callee saved. It implies that all other x86 registers will be saved and restored by the callee when this is not the case if some of the registers are never used in the call anyway. With cdecl, eax:edx may be used to return a 64 bit value. I'm not sure why ecx is also caller saved if needed, but it is.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Unless there is some other requirement not specified, I would simply convert your color image to grayscale and work with that only (no need to work on the 3 channels, the contrast present is too high already). Also, unless there is some specific problem regarding resizing, I would work with a downscaled version of your images, since they are relatively large and the size adds nothing to the problem being solved. Then, finally, your problem is solved with a median filter, some basic morphological tools, and statistics (mostly for the Otsu thresholding, which is already done for you).

Here is what I obtain with your sample image and some other image with a sheet of paper I found around:

enter image description here enter image description here

The median filter is used to remove minor details from the, now grayscale, image. It will possibly remove thin lines inside the whitish paper, which is good because then you will end with tiny connected components which are easy to discard. After the median, apply a morphological gradient (simply dilation - erosion) and binarize the result by Otsu. The morphological gradient is a good method to keep strong edges, it should be used more. Then, since this gradient will increase the contour width, apply a morphological thinning. Now you can discard small components.

At this point, here is what we have with the right image above (before drawing the blue polygon), the left one is not shown because the only remaining component is the one describing the paper:

enter image description here

Given the examples, now the only issue left is distinguishing between components that look like rectangles and others that do not. This is a matter of determining a ratio between the area of the convex hull containing the shape and the area of its bounding box; the ratio 0.7 works fine for these examples. It might be the case that you also need to discard components that are inside the paper, but not in these examples by using this method (nevertheless, doing this step should be very easy especially because it can be done through OpenCV directly).

For reference, here is a sample code in Mathematica:

f = Import["http://thwartedglamour.files.wordpress.com/2010/06/my-coffee-table-1-sa.jpg"]
f = ImageResize[f, ImageDimensions[f][[1]]/4]
g = MedianFilter[ColorConvert[f, "Grayscale"], 2]
h = DeleteSmallComponents[Thinning[
     Binarize[ImageSubtract[Dilation[g, 1], Erosion[g, 1]]]]]
convexvert = ComponentMeasurements[SelectComponents[
     h, {"ConvexArea", "BoundingBoxArea"}, #1 / #2 > 0.7 &], 
     "ConvexVertices"][[All, 2]]
(* To visualize the blue polygons above: *)
Show[f, Graphics[{EdgeForm[{Blue, Thick}], RGBColor[0, 0, 1, 0.5], 
     Polygon @@ convexvert}]]

If there are more varied situations where the paper's rectangle is not so well defined, or the approach confuses it with other shapes -- these situations could happen due to various reasons, but a common cause is bad image acquisition -- then try combining the pre-processing steps with the work described in the paper "Rectangle Detection based on a Windowed Hough Transform".

C/C++ switch case with string

If you are after performance and don't want to go through all the if clauses each time if there are many or the need to hash the values, you could send some extra information to the function with the help of enum or just add an enum type to your structure.

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

In this particular case, an even simpler fix would be to just get rid of the "+" all together because AGE is a string literal and what comes before and after are also string literals. You could write line 3 as:

str += "Do you feel " AGE " years old?";

This is because most C/C++ compilers will concatenate string literals automatically. The above is equivalent to:

str += "Do you feel " "42" " years old?";

which the compiler will convert to:

str += "Do you feel 42 years old?";

Best way in asp.net to force https for an entire site?

If you are using ASP.NET Core you could try out the nuget package SaidOut.AspNetCore.HttpsWithStrictTransportSecurity.

Then you only need to add

app.UseHttpsWithHsts(HttpsMode.AllowedRedirectForGet, configureRoutes: routeAction);

This will also add HTTP StrictTransportSecurity header to all request made using https scheme.

Example code and documentation https://github.com/saidout/saidout-aspnetcore-httpswithstricttransportsecurity#example-code

Tkinter: "Python may not be configured for Tk"

Even after installing python-tk, python3-tk I was getting error your python is not configured for Tk.

So I additionally installed tk8.6-dev Then I build my Python again, run following again: make, make install.

When I did this I saw messages on screen that it is building _tkinter and related modules. Once that is done, I tried 'import tkinter" and it worked.

Laravel 5 – Remove Public from URL

You can remove public keyword from url using various methods.

1) If you are using dedicated hosting and you have root access then You can remove public keyword from url using Virtual Host. You should give DocumentRoot path with public. So this will start index from public directory and remove it from url.

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/html/{yoursourcedirectory}/public

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

2) If you dont have root access of your hosting then you should genarate a new .htaccess file in your root directory and put the code as below

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1 

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
</IfModule>

You can get more reference here.

PHPMailer: SMTP Error: Could not connect to SMTP host

I had the same problem and it was because PHPMailer realized the server supported STARTTLS so it tried to automatically upgrade the connection to an encrypted connection. My mail server is on the same subnet as the web server within my network which is all behind our domain firewalls so I'm not too worried about using encryption (plus the generated emails don't contain sensitive data anyway).

So what I went ahead and did was change the SMTPAutoTLS to false in the class.phpmailer.php file.

/**
 * Whether to enable TLS encryption automatically if a server supports it,
 * even if `SMTPSecure` is not set to 'tls'.
 * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
 * @var boolean
 */
public $SMTPAutoTLS = false;

VBA procedure to import csv file into access

Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work

Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant

    sFileIn = "z:\docs\FileName.csv"
    sFileOut = "z:\docs\FileOut.csv"

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading

    sTmp = tsIn.ReadAll

    Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
    aryFile = Split(sTmp, vbCrLf)

    ''Start at line 3 and end at last line -1
    For i = 3 To UBound(aryFile) - 1
        tsOut.WriteLine aryFile(i)
    Next

    tsOut.Close

    DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub

Edit re various comments

It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.

About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003

Introduction to importing and exporting data -- Applies to: Microsoft Access 2010

Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.

Troubleshooting misplaced .git directory (nothing to commit)

This must have happened because by mistake you reinitialized git in the same directory. Delete the .git folder using the following command Go to repository you want to upload open the terminal and then use the following commands

  1. remove the .git repository sudo rm -r .git
  2. Now again repeat from initializing git repo using git init
  3. then git commit -m "first commit"
  4. git remote add origin https://github.com/user_name/repo
  5. git push -u origin master After that enter the username and password and you are good to go

Using if-else in JSP

Instead of if-else condition use if in both conditions. it will work that way but not sure why.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

I personally use a little AutoHotkey script to remap certain keyboard functions, for the console window (CMD) I use:

; Redefine only when the active window is a console window 
#IfWinActive ahk_class ConsoleWindowClass

; Close Command Window with Ctrl+w
$^w::
WinGetTitle sTitle
If (InStr(sTitle, "-")=0) { 
    Send EXIT{Enter}
} else {
    Send ^w
}

return 


; Ctrl+up / Down to scroll command window back and forward
^Up::
Send {WheelUp}
return

^Down::
Send {WheelDown}
return


; Paste in command window
^V::
; Spanish menu (Editar->Pegar, I suppose English version is the same, Edit->Paste)
Send !{Space}ep
return

#IfWinActive 

How to parse JSON in Kotlin?

i am using my custom implementation in kotlin:

/**
 * Created by Anton Kogan on 10/9/2020
 */
object JsonParser {

    val TAG = "JsonParser"
    /**
 * parse json object
 * @param objJson
 * @param include - all  keys, that you want to display
 * @return  Map<String, String>
 * @throws JSONException
 */
    @Throws(JSONException::class)
    fun parseJson(objJson: Any?, map :HashMap<String, String>, include : Array<String>?): Map<String, String> {
        // If obj is a json array
        if (objJson is JSONArray) {
            for (i in 0 until objJson.length()) {
                parseJson(objJson[i], map, include)
            }
        } else if (objJson is JSONObject) {
            val it: Iterator<*> = objJson.keys()
            while (it.hasNext()) {
                val key = it.next().toString()
                // If you get an array
                when (val jobject = objJson[key]) {
                    is JSONArray -> {
                        Log.e(TAG, " JSONArray: $jobject")
                        parseJson(
                            jobject, map, include
                        )
                    }
                    is JSONObject -> {
                        Log.e(TAG, " JSONObject: $jobject")
                        parseJson(
                            jobject, map, include
                        )
                    }
                    else -> {
//
                        if(include == null || include.contains(key)) // here is check for include param
                        {
                            map[key] = jobject.toString()
                            Log.e(TAG, " adding to map: $key $jobject")
                        }
                    }
                }
            }
        }
        return map
    }

    /**
     * parse json object
     * @param objJson
     * @param include - all  keys, that you want to display
     * @return  Map<String, String>
     * @throws JSONException
     */
    @Throws(JSONException::class)
    fun parseJson(objJson: Any?, map :HashMap<String, String>): Map<String, String> {
        return parseJson(objJson, map, null)
    }
}

You can use it like:

    val include= arrayOf(
        "atHome",//JSONArray
        "cat",
        "dog",
        "persons",//JSONArray
        "man",
        "woman"
    )
    JsonParser.parseJson(jsonObject, map, include)
    val linearContent: LinearLayout = taskInfoFragmentBinding.infoContainer

here is some useful links:

json parsing :

plugin: https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-

create POJOs from json: https://codebeautify.org/jsonviewer

Retrofit: https://square.github.io/retrofit/

Gson: https://github.com/google/gson

jQuery if checkbox is checked

if ($('input.checkbox_check').is(':checked')) {

How can I restart a Java application?

Although this question is old and answered, I've stumbled across a problem with some of the solutions and decided to add my suggestion into the mix.

The problem with some of the solutions is that they build a single command string. This creates issues when some parameters contain spaces, especially java.home.

For example, on windows, the line

final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";

Might return something like this:C:\Program Files\Java\jre7\bin\java

This string has to be wrapped in quotes or escaped due to the space in Program Files. Not a huge problem, but somewhat annoying and error prone, especially in cross platform applications.

Therefore my solution builds the command as an array of commands:

public static void restart(String[] args) {

        ArrayList<String> commands = new ArrayList<String>(4 + jvmArgs.size() + args.length);
        List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();

        // Java
        commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");

        // Jvm arguments
        for (String jvmArg : jvmArgs) {
            commands.add(jvmArg);
        }

        // Classpath
        commands.add("-cp");
        commands.add(ManagementFactory.getRuntimeMXBean().getClassPath());

        // Class to be executed
        commands.add(BGAgent.class.getName());

        // Command line arguments
        for (String arg : args) {
            commands.add(arg);
        }

        File workingDir = null; // Null working dir means that the child uses the same working directory

        String[] env = null; // Null env means that the child uses the same environment

        String[] commandArray = new String[commands.size()];
        commandArray = commands.toArray(commandArray);

        try {
            Runtime.getRuntime().exec(commandArray, env, workingDir);
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Show a number to two decimal places

Alternatively,

$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00

running a command as a super user from a python script

I tried all the solutions, but did not work. Wanted to run long running tasks with Celery but for these I needed to run sudo chown command with subprocess.call().

This is what worked for me:

To add safe environment variables, in command line, type:

export MY_SUDO_PASS="user_password_here"

To test if it's working type:

echo $MY_SUDO_PASS
 > user_password_here

To run it at system startup add it to the end of this file:

nano ~/.bashrc  

#.bashrc
...
existing_content:

  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi
...

export MY_SUDO_PASS="user_password_here"

You can add all your environment variables passwords, usernames, host, etc here later.

If your variables are ready you can run:

To update:

echo $MY_SUDO_PASS | sudo -S apt-get update

Or to install Midnight Commander

echo $MY_SUDO_PASS | sudo -S apt-get install mc

To start Midnight Commander with sudo

echo $MY_SUDO_PASS | sudo -S mc

Or from python shell (or Django/Celery), to change directory ownership recursively:

python
>> import subprocess
>> subprocess.call('echo $MY_SUDO_PASS | sudo -S chown -R username_here /home/username_here/folder_to_change_ownership_recursivley', shell=True)

Hope it helps.

MySQL - How to parse a string value to DATETIME format inside an INSERT statement?

Use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert:

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
  (STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

You have to change androidx.constraintlayout.widget.ConstraintLayout to RelativeLayout.

Must issue a STARTTLS command first

Try this code :

Properties props = new Properties();
                        props.put("mail.smtp.host", "smtp.gmail.com");
                        props.put("mail.smtp.socketFactory.port", "465");
                        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                        props.put("mail.smtp.auth", "true");
                        props.put("mail.smtp.prot", "465");

                        Session session = Session.getDefaultInstance(props,
                                new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {

                                return new PasswordAuthentication("PUT THE MAIL SENDER HERE !", "PUT THE PASSWORD OF THE MAIL SENDER HERE !");
                            }
                        }
                        );
                        try {
                            Message message = new MimeMessage(session);
                            message.setFrom(new InternetAddress("PUT THE MAIL SENDER HERE !"));
                            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("PUT THE MAIL RECEIVER HERE !"));
                            message.setSubject("MAIL SUBJECT !");
                            message.setText("MAIL BODY !");
                            Transport.send(message);

                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

You have to less secure the security of the mail sender. if the problem persist I think It can be caused by the antivirus, try to disable it ..

How to convert password into md5 in jquery?

Fiddle: http://jsfiddle.net/33HMj/

Js:

var md5 = function(value) {
    return CryptoJS.MD5(value).toString();
}

$("input").keyup(function () {
     var value = $(this).val(),
         hash = md5(value);
     $(".test").html(hash);
 });

Why is nginx responding to any domain name?

I was unable to resolve my problem with any of the other answers. I resolved the issue by checking to see if the host matched and returning a 403 if it did not. (I had some random website pointing to my web servers content. I'm guessing to hijack search rank)

server {
    listen 443;
    server_name example.com;

    if ($host != "example.com") {
        return 403;
    }

    ...
}

What is the difference between 127.0.0.1 and localhost

There is nothing different. One is easier to remember than the other. Generally, you define a name to associate with an IP address. You don't have to specify localhost for 127.0.0.1, you could specify any name you want.

How to set -source 1.7 in Android Studio and Gradle

Always use latest SDK version to build:

compileSdkVersion 23

It does not affect runtime behavior, but give you latest programming features.

printf formatting (%d versus %u)

%u prints unsigned integer

%d prints signed integer

to get a pointer address use %p

Other List of Formatting Escapes:

Here are the full list of formatting escapes. I am just giving a screen shot from this page

enter image description here

AngularJS : Factory and Service?

Factory and Service is a just wrapper of a provider.

Factory

Factory can return anything which can be a class(constructor function), instance of class, string, number or boolean. If you return a constructor function, you can instantiate in your controller.

 myApp.factory('myFactory', function () {

  // any logic here..

  // Return any thing. Here it is object
  return {
    name: 'Joe'
  }
}

Service

Service does not need to return anything. But you have to assign everything in this variable. Because service will create instance by default and use that as a base object.

myApp.service('myService', function () {

  // any logic here..

  this.name = 'Joe';
}

Actual angularjs code behind the service

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
        return $injector.instantiate(constructor);
    }]);
}

It just a wrapper around the factory. If you return something from service, then it will behave like Factory.

IMPORTANT: The return result from Factory and Service will be cache and same will be returned for all controllers.

When should i use them?

Factory is mostly preferable in all cases. It can be used when you have constructor function which needs to be instantiated in different controllers.

Service is a kind of Singleton Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application. Eg: Authenticated user details.

For further understanding, read

http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html

http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

What is the string concatenation operator in Oracle?

Using CONCAT(CONCAT(,),) worked for me when concatenating more than two strings.

My problem required working with date strings (only) and creating YYYYMMDD from YYYY-MM-DD as follows (i.e. without converting to date format):

CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD

Where is database .bak file saved from SQL Server Management Studio?

As said by Faiyaz, to get default backup location for the instance, you cannot get it into msdb, but you have to look into Registry. You can get it in T-SQL in using xp_instance_regread stored procedure like this:

EXEC  master.dbo.xp_instance_regread 
      N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQLServer',N'BackupDirectory'

The double backslash (\\) is because the spaces into that key name part (Microsoft SQL Server). The "MSSQL12.MSSQLSERVER" part is for default instance name for SQL 2014. You have to adapt to put your own instance name (look into Registry).

Transfer data from one HTML file to another

The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript.

1) page1.html

<!-- Value passing one page to another 
     Author: Codemaker
-->
<html>
    <head>
        <title> Page 1 - Codemaker</title>
    </head>
    <body>
        <form method="get" action="page2.html">
            <table>
                <tr>
                    <td>First Name:</td>
                    <td><input type=text name=firstname size=10></td>
                </tr>
                <tr>
                    <td>Last Name:</td>
                    <td><input type=text name=lastname size=10></td>
                </tr>
                <tr>
                    <td>Age:</td>
                    <td><input type=text name=age size=10></td>
                </tr>
                <tr>
                    <td colspan=2><input type=submit value="Submit">
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

2) page2.html

<!-- Value passing one page to another 
     Author: Codemaker
-->

<html>
    <head>
        <title> Page 2 - Codemaker</title>
    </head>
    <body>
        <script>
            function getParams(){
                var idx = document.URL.indexOf('?');
                var params = new Array();
                if (idx != -1) {
                    var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
                    for (var i=0; i<pairs.length; i++){
                        nameVal = pairs[i].split('=');
                        params[nameVal[0]] = nameVal[1];
                    }
                }
                return params;
            }
            params = getParams();
            firstname = unescape(params["firstname"]);
            lastname = unescape(params["lastname"]);
            age = unescape(params["age"]);
            document.write("firstname = " + firstname + "<br>");
            document.write("lastname = " + lastname + "<br>");
            document.write("age = " + age + "<br>");
        </script>
    </body>
</html>

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

The method in the post you link to calls Invoke/BeginInvoke before checking if the control's handle has been created in the case where it's being called from a thread that didn't create the control.

So you'll get the exception when your method is called from a thread other than the one that created the control. This can happen from remoting events or queued work user items...

EDIT

If you check InvokeRequired and HandleCreated before calling invoke you shouldn't get that exception.

Simulate delayed and dropped packets on Linux

One of the most used tool in the scientific community to that purpose is DummyNet. Once you have installed the ipfw kernel module, in order to introduce 50ms propagation delay between 2 machines simply run these commands:

./ipfw pipe 1 config delay 50ms
./ipfw add 1000 pipe 1 ip from $IP_MACHINE_1 to $IP_MACHINE_2

In order to also introduce 50% of packet losses you have to run:

./ipfw pipe 1 config plr 0.5

Here more details.

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

Permanent Fix

pip install --upgrade pip --trusted-host pypi.org --trusted-host files.pythonhosted.org

For eg:

pip install <package name> --trusted-host pypi.org --trusted-host files.pythonhosted.org

Writing JSON object to a JSON file with fs.writeFileSync

Here's a variation, using the version of fs that uses promises:

const fs = require('fs');

await fs.promises.writeFile('../data/phraseFreqs.json', JSON.stringify(output)); // UTF-8 is default

jquery how to get the page's current screen top position?

var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

What's the best way to break from nested loops in JavaScript?

var str = "";
for (var x = 0; x < 3; x++) {
    (function() {  // here's an anonymous function
        for (var y = 0; y < 3; y++) {
            for (var z = 0; z < 3; z++) {
                // you have access to 'x' because of closures
                str += "x=" + x + "  y=" + y + "  z=" + z + "<br />";
                if (x == z && z == 2) {
                    return;
                }
            }
        }
    })();  // here, you execute your anonymous function
}

How's that? :)

Is there a way to make AngularJS load partials in the beginning and not at when needed?

Another method is to use HTML5's Application Cache to download all files once and keep them in the browser's cache. The above link contains much more information. The following information is from the article:

Change your <html> tag to include a manifest attribute:

<html manifest="http://www.example.com/example.mf">

A manifest file must be served with the mime-type text/cache-manifest.

A simple manifest looks something like this:

CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js
http://cdn.example.com/scripts/main.js

Once an application is offline it remains cached until one of the following happens:

  1. The user clears their browser's data storage for your site.
  2. The manifest file is modified. Note: updating a file listed in the manifest doesn't mean the browser will re-cache that resource. The manifest file itself must be altered.

How to increase memory limit for PHP over 2GB?

I had the same problem with commandline php even when ini_set("memory_limit", "-1"); was set, so the limit is in php not from apache.

You should check if you are using the 64bit version of php.

Look at this question about Checking if code is running on 64-bit PHP to find out what php you are using.

I think your php is compiled in 32 bit.

How to set background color of HTML element using css properties in JavaScript

Changing CSS of a HTMLElement

You can change most of the CSS properties with JavaScript, use this statement:

document.querySelector(<selector>).style[<property>] = <new style>

where <selector>, <property>, <new style> are all String objects.

Usually, the style property will have the same name as the actual name used in CSS. But whenever there is more that one word, it will be camel case: for example background-color is changed with backgroundColor.

The following statement will set the background of #container to the color red:

documentquerySelector('#container').style.background = 'red'

Here's a quick demo changing the color of the box every 0.5s:

_x000D_
_x000D_
colors = ['rosybrown', 'cornflowerblue', 'pink', 'lightblue', 'lemonchiffon', 'lightgrey', 'lightcoral', 'blueviolet', 'firebrick', 'fuchsia', 'lightgreen', 'red', 'purple', 'cyan']_x000D_
_x000D_
let i = 0_x000D_
setInterval(() => {_x000D_
  const random = Math.floor(Math.random()*colors.length)_x000D_
  document.querySelector('.box').style.background = colors[random];_x000D_
}, 500)
_x000D_
.box {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_


Changing CSS of multiple HTMLElement

Imagine you would like to apply CSS styles to more than one element, for example, make the background color of all elements with the class name box lightgreen. Then you can:

  1. select the elements with .querySelectorAll and unwrap them in an object Array with the destructuring syntax:

    const elements = [...document.querySelectorAll('.box')]
    
  2. loop over the array with .forEach and apply the change to each element:

    elements.forEach(element => element.style.background = 'lightgreen')
    

Here is the demo:

_x000D_
_x000D_
const elements = [...document.querySelectorAll('.box')]_x000D_
elements.forEach(element => element.style.background = 'lightgreen')
_x000D_
.box {_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
  display: inline-block;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<div class="box"></div>_x000D_
<div class="box"></div>_x000D_
<div class="box"></div>_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_


Another method

If you want to change multiple style properties of an element more than once you may consider using another method: link this element to another class instead.

Assuming you can prepare the styles beforehand in CSS you can toggle classes by accessing the classList of the element and calling the toggle function:

_x000D_
_x000D_
document.querySelector('.box').classList.toggle('orange')
_x000D_
.box {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
.orange {_x000D_
  background: orange;_x000D_
}
_x000D_
<div class='box'></div>
_x000D_
_x000D_
_x000D_


List of CSS properties in JavaScript

Here is the complete list:

alignContent
alignItems
alignSelf
animation
animationDelay
animationDirection
animationDuration
animationFillMode
animationIterationCount
animationName
animationTimingFunction
animationPlayState
background
backgroundAttachment
backgroundColor
backgroundImage
backgroundPosition
backgroundRepeat
backgroundClip
backgroundOrigin
backgroundSize</a></td>
backfaceVisibility
borderBottom
borderBottomColor
borderBottomLeftRadius
borderBottomRightRadius
borderBottomStyle
borderBottomWidth
borderCollapse
borderColor
borderImage
borderImageOutset
borderImageRepeat
borderImageSlice
borderImageSource  
borderImageWidth
borderLeft
borderLeftColor
borderLeftStyle
borderLeftWidth
borderRadius
borderRight
borderRightColor
borderRightStyle
borderRightWidth
borderSpacing
borderStyle
borderTop
borderTopColor
borderTopLeftRadius
borderTopRightRadius
borderTopStyle
borderTopWidth
borderWidth
bottom
boxShadow
boxSizing
captionSide
clear
clip
color
columnCount
columnFill
columnGap
columnRule
columnRuleColor
columnRuleStyle
columnRuleWidth
columns
columnSpan
columnWidth
counterIncrement
counterReset
cursor
direction
display
emptyCells
filter
flex
flexBasis
flexDirection
flexFlow
flexGrow
flexShrink
flexWrap
content
fontStretch
hangingPunctuation
height
hyphens
icon
imageOrientation
navDown
navIndex
navLeft
navRight
navUp>
cssFloat
font
fontFamily
fontSize
fontStyle
fontVariant
fontWeight
fontSizeAdjust
justifyContent
left
letterSpacing
lineHeight
listStyle
listStyleImage
listStylePosition
listStyleType
margin
marginBottom
marginLeft
marginRight
marginTop
maxHeight
maxWidth
minHeight
minWidth
opacity
order
orphans
outline
outlineColor
outlineOffset
outlineStyle
outlineWidth
overflow
overflowX
overflowY
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
pageBreakAfter
pageBreakBefore
pageBreakInside
perspective
perspectiveOrigin
position
quotes
resize
right
tableLayout
tabSize
textAlign
textAlignLast
textDecoration
textDecorationColor
textDecorationLine
textDecorationStyle
textIndent
textOverflow
textShadow
textTransform
textJustify
top
transform
transformOrigin
transformStyle
transition
transitionProperty
transitionDuration
transitionTimingFunction
transitionDelay
unicodeBidi
userSelect
verticalAlign
visibility
voiceBalance
voiceDuration
voicePitch
voicePitchRange
voiceRate
voiceStress
voiceVolume
whiteSpace
width
wordBreak
wordSpacing
wordWrap
widows
writingMode
zIndex

Accessing localhost of PC from USB connected Android mobile device

Problem I faced maybe it will help some one, I was working long time where my pc and android device connected to the same WiFi network and the android device connected via the IPV4 address of the pc with opened port 8080 trought the fire wall.

ONE DAY : I installed Genymotion emulator in order to debug UI on different screens. THANKS to Genymotion/Virtualbox network configurations it ruined my WiFi adapter.

The fix was to reconfigure IPV4/TCP settings on the WiFi netwrok adapter :

enter image description here

How to draw checkbox or tick mark in GitHub Markdown table?

Try adding a - before the [] or [x]. That's an - followed by a blank space .

Below is an example from Github blog.

### Solar System Exploration, 1950s – 1960s

- [ ] Mercury
- [x] Venus
- [x] Earth (Orbit/Moon)
- [x] Mars
- [ ] Jupiter
- [ ] Saturn
- [ ] Uranus
- [ ] Neptune
- [ ] Comet Haley

It appears like below:

Resultant Image

Here's how one could do the same in a table:

| Task           | Time required | Assigned to   | Current Status | Finished | 
|----------------|---------------|---------------|----------------|-----------|
| Calendar Cache | > 5 hours  |  | in progress | - [x] ok?
| Object Cache   | > 5 hours  |  | in progress | [x] item1<br/>[ ] item2
| Object Cache   | > 5 hours  |  | in progress | <ul><li>- [x] item1</li><li>- [ ] item2</li></ul>
| Object Cache   | > 5 hours  |  | in progress | <ul><li>[x] item1</li><li>[ ] item2</li></ul>


- [x] works
- [x] works too

Here's how it looks:

enter image description here

Comparing two java.util.Dates to see if they are in the same day

you can apply the same logic as the SimpleDateFormat solution without relying on SimpleDateFormat

date1.getFullYear()*10000 + date1.getMonth()*100 + date1.getDate() == 
date2.getFullYear()*10000 + date2.getMonth()*100 + date2.getDate()

How do I get monitor resolution in Python?

Another version using xrandr:

import re
from subprocess import run, PIPE

output = run(['xrandr'], stdout=PIPE).stdout.decode()
result = re.search(r'current (\d+) x (\d+)', output)
width, height = map(int, result.groups()) if result else (800, 600)

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

Try pulling out the NVIDIA graphics card and reinserting it.

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

Move cursor to end of file in vim

Another alternative:

:call cursor('.',strwidth(getline('.')))

This is may be useful if you're writing a function. Another situation would be when I need to open a specific template and jump to end of first line, I can do:

vi +"call cursor('.',strwidth(getline(1)))"  notetaking_template.txt

The above could also be done with

vi +"execute ':normal! $'" notetaking_template.txt

See also:

vim - Get length of the current line

ORA-00907: missing right parenthesis

ORA-00907: missing right parenthesis

This is one of several generic error messages which indicate our code contains one or more syntax errors. Sometimes it may mean we literally have omitted a right bracket; that's easy enough to verify if we're using an editor which has a match bracket capability (most text editors aimed at coders do). But often it means the compiler has come across a keyword out of context. Or perhaps it's a misspelled word, a space instead of an underscore or a missing comma.

Unfortunately the possible reasons why our code won't compile is virtually infinite and the compiler just isn't clever enough to distinguish them. So it hurls a generic, slightly cryptic, message like ORA-00907: missing right parenthesis and leaves it to us to spot the actual bloomer.

The posted script has several syntax errors. First I will discuss the error which triggers that ORA-0097 but you'll need to fix them all.

Foreign key constraints can be declared in line with the referencing column or at the table level after all the columns have been declared. These have different syntaxes; your scripts mix the two and that's why you get the ORA-00907.

In-line declaration doesn't have a comma and doesn't include the referencing column name.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8) 
          CONSTRAINT historys_T_FK FOREIGN KEY REFERENCES T_customers ON DELETE CASCADE,
    order_id           VARCHAR2 (10) NOT NULL,
          CONSTRAINT fk_order_id_orders REFERENCES orders ON DELETE CASCADE)

Table level constraints are a separate component, and so do have a comma and do mention the referencing column.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8),    
    order_id           VARCHAR2 (10) NOT NULL,
    CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customers ON DELETE CASCADE,   
   CONSTRAINT fk_order_id_orders FOREIGN KEY (order_id) REFERENCES orders ON DELETE CASCADE)

Here is a list of other syntax errors:

  1. The referenced table (and the referenced primary key or unique constraint) must already exist before we can create a foreign key against them. So you cannot create a foreign key for HISTORYS_T before you have created the referenced ORDERS table.
  2. You have misspelled the names of the referenced tables in some of the foreign key clauses (LIBRARY_T and FORMAT_T).
  3. You need to provide an expression in the DEFAULT clause. For DATE columns that is usually the current date, DATE DEFAULT sysdate.

Looking at our own code with a cool eye is a skill we all need to gain to be successful as developers. It really helps to be familiar with Oracle's documentation. A side-by-side comparison of your code and the examples in the SQL Reference would have helped you resolved these syntax errors in considerably less than two days. Find it here (11g) and here (12c).

As well as syntax errors, your scripts contain design mistakes. These are not failures, but bad practice which should not become habits.

  1. You have not named most of your constraints. Oracle will give them a default name but it will be a horrible one, and makes the data dictionary harder to understand. Explicitly naming every constraint helps us navigate the physical database. It also leads to more comprehensible error messages when our SQL trips a constraint violation.
  2. Name your constraints consistently. HISTORY_T has constraints called historys_T_FK and fk_order_id_orders, neither of which is helpful. A useful convention is <child_table>_<parent_table>_fk. So history_customer_fk and history_order_fk respectively.
  3. It can be useful to create the constraints with separate statements. Creating tables then primary keys then foreign keys will avoid the problems with dependency ordering identified above.
  4. You are trying to create cyclic foreign keys between LIBRARY_T and FORMATS. You could do this by creating the constraints in separate statement but don't: you will have problems when inserting rows and even worse problems with deletions. You should reconsider your data model and find a way to model the relationship between the two tables so that one is the parent and the other the child. Or perhaps you need a different kind of relationship, such as an intersection table.
  5. Avoid blank lines in your scripts. Some tools will handle them but some will not. We can configure SQL*Plus to handle them but it's better to avoid the need.
  6. The naming convention of LIBRARY_T is ugly. Try to find a more expressive name which doesn't require a needless suffix to avoid a keyword clash.
  7. T_CUSTOMERS is even uglier, being both inconsistent with your other tables and completely unnecessary, as customers is not a keyword.

Naming things is hard. You wouldn't believe the wrangles I've had about table names over the years. The most important thing is consistency. If I look at a data dictionary and see tables called T_CUSTOMERS and LIBRARY_T my first response would be confusion. Why are these tables named with different conventions? What conceptual difference does this express? So, please, decide on a naming convention and stick to. Make your table names either all singular or all plural. Avoid prefixes and suffixes as much as possible; we already know it's a table, we don't need a T_ or a _TAB.

Adding a new value to an existing ENUM Type

If you are using Postgres 12 you can just run ALTER TYPE ... ADD VALUE inside of transaction (documentation).

If ALTER TYPE ... ADD VALUE (the form that adds a new value to an enum type) is executed inside a transaction block, the new value cannot be used until after the transaction has been committed.

So no hacks needed in migrations.

UPD: here is an example (thanks to Nick for it)

ALTER TYPE enum_type ADD VALUE 'new_value';

How do I get the current time only in JavaScript

_x000D_
_x000D_
const date = Date().slice(16,21);_x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

Why does the jquery change event not trigger when I set the value of a select using val()?

I believe you can manually trigger the change event with trigger():

$("#single").val("Single2").trigger('change');

Though why it doesn't fire automatically, I have no idea.

CSS Box Shadow Bottom Only

Do this:

box-shadow: 0 4px 2px -2px gray;

It's actually much simpler, whatever you set the blur to (3rd value), set the spread (4th value) to the negative of it.

Android - java.lang.SecurityException: Permission Denial: starting Intent

In my case, this error was due to incorrect paths used to specify intents in my preferences xml file after I renamed the project. For instance, where I had:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <Preference
        android:key="pref_edit_recipe_key"
        android:title="Add/Edit Recipe">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.ssimon.olddirectory"
            android:targetClass="com.ssimon.olddirectory.RecipeEditActivity"/>
    </Preference>
</PreferenceScreen> 

I needed the following instead:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <Preference
        android:key="pref_edit_recipe_key"
        android:title="Add/Edit Recipe">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.ssimon.newdirectory"
            android:targetClass="com.ssimon.newdirectory.RecipeEditActivity"/>
</Preference>

Correcting the path names fixed the problem.

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

Selecting rows where remainder (modulo) is 1 after division by 2?

Note: Disregard this answer, as I must have misunderstood the question.

select *
  from Table
  where len(ColName) mod 2 = 1

The exact syntax depends on what flavor of SQL you're using.

Link error "undefined reference to `__gxx_personality_v0'" and g++

It sounds like you're trying to link with your resulting object file with gcc instead of g++:

Note that programs using C++ object files must always be linked with g++, in order to supply the appropriate C++ libraries. Attempting to link a C++ object file with the C compiler gcc will cause "undefined reference" errors for C++ standard library functions:

$ g++ -Wall -c hello.cc
$ gcc hello.o       (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
  undefined reference to `__gxx_personality_v0'

Source: An Introduction to GCC - for the GNU compilers gcc and g++

npm install vs. update - what's the difference?

npm update: install and update with latest node modules which are in package.json

npm install: install node modules which are defined in package.json(without update)

json call with C#

Here's a variation of Shiv Kumar's answer, using Newtonsoft.Json (aka Json.NET):

public static bool SendAnSMSMessage(string message)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
    httpWebRequest.ContentType = "text/json";
    httpWebRequest.Method = "POST";

    var serializer = new Newtonsoft.Json.JsonSerializer();
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
        {
             serializer.Serialize(tw, 
                 new {method= "send",
                      @params = new string[]{
                          "IPutAGuidHere", 
                          "[email protected]",
                          "MyTenDigitNumberWasHere",
                          message
                      }});
        }
    }
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
        //Now you have your response.
        //or false depending on information in the response
        return true;        
    }
}

Why is my JavaScript function sometimes "not defined"?

This doesn't solve your original problem, but you could always replace the call to copyArray() with:

__args = Array.prototype.slice.call(arguments);

More information available from Google.

I've tested the above in the following browsers: IE6, 7 & 8B2, Firefox 2.0.0.17 & 3.0.3, Opera 9.52, Safari for Windows 3.1.2 and Google Chrome (whatever the latest version was at the time of this post) and it works across all browsers.

Can you split/explode a field in a MySQL query?

MySQL's only string-splitting function is SUBSTRING_INDEX(str, delim, count). You can use this, to, for example:

  • Return the item before the first separator in a string:

    mysql> SELECT SUBSTRING_INDEX('foo#bar#baz#qux', '#', 1);
    +--------------------------------------------+
    | SUBSTRING_INDEX('foo#bar#baz#qux', '#', 1) |
    +--------------------------------------------+
    | foo                                        |
    +--------------------------------------------+
    1 row in set (0.00 sec)
    
  • Return the item after the last separator in a string:

    mysql> SELECT SUBSTRING_INDEX('foo#bar#baz#qux', '#', -1);
    +---------------------------------------------+
    | SUBSTRING_INDEX('foo#bar#baz#qux', '#', -1) |
    +---------------------------------------------+
    | qux                                         |
    +---------------------------------------------+
    1 row in set (0.00 sec)
    
  • Return everything before the third separator in a string:

    mysql> SELECT SUBSTRING_INDEX('foo#bar#baz#qux', '#', 3);
    +--------------------------------------------+
    | SUBSTRING_INDEX('foo#bar#baz#qux', '#', 3) |
    +--------------------------------------------+
    | foo#bar#baz                                |
    +--------------------------------------------+
    1 row in set (0.00 sec)
    
  • Return the second item in a string, by chaining two calls:

    mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('foo#bar#baz#qux', '#', 2), '#', -1);
    +----------------------------------------------------------------------+
    | SUBSTRING_INDEX(SUBSTRING_INDEX('foo#bar#baz#qux', '#', 2), '#', -1) |
    +----------------------------------------------------------------------+
    | bar                                                                  |
    +----------------------------------------------------------------------+
    1 row in set (0.00 sec)
    

In general, a simple way to get the nth element of a #-separated string (assuming that you know it definitely has at least n elements) is to do:

SUBSTRING_INDEX(SUBSTRING_INDEX(your_string, '#', n), '#', -1);

The inner SUBSTRING_INDEX call discards the nth separator and everything after it, and then the outer SUBSTRING_INDEX call discards everything except the final element that remains.

If you want a more robust solution that returns NULL if you ask for an element that doesn't exist (for instance, asking for the 5th element of 'a#b#c#d'), then you can count the delimiters using REPLACE and then conditionally return NULL using IF():

IF(
    LENGTH(your_string) - LENGTH(REPLACE(your_string, '#', '')) / LENGTH('#') < n - 1,
    NULL,
    SUBSTRING_INDEX(SUBSTRING_INDEX(your_string, '#', n), '#', -1)
)

Of course, this is pretty ugly and hard to understand! So you might want to wrap it in a function:

CREATE FUNCTION split(string TEXT, delimiter TEXT, n INT)
RETURNS TEXT DETERMINISTIC
RETURN IF(
    (LENGTH(string) - LENGTH(REPLACE(string, delimiter, ''))) / LENGTH(delimiter) < n - 1,
    NULL,
    SUBSTRING_INDEX(SUBSTRING_INDEX(string, delimiter, n), delimiter, -1)
);

You can then use the function like this:

mysql> SELECT SPLIT('foo,bar,baz,qux', ',', 3);
+----------------------------------+
| SPLIT('foo,bar,baz,qux', ',', 3) |
+----------------------------------+
| baz                              |
+----------------------------------+
1 row in set (0.00 sec)

mysql> SELECT SPLIT('foo,bar,baz,qux', ',', 5);
+----------------------------------+
| SPLIT('foo,bar,baz,qux', ',', 5) |
+----------------------------------+
| NULL                             |
+----------------------------------+
1 row in set (0.00 sec)

mysql> SELECT SPLIT('foo###bar###baz###qux', '###', 2);
+------------------------------------------+
| SPLIT('foo###bar###baz###qux', '###', 2) |
+------------------------------------------+
| bar                                      |
+------------------------------------------+
1 row in set (0.00 sec)

How to display raw html code in PRE or something like it but without escaping it

Essentially the original question can be broken down in 2 parts:

  • Main objective/challenge: embedding(/transporting) a raw formatted code-snippet (any kind of code) in a web-page's markup (for simple copy/paste/edit due to no encoding/escaping)
  • correctly displaying/rendering that code-snippet (possibly edit it) in the browser

The short (but) ambiguous answer is: you can't, ...but you can (get very close).
(I know, that are 3 contradicting answers, so read on...)

(polyglot)(x)(ht)ml Markup-languages rely on wrapping (almost) everything between begin/opening and end/closing tags/character(sequences).
So, to embed any kind of raw code/snippet inside your markup-language, one will always have to escape/encode every instance (inside that snippet) that resembles the character(-sequence) that would close the wrapping 'container' element in the markup. (During this post I'll refer to this as rule no 1.)
Think of "some "data" here" or <i>..close italics with '</i>'-tag</i>, where it is obvious one should escape/encode (something in) </i and " (or change container's quote-character from " to ').

So, because of rule no 1, you can't 'just' embed 'any' unknown raw code-snippet inside markup.
Because, if one has to escape/encode even one character inside the raw snippet, then that snippet would no longer be the same original 'pure raw code' that anyone can copy/paste/edit in the document's markup without further thought. It would lead to malformed/illegal markup and Mojibake (mainly) because of entities.
Also, should that snippet contain such characters, you'd still need some javascript to 'translate' that character(sequence) from (and to) it's escaped/encoded representation to display the snippet correctly in the 'webpage' (for copy/paste/edit).

That brings us to (some of) the datatypes that markup-languages specify. These datatypes essentially define what are considered 'valid characters' and their meaning (per tag, property, etc.):

  • PCDATA (Parsed Character DATA): will expand entities and one must escape <, & (and > depending on markup language/version).
    Most tags like body, div, pre, etc, but also textarea (until HTML5) fall under this type.
    So not only do you need to encode all the container's closing character-sequences inside the snippet, you also have to encode all <, & (,>) characters (at minimum).
    Needless to say, encoding/escaping this many characters falls outside this objective's scope of embedding a raw snippet in the markup.
    '..But a textarea seems to work...', yes, either because of the browsers error-engine trying to make something out of it, or because HTML5:

  • RCDATA (Replaceable Character DATA): will not not treat tags inside the text as markup (but are still governed by rule 1), so one doesn't need to encode < (>). BUT entities are still expanded, so they and 'ambiguous ampersands' (&) need special care.
    The current HTML5 spec says the textarea is now a RCDATA field and (quote):

    The text in raw text and RCDATA elements must not contain any occurrences of the string "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

    Thus no matter what, textarea needs a hefty entity translation handler or it will eventually Mojibake on entities!

  • CDATA (Character Data) will not treat tags inside the text as markup and will not expand entities.
    So as long as the raw snippet code does not violate rule 1 (that one can't have the containers closing character(sequence) inside the snippet), this requires no other escaping/encoding.

Clearly this boils down to: how can we minimize the number of characters/character-sequences that still need to be encoded in the snippet's raw source and the number of times that character(sequence) might appear in an average snippet; something that is also of importance for the javascript that handles the translation of these characters (if they occur).

So what 'containers' have this CDATA context?

Most value properties of tags are CDATA, so one could (ab)use a hidden input's value property (proof of concept jsfiddle here).
However (conform rule 1) this creates an encoding/escape problem with nested quotes (" and ') in the raw snippet and one needs some javascript to get/translate and set the snippet in another (visible) element (or simply setting it as a text-area's value). Somehow this gave me problems with entities in FF (just like in a textarea). But it doesn't really matter, since the 'price' of having to escape/encode nested quotes is higher then a (HTML5) textarea (quotes are quite common in source code..).

What about trying to (ab)use <![CDATA[<tag>bla & bla</tag>]]>?
As Jukka points out in his extended answer, this would only work in (rare) 'real xhtml'.
I thought of using a script-tag (with or without such a CDATA wrapper inside the script-tag) together with a multi-line comment /* */ that wraps the raw snippet (script-tags can have an id and you can access them by count). But since this obviously introduces a escaping problem with */, ]]> and </script in the raw snippet, this doesn't seem like a solution either.

Please post other viable 'containers' in the comments to this answer.

By the way, encoding or counting the number of - characters and balancing them out inside a comment tag <!-- --> is just insane for this purpose (apart from rule 1).


That leaves us with Jukka K. Korpela's excellent answer: the <xmp> tag seems the best option!

The 'forgotten' <xmp> holds CDATA, is intended for this purpose AND is indeed still in the current HTML 5 spec (and has been at least since HTML3.2); exactly what we need! It's also widely supported, even in IE6 (that is.. until it suffers from the same regression as the scrolling table-body).
Note: as Jukka pointed out, this will not work in true xhtml or polyglot (that will treat it as a pre) and the xmp tag must still adhere to rule no 1. But that's the 'only' rule.

Consider the following markup:

<!-- ATTENTION: replace any occurrence of &lt;/xmp with </xmp -->
<xmp id="snippet-container">
<div>
    <div>this is an example div &amp; holds an xmp tag:<br />
        <xmp> 
<html><head>  <!-- indentation col 0!! -->
    <title>My Title</title>
</head><body>
    <p>hello world !!</p>
</body></html>
        &lt;/xmp>  <!-- note this encoded/escaped tag -->
    </div>
    This line is also part of the snippet
</div>
</xmp>

The above codeblok illustrates a raw piece of markup where <xmp id="snippet-container"> contains an (almost raw) code-snippet (containing div>div>xmp>html-document).
Notice the encoded closing tag in this markup? To comply with rule no 1, this was encoded/escaped).

So embedding/transporting the (sometimes almost) raw code is/seems solved.

What about displaying/rendering the snippet (and that encoded &lt;/xmp>)?

The browser will (or it should) render the snippet (the contents inside snippet-container) exactly the way you see it in the codeblock above (with some discrepancy amongst browsers whether or not the snippet starts with a blank line).
That includes the formatting/indentation, entities (like the string &amp;), full tags, comments AND the encoded closing tag &lt;/xmp> (just like it was encoded in the markup). And depending on browser(version) one could even try use the property contenteditable="true" to edit this snippet (all that without javascript enabled). Doing something like textarea.value=xmp.innerHTML is also a breeze.

So you can... if the snippet doesn't contain the containers closing character-sequence.

However, should a raw snippet contain the closing character-sequence </xmp (because it is an example of xmp itself or it contains some regex, etc), you must accept that you have to encode/escape that sequence in the raw snippet AND need a javascript handler to translate that encoding to display/render the encoded &lt;/xmp> like </xmp> inside a textarea (for editing/posting) or (for example) a pre just to correctly render the snippet's code (or so it seems).

A very rudimentary jsfiddle example of this here. Note that getting/embedding/displaying/retrieving-to-textarea worked perfect even in IE6. But setting the xmp's innerHTML revealed some interesting 'would-be-intelligent' behavior on IE's part. There is a more extensive note and workaround on that in the fiddle.

But now comes the important kicker (another reason why you only get very close): Just as an over-simplified example, imagine this rabbit-hole:

Intended raw code-snippet:

<!-- remember to translate between </xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Well, to comply with rule 1, we 'only' need to encode those </xmp[> \n\r\t\f\/] sequences, right?

So that gives us the following markup (using just a possible encoding):

<xmp id="container">
<!-- remember to translate between &lt;/xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
&lt;/xmp>
</xmp>

Hmm.. shalt I get my crystal ball or flip a coin? No, let the computer look at its system-clock and state that a derived number is 'random'. Yes, that should do it..

Using a regex like: xmp.innerHTML.replace(/&lt;(?=\/xmp[> \n\r\t\f\/])/gi, '<');, would translate 'back' to this:

<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Hmm.. seems this random generator is broken... Houston..?
Should you have missed the joke/problem, read again starting at the 'intended raw code-snippet'.

Wait, I know, we (also) need to encode .... to ....
Ok, rewind to 'intended raw code-snippet' and read again.
Somehow this all begins to smell like the famous hilarious-but-true rexgex-answer on SO, a good read for people fluent in mojibake.

Maybe someone knows a clever algorithm or solution to fix this problem, but I assume that the embedded raw code will get more and more obscure to the point where you'd be better of properly escaping/encoding just your <, & (and >), just like the rest of the world.

Conclusion: (using the xmp tag)

  • it can be done with known snippets that do not contain the container's closing character-sequence,
  • we can get very close to the original objective with known snippets that only use 'basic first-level' escaping/encoding so we don't fall in the rabbithole,
  • but ultimately it seems that one can't do this reliably in a 'production-environment' where people can/should copy/paste/edit 'any unknown' raw snippets while not knowing/understanding the implications/rules/rabbithole (depending on your implementation of handling/translating for rule 1 and the rabbit-hole).

Hope this helps!

PS: Whilst I would appreciate an upvote if you find this explanation useful, I kind of think Jukka's answer should be the accepted answer (should no better option/answer come along), since he was the one who remembered the xmp tag (that I forgot about over the years and got 'distracted' by the commonly advocated PCDATA elements like pre, textarea, etc.).
This answer originated in explaining why you can't do it (with any unknown raw snippet) and explain some obvious pitfalls that some other (now deleted) answers overlooked when advising a textarea for embedding/transport. I've expanded my existing explanation to also support and further explain Jukka's answer (since all that entity and *CDATA stuff is almost harder than code-pages).

Handle ModelState Validation in ASP.NET Web API

I had an issue implementing the accepted solution pattern where my ModelStateFilter would always return false (and subsequently a 400) for actionContext.ModelState.IsValid for certain model objects:

public class ModelStateFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest};
        }
    }
}

I only accept JSON, so I implemented a custom model binder class:

public class AddressModelBinder : System.Web.Http.ModelBinding.IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        var posted = actionContext.Request.Content.ReadAsStringAsync().Result;
        AddressDTO address = JsonConvert.DeserializeObject<AddressDTO>(posted);
        if (address != null)
        {
            // moar val here
            bindingContext.Model = address;
            return true;
        }
        return false;
    }
}

Which I register directly after my model via

config.BindParameter(typeof(AddressDTO), new AddressModelBinder());

How to get the Mongo database specified in connection string in C#

Update:

MongoServer.Create is obsolete now (thanks to @aknuds1). Instead this use following code:

var _server = new MongoClient(connectionString).GetServer();

It's easy. You should first take database name from connection string and then get database by name. Complete example:

var connectionString = "mongodb://localhost:27020/mydb";

//take database name from connection string
var _databaseName = MongoUrl.Create(connectionString).DatabaseName;
var _server = MongoServer.Create(connectionString);

//and then get database by database name:
_server.GetDatabase(_databaseName);

Important: If your database and auth database are different, you can add a authSource= query parameter to specify a different auth database. (thank you to @chrisdrobison)

From docs:

NOTE If you are using the database segment as the initial database to use, but the username and password specified are defined in a different database, you can use the authSource option to specify the database in which the credential is defined. For example, mongodb://user:pass@hostname/db1?authSource=userDb would authenticate the credential against the userDb database instead of db1.

how to read a text file using scanner in Java?

Well.. Apparently the file does not exist or cannot be found. Try using a full path. You're probably reading from the wrong directory when you don't specify the path, unless a.txt is in your current working directory.

SQL How to correctly set a date variable value and use it?

Your syntax is fine, it will return rows where LastAdDate lies within the last 6 months;

select cast('01-jan-1970' as datetime) as LastAdDate into #PubAdvTransData 
    union select GETDATE()
    union select NULL
    union select '01-feb-2010'

DECLARE @sp_Date DATETIME = DateAdd(m, -6, GETDATE())

SELECT * FROM #PubAdvTransData pat
     WHERE (pat.LastAdDate > @sp_Date)

>2010-02-01 00:00:00.000
>2010-04-29 21:12:29.920

Are you sure LastAdDate is of type DATETIME?

How to check if a database exists in SQL Server?

Actually it's best to use:

IF DB_ID('dms') IS NOT NULL
   --code mine :)
   print 'db exists'

See https://docs.microsoft.com/en-us/sql/t-sql/functions/db-id-transact-sql and note that this does not make sense with the Azure SQL Database.

Using arrays or std::vectors in C++, what's the performance gap?

If you're using vectors to represent multi-dimensional behavior, there is a performance hit.

Do 2d+ vectors cause a performance hit?

The gist is that there's a small amount of overhead with each sub-vector having size information, and there will not necessarily be serialization of data (as there is with multi-dimensional c arrays). This lack of serialization can offer greater than micro optimization opportunities. If you're doing multi-dimensional arrays, it may be best to just extend std::vector and roll your own get/set/resize bits function.

Group query results by month and year in postgresql

bma answer is great! I have used it with ActiveRecords, here it is if anybody needs it in Rails:

Model.find_by_sql(
  "SELECT TO_CHAR(created_at, 'Mon') AS month,
   EXTRACT(year from created_at) as year,
   SUM(desired_value) as desired_value
   FROM desired_table
   GROUP BY 1,2
   ORDER BY 1,2"
)

Create a List that contain each Line of a File

A file is almost a list of lines. You can trivially use it in a for loop.

myFile= open( "SomeFile.txt", "r" )
for x in myFile:
    print x
myFile.close()

Or, if you want an actual list of lines, simply create a list from the file.

myFile= open( "SomeFile.txt", "r" )
myLines = list( myFile )
myFile.close()
print len(myLines), myLines

You can't do someList[i] to put a new item at the end of a list. You must do someList.append(i).

Also, never start a simple variable name with an uppercase letter. List confuses folks who know Python.

Also, never use a built-in name as a variable. list is an existing data type, and using it as a variable confuses folks who know Python.

ISO C90 forbids mixed declarations and code in C

I think you should move the variable declaration to top of block. I.e.

{
    foo();
    int i = 0;
    bar();
}

to

{
    int i = 0;
    foo();
    bar();
}

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

I'm not sure about HQL, but in JPA you just call the query's setParameter with the parameter and collection.

Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)");
q.setParameter("names", names);

where names is the collection of names you're searching for

Collection<String> names = new ArrayList<String();
names.add("Joe");
names.add("Jane");
names.add("Bob");

Reading the selected value from asp:RadioButtonList using jQuery

Why so complex?

$('#id:checked').val();

Will work just fine!

How to host google web fonts on my own server?

As you want to host all fonts (or some of them) at your own server, you a download fonts from this repo and use it the way you want: https://github.com/praisedpk/Local-Google-Fonts

If you just want to do this to fix the leverage browser caching issue that comes with Google Fonts, you can use alternative fonts CDN, and include fonts as:

<link href="https://pagecdn.io/lib/easyfonts/fonts.css" rel="stylesheet" />

Or a specific font, as:

<link href="https://pagecdn.io/lib/easyfonts/lato.css" rel="stylesheet" />

How to manually force a commit in a @Transactional method?

Why don't you use spring's TransactionTemplate to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional method, but given that it's a test I would opt for programmatic control of your transactions.

Also note that the @Transactional annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!

@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {

@Autowired
PlatformTransactionManager platformTransactionManager;

TransactionTemplate transactionTemplate;

@Before
public void setUp() throws Exception {
    transactionTemplate = new TransactionTemplate(platformTransactionManager);
}

@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {

    final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
        @Override
        public Contract doInTransaction(TransactionStatus status) {
            Contract c = contractDOD.getNewTransientContract(15);
            contractRepository.save(c);
            return c;
        }
    });

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    for (int i = 0; i < 5; ++i) {
        executorService.execute(new Runnable() {
            @Override  //note that there is no @Transactional configured for the method
            public void run() {
                transactionTemplate.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus status) {
                        // do whatever you want to do with c1
                        return null;
                    }
                });
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            // validate test results in transaction
            return null;
        }
    });
}

}

Logging levels - Logback - rule-of-thumb to assign log levels

I mostly build large scale, high availability type systems, so my answer is biased towards looking at it from a production support standpoint; that said, we assign roughly as follows:

  • error: the system is in distress, customers are probably being affected (or will soon be) and the fix probably requires human intervention. The "2AM rule" applies here- if you're on call, do you want to be woken up at 2AM if this condition happens? If yes, then log it as "error".

  • warn: an unexpected technical or business event happened, customers may be affected, but probably no immediate human intervention is required. On call people won't be called immediately, but support personnel will want to review these issues asap to understand what the impact is. Basically any issue that needs to be tracked but may not require immediate intervention.

  • info: things we want to see at high volume in case we need to forensically analyze an issue. System lifecycle events (system start, stop) go here. "Session" lifecycle events (login, logout, etc.) go here. Significant boundary events should be considered as well (e.g. database calls, remote API calls). Typical business exceptions can go here (e.g. login failed due to bad credentials). Any other event you think you'll need to see in production at high volume goes here.

  • debug: just about everything that doesn't make the "info" cut... any message that is helpful in tracking the flow through the system and isolating issues, especially during the development and QA phases. We use "debug" level logs for entry/exit of most non-trivial methods and marking interesting events and decision points inside methods.

  • trace: we don't use this often, but this would be for extremely detailed and potentially high volume logs that you don't typically want enabled even during normal development. Examples include dumping a full object hierarchy, logging some state during every iteration of a large loop, etc.

As or more important than choosing the right log levels is ensuring that the logs are meaningful and have the needed context. For example, you'll almost always want to include the thread ID in the logs so you can follow a single thread if needed. You may also want to employ a mechanism to associate business info (e.g. user ID) to the thread so it gets logged as well. In your log message, you'll want to include enough info to ensure the message can be actionable. A log like " FileNotFound exception caught" is not very helpful. A better message is "FileNotFound exception caught while attempting to open config file: /usr/local/app/somefile.txt. userId=12344."

There are also a number of good logging guides out there... for example, here's an edited snippet from JCL (Jakarta Commons Logging):

  • error - Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
  • warn - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
  • info - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
  • debug - detailed information on the flow through the system. Expect these to be written to logs only.
  • trace - more detailed information. Expect these to be written to logs only.

Put search icon near textbox using bootstrap

I liked @KyleMit's answer on how to make an unstyled input group, but in my case, I only wanted the right side unstyled - I still wanted to use an input-group-addon on the left side and have it look like normal bootstrap. So, I did this:

css

.input-group.input-group-unstyled-right input.form-control {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}
.input-group-unstyled-right .input-group-addon.input-group-addon-unstyled {
    border-radius: 4px;
    border: 0px;
    background-color: transparent;
}

html

<div class="input-group input-group-unstyled-right">
    <span class="input-group-addon">
        <i class="fa fa-envelope-o"></i>
    </span>
    <input type="text" class="form-control">
    <span class="input-group-addon input-group-addon-unstyled">
        <i class="fa fa-check"></i>
    </span>
</div>

XAMPP: Couldn't start Apache (Windows 10)

  1. Press Windows+R, and type regedit.

  2. Go to

     HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP
    

    Change the value of Start to 4, which means disabled.

  3. Reboot your computer.

How to install python-dateutil on Windows?

You could also change your PYTHONPATH:

$ python -c 'import dateutil'
   Traceback (most recent call last):
     File "<string>", line 1, in <module>
   ImportError: No module named dateutil
$
$ PYTHONPATH="/usr/lib/python2.6/site-packages/python_dateutil-1.5-py2.6.egg":"${PYTHONPATH}"
$ export PYTHONPATH
$ python -c 'import dateutil'
$

Where /usr/lib/python2.6/site-packages/python_dateutil-1.5-py2.6.egg is the place dateutil was installed in my box (centos using sudo yum install python-dateutil15)

How to retrieve all keys (or values) from a std::map and put them into a vector?

I think the BOOST_FOREACH presented above is nice and clean, however, there is another option using BOOST as well.

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

std::map<int, int> m;
std::vector<int> keys;

using namespace boost::lambda;

transform(      m.begin(), 
                m.end(), 
                back_inserter(keys), 
                bind( &std::map<int,int>::value_type::first, _1 ) 
          );

copy( keys.begin(), keys.end(), std::ostream_iterator<int>(std::cout, "\n") );

Personally, I don't think this approach is as clean as the BOOST_FOREACH approach in this case, but boost::lambda can be really clean in other cases.

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

If you are using variables with the same name as your column, it could be that you forgot the '@' variable marker. In an INSERT statement it will be detected as a column.

Ignoring SSL certificate in Apache HttpClient 4.3

One small addition to the answer by vasekt:

The provided solution with the SocketFactoryRegistry works when using PoolingHttpClientConnectionManager.

However, connections via plain http don't work any longer then. You have to add a PlainConnectionSocketFactory for the http protocol additionally to make them work again:

Registry<ConnectionSocketFactory> socketFactoryRegistry = 
  RegistryBuilder.<ConnectionSocketFactory> create()
  .register("https", sslsf)
  .register("http", new PlainConnectionSocketFactory()).build();

Read a text file line by line in Qt

Since Qt 5.5 you can use QTextStream::readLineInto. It behaves similar to std::getline and is maybe faster as QTextStream::readLine, because it reuses the string:

QIODevice* device;
QTextStream in(&device);

QString line;
while (in.readLineInto(&line)) {
  // ...
}

How do I output coloured text to a Linux terminal?

As others have stated, you can use escape characters. You can use my header in order to make it easier:

#ifndef _COLORS_
#define _COLORS_

/* FOREGROUND */
#define RST  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST

#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST

#endif  /* _COLORS_ */

An example using the macros of the header could be:

#include <iostream>
#include "colors.h"
using namespace std;

int main()
{
    cout << FBLU("I'm blue.") << endl;
    cout << BOLD(FBLU("I'm blue-bold.")) << endl;
    return 0;
}

enter image description here

No mapping found for HTTP request with URI Spring MVC

First check whether the java classes are compiled or not in your [PROJECT_NAME]\target\classes directory.

If not you have some compilation errors in your java classes.

How can I extract audio from video with ffmpeg?

If the audio wrapped into the avi is not mp3-format to start with, you may need to specify -acodec mp3 as an additional parameter. Or whatever your mp3 codec is (on Linux systems its probably -acodec libmp3lame). You may also get the same effect, platform-agnostic, by instead specifying -f mp3 to "force" the format to mp3, although not all versions of ffmpeg still support that switch. Your Mileage May Vary.

Search for executable files using find command

Well the easy answer would be: "your executable files are in the directories contained in your PATH variable" but that would not really find your executables and could miss a lot of executables anyway.

I don't know much about mac but I think "mdfind 'kMDItemContentType=public.unix-executable'" might miss stuff like interpreted scripts

If it's ok for you to find files with the executable bits set (regardless of whether they are actually executable) then it's fine to do

find . -type f -perm +111 -print

where supported the "-executable" option will make a further filter looking at acl and other permission artifacts but is technically not much different to "-pemr +111".

Maybe in the future find will support "-magic " and let you look explicitly for files with a specific magic id ... but then you would haveto specify to fine all the executable formats magic id.

I'm unaware of a technically correct easy way out on unix.

7-zip commandline

7-Zip wants relative paths in the list file otherwise it will store only the filenames, causing duplicate file name error.

Assuming that your list contains full path names:

  • Edit the list file to remove drive prefix, C:\
  • Make sure you are in the root of the drive when you run 7Z to use the above list file.
  • Then it will store the paths and won't complain of the duplicate name. It wants relative paths in the list file.

If your list file has paths relative to another folder, you should be running 7Z from that folder.

Update: I noticed from another post above that the new 7-Zip has an -spf option that doesn't require the above steps. Not tested it yet but my steps are for earlier versions that do not have this option.

How to repeat last command in python interpreter shell?

Ipython isn't allways the way... I like it pretty much, but if you try run Django shell with ipython. Something like>>>

ipython manage.py shell

it does'n work correctly if you use virtualenv. Django needs some special includes which aren't there if you start ipython, because it starts default system python, but not that virtual.

How to load GIF image in Swift?

//
//  iOSDevCenters+GIF.swift
//  GIF-Swift
//
//  Created by iOSDevCenters on 11/12/15.
//  Copyright © 2016 iOSDevCenters. All rights reserved.
//
import UIKit
import ImageIO


extension UIImage {

public class func gifImageWithData(data: NSData) -> UIImage? {
    guard let source = CGImageSourceCreateWithData(data, nil) else {
        print("image doesn't exist")
        return nil
    }

    return UIImage.animatedImageWithSource(source: source)
}

public class func gifImageWithURL(gifUrl:String) -> UIImage? {
    guard let bundleURL = NSURL(string: gifUrl)
        else {
            print("image named \"\(gifUrl)\" doesn't exist")
            return nil
    }
    guard let imageData = NSData(contentsOf: bundleURL as URL) else {
        print("image named \"\(gifUrl)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

public class func gifImageWithName(name: String) -> UIImage? {
    guard let bundleURL = Bundle.main
        .url(forResource: name, withExtension: "gif") else {
            print("SwiftGif: This image named \"\(name)\" does not exist")
            return nil
    }

    guard let imageData = NSData(contentsOf: bundleURL) else {
        print("SwiftGif: Cannot turn image named \"\(name)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

class func delayForImageAtIndex(index: Int, source: CGImageSource!) -> Double {
    var delay = 0.1

    let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
    let gifProperties: CFDictionary = unsafeBitCast(CFDictionaryGetValue(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()), to: CFDictionary.self)

    var delayObject: AnyObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self)

    if delayObject.doubleValue == 0 {
        delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
    }

    delay = delayObject as! Double

    if delay < 0.1 {
        delay = 0.1
    }

    return delay
}

class func gcdForPair(a: Int?, _ b: Int?) -> Int {
    var a = a
    var b = b
    if b == nil || a == nil {
        if b != nil {
            return b!
        } else if a != nil {
            return a!
        } else {
            return 0
        }
    }

    if a! < b! {
        let c = a!
        a = b!
        b = c
    }

    var rest: Int
    while true {
        rest = a! % b!

        if rest == 0 {
            return b!
        } else {
            a = b!
            b = rest
        }
    }
}

class func gcdForArray(array: Array<Int>) -> Int {
    if array.isEmpty {
        return 1
    }

    var gcd = array[0]

    for val in array {
        gcd = UIImage.gcdForPair(a: val, gcd)
    }

    return gcd
}

class func animatedImageWithSource(source: CGImageSource) -> UIImage? {
    let count = CGImageSourceGetCount(source)
    var images = [CGImage]()
    var delays = [Int]()

    for i in 0..<count {
        if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
            images.append(image)
        }

        let delaySeconds = UIImage.delayForImageAtIndex(index: Int(i), source: source)
        delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
    }

    let duration: Int = {
        var sum = 0

        for val: Int in delays {
            sum += val
        }

        return sum
    }()

    let gcd = gcdForArray(array: delays)
    var frames = [UIImage]()

    var frame: UIImage
    var frameCount: Int
    for i in 0..<count {
        frame = UIImage(cgImage: images[Int(i)])
        frameCount = Int(delays[Int(i)] / gcd)

        for _ in 0..<frameCount {
            frames.append(frame)
        }
    }

    let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0)

    return animation
}
}

Here is the file updated for Swift 3

jquery $(window).height() is returning the document height

With no doctype tag, Chrome reports the same value for both calls.

Adding a strict doctype like <!DOCTYPE html> causes the values to work as advertised.

The doctype tag must be the very first thing in your document. E.g., you can't have any text before it, even if it doesn't render anything.

JavaFX How to set scene background image

I know this is an old Question

But in case you want to do it programmatically or the java way

For Image Backgrounds; you can use BackgroundImage class

BackgroundImage myBI= new BackgroundImage(new Image("my url",32,32,false,true),
        BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
          BackgroundSize.DEFAULT);
//then you set to your node
myContainer.setBackground(new Background(myBI));

For Paint or Fill Backgrounds; you can use BackgroundFill class

BackgroundFill myBF = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1),
         new Insets(0.0,0.0,0.0,0.0));// or null for the padding
//then you set to your node or container or layout
myContainer.setBackground(new Background(myBF));

Keeps your java alive && your css dead..

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

How to check if a std::string is set or not?

As several answers pointed out, std::string has no concept of 'nullness' for its value. If using the empty string as such a value isn't good enough (ie., you need to distinguish between a string that has no characters and a string that has no value), you can use a std::string* and set it to NULL or to a valid std::string instance as appropriate.

You may want to use some sort of smart pointer type (boost::scoped_ptr or something) to help manage the lifetime of any std::string object that you set the pointer to.

How to make an element in XML schema optional?

Try this

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />

if you want 0 or 1 "description" elements, Or

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />

if you want 0 to infinity number of "description" elements.

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

I found a more generic solution with the most angular-native solution I can think. Basically you can pass your own comparator to the default filterFilter function. Here's plunker as well.

Using Bootstrap Modal window as PartialView

Complete and clear example project http://www.codeproject.com/Articles/786085/ASP-NET-MVC-List-Editor-with-Bootstrap-Modals It displays create, edit and delete entity operation modals with bootstrap and also includes code to handle result returned from those entity operations (c#, JSON, javascript)

How to simulate browsing from various locations?

It depends on wether the locatoin is detected by different DNS resolution from different locations, or by IP address that you are browsing from.

If its by DNS, you could just modify your hosts file to point at the server used in europe. Get your friend to ping the address, to see if its different from the one yours resolves to.

To browse from a different IP address:

You can rent a VPS server. You can use putty / SSH to act as a proxy. I use this from time to time to brows from the US using a VPS server I rent in the US.

Having an account on a remote host may or may not be enough. Sadly, my dreamhost account, even though I have ssh access, does not allow proxying.

How to enable bulk permission in SQL Server

Note that the accepted answer or either of these two solutions work for Windows only.

GRANT ADMINISTER BULK OPERATIONS TO [login_name];
-- OR
ALTER SERVER ROLE [bulkadmin] ADD MEMBER [login_name];

If you run any of them on SQL Server based on a linux machine, you will get these errors:

Msg 16202, Level 15, State 1, Line 1
Keyword or statement option 'bulkadmin' is not supported on the 'Linux' platform.
Msg 16202, Level 15, State 3, Line 1
Keyword or statement option 'ADMINISTER BULK OPERATIONS' is not supported on the 'Linux' platform.

Check the docs.

Requires INSERT and ADMINISTER BULK OPERATIONS permissions. In Azure SQL Database, INSERT and ADMINISTER DATABASE BULK OPERATIONS permissions are required. ADMINISTER BULK OPERATIONS permissions or the bulkadmin role is not supported for SQL Server on Linux. Only the sysadmin can perform bulk inserts for SQL Server on Linux.

Solution for Linux

ALTER SERVER ROLE [sysadmin] ADD MEMBER [login_name];

jQuery - Create hidden form element on the fly

$('<input>').attr('type','hidden').appendTo('form');

To answer your second question:

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'bar'
}).appendTo('form');

Assign result of dynamic sql to variable

You could use sp_executesql instead of exec. That allows you to specify an output parameter.

declare @out_var varchar(max);
execute sp_executesql 
    N'select @out_var = ''hello world''', 
    N'@out_var varchar(max) OUTPUT', 
    @out_var = @out_var output;
select @out_var;

This prints "hello world".

How to check encoding of a CSV file

You can also use python chardet library

# install the chardet library
!pip install chardet

# import the chardet library
import chardet 

# use the detect method to find the encoding
# 'rb' means read in the file as binary
with open("test.csv", 'rb') as file:
    print(chardet.detect(file.read()))

Read all worksheets in an Excel workbook into an R list with data.frames

excel.link will do the job.

I actually found it easier to use compared to XLConnect (not that either package is that difficult to use). Learning curve for both was about 5 minutes.

As an aside, you can easily find all R packages that mention the word "Excel" by browsing to http://cran.r-project.org/web/packages/available_packages_by_name.html

Find the version of an installed npm package

This is simple question, and should have a simpler answer than what I see above.

To see the installed npm packages with their version, the command is npm ls --depth=0, which, by default, displays what is installed locally. To see the globally installed packages, add the -global argument: npm ls --depth=0 -global.

--depth=0 returns a list of installed packages without their dependencies, which is what you're wanting to do most of the time.

ls is the name of the command, and list is an alias for ls.

How to obtain the start time and end time of a day?

Java 8


public static Date atStartOfDay(Date date) {
    LocalDateTime localDateTime = dateToLocalDateTime(date);
    LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
    return localDateTimeToDate(startOfDay);
}

public static Date atEndOfDay(Date date) {
    LocalDateTime localDateTime = dateToLocalDateTime(date);
    LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
    return localDateTimeToDate(endOfDay);
}

private static LocalDateTime dateToLocalDateTime(Date date) {
    return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}

private static Date localDateTimeToDate(LocalDateTime localDateTime) {
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}

Update: I've added these 2 methods to my Java Utility Classes here

It is in the Maven Central Repository at:

<dependency>
  <groupId>com.github.rkumsher</groupId>
  <artifactId>utils</artifactId>
  <version>1.3</version>
</dependency>

Java 7 and Earlier


With Apache Commons

public static Date atEndOfDay(Date date) {
    return DateUtils.addMilliseconds(DateUtils.ceiling(date, Calendar.DATE), -1);
}

public static Date atStartOfDay(Date date) {
    return DateUtils.truncate(date, Calendar.DATE);
}

Without Apache Commons

public Date atEndOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    return calendar.getTime();
}

public Date atStartOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

Database design for a survey

I think that your model #2 is fine, however you can take a look at the more complex model which stores questions and pre-made answers (offered answers) and allows them to be re-used in different surveys.

- One survey can have many questions; one question can be (re)used in many surveys.
- One (pre-made) answer can be offered for many questions. One question can have many answers offered. A question can have different answers offered in different surveys. An answer can be offered to different questions in different surveys. There is a default "Other" answer, if a person chooses other, her answer is recorded into Answer.OtherText.
- One person can participate in many surveys, one person can answer specific question in a survey only once.

survey_model_02

Is it possible to convert char[] to char* in C?

It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.

  • An array char a[SIZE] says that the value at the location of a is an array of length SIZE
  • A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)

In memory, it looks like this (example taken from the FAQ):

 char a[] = "hello";  // array

   +---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
   +---+---+---+---+---+---+

 char *p = "world"; // pointer

   +-----+     +---+---+---+---+---+---+
p: |  *======> | w | o | r | l | d |\0 |
   +-----+     +---+---+---+---+---+---+

It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.

One major practical difference is that the compiler knows how long an array is. Using the examples above:

char a[] = "hello";  
char *p =  "world";  

sizeof(a); // 6 - one byte for each character in the string,
           // one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
           // probably 4 or 8 on most machines (depending on whether it's a 
           // 32 or 64 bit machine)

Without seeing your code, it's hard to recommend the best course of action, but I suspect changing to use pointers everywhere will solve the problems you're currently having. Take note that now:

  • You will need to initialise memory wherever the arrays used to be. Eg, char a[10]; will become char *a = malloc(10 * sizeof(char));, followed by a check that a != NULL. Note that you don't actually need to say sizeof(char) in this case, because sizeof(char) is defined to be 1. I left it in for completeness.

  • Anywhere you previously had sizeof(a) for array length will need to be replaced by the length of the memory you allocated (if you're using strings, you could use strlen(), which counts up to the '\0').

  • You will need a make a corresponding call to free() for each call to malloc(). This tells the computer you are done using the memory you asked for with malloc(). If your pointer is a, just write free(a); at a point in the code where you know you no longer need whatever a points to.

As another answer pointed out, if you want to get the address of the start of an array, you can use:

char* p = &a[0] 

You can read this as "char pointer p becomes the address of element [0] of a".

How to remove a package from Laravel using composer?

If you are still getting the error after you have done with all above steps, go to your projects bootstrap->cache->config.php remove the provider & aliases entries from the cached array manually.

How to redirect from one URL to another URL?

location.href = "Pagename.html";

ggplot2 legend to bottom and horizontal

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.

Set height of <div> = to height of another <div> through .css

I am assuming that you have used height attribute at both so i am comparing it with a height left do it with JavaScript.

var right=document.getElementById('rightdiv').style.height;
var left=document.getElementById('leftdiv').style.height;
if(left>right)
{
    document.getElementById('rightdiv').style.height=left;
}
else
{
    document.getElementById('leftdiv').style.height=right;
}

Another idea can be found here HTML/CSS: Making two floating divs the same height.

"commence before first target. Stop." error

It's a simple Mistake while adding a new file you just have to make sure that \ is added to the file before and the new file remain as it is eg.

Check Out what to do if i want to add a new file named customer.cc

Effectively use async/await with ASP.NET Web API

You are not leveraging async / await effectively because the request thread will be blocked while executing the synchronous method ReturnAllCountries()

The thread that is assigned to handle a request will be idly waiting while ReturnAllCountries() does it's work.

If you can implement ReturnAllCountries() to be asynchronous, then you would see scalability benefits. This is because the thread could be released back to the .NET thread pool to handle another request, while ReturnAllCountries() is executing. This would allow your service to have higher throughput, by utilizing threads more efficiently.

Using member variable in lambda capture list inside a member function

Summary of the alternatives:

capture this:

auto lambda = [this](){};

use a local reference to the member:

auto& tmp = grid;
auto lambda = [ tmp](){}; // capture grid by (a single) copy
auto lambda = [&tmp](){}; // capture grid by ref

C++14:

auto lambda = [ grid = grid](){}; // capture grid by copy
auto lambda = [&grid = grid](){}; // capture grid by ref

example: https://godbolt.org/g/dEKVGD

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

If you need to both get the raw content from the request, but also need to use a bound model version of it in the controller, you will likely get this exception.

NotSupportedException: Specified method is not supported. 

For example, your controller might look like this, leaving you wondering why the solution above doesn't work for you:

public async Task<IActionResult> Index(WebhookRequest request)
{
    using var reader = new StreamReader(HttpContext.Request.Body);

    // this won't fix your string empty problems
    // because exception will be thrown
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var body = await reader.ReadToEndAsync();

    // Do stuff
}

You'll need to take your model binding out of the method parameters, and manually bind yourself:

public async Task<IActionResult> Index()
{
    using var reader = new StreamReader(HttpContext.Request.Body);

    // You shouldn't need this line anymore.
    // reader.BaseStream.Seek(0, SeekOrigin.Begin);

    // You now have the body string raw
    var body = await reader.ReadToEndAsync();

    // As well as a bound model
    var request = JsonConvert.DeserializeObject<WebhookRequest>(body);
}

It's easy to forget this, and I've solved this issue before in the past, but just now had to relearn the solution. Hopefully my answer here will be a good reminder for myself...

Convert timedelta to total seconds

You can use mx.DateTime module

import mx.DateTime as mt

t1 = mt.now() 
t2 = mt.now()
print int((t2-t1).seconds)

What difference is there between WebClient and HTTPWebRequest classes in .NET?

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:

var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

With WebClient, you just do DownloadString:

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.

Lua string to int

tonumber (e [, base])

tonumber takes two arguments, first is string which is converted to number and second is base of e.

Return value tonumber is in base 10.

If no base is provided it converts number to base 10.

> a = '101'
> tonumber(a)
101

If base is provided, it converts it to the given base.

> a = '101'
> 
> tonumber(a, 2)
5
> tonumber(a, 8)
65
> tonumber(a, 10)
101
> tonumber(a, 16)
257
> 

If e contains invalid character then it returns nil.

> --[[ Failed because base 2 numbers consist (0 and 1) --]]
> a = '112'
> tonumber(a, 2)
nil
> 
> --[[ similar to above one, this failed because --]]
> --[[ base 8 consist (0 - 7) --]]
> --[[ base 10 consist (0 - 9) --]]
> a = 'AB'
> tonumber(a, 8)
nil
> tonumber(a, 10)
nil
> tonumber(a, 16)
171

I answered considering Lua5.3

Linux command (like cat) to read a specified quantity of characters

Even though this was answered/accepted years ago, the presently accepted answer is only correct for one-byte-per-character encodings like iso-8859-1, or for the single-byte subsets of variable-byte character sets (like Latin characters within UTF-8). Even using multiple-byte splices instead would still only work for fixed-multibyte encodings like UTF-16. Given that now UTF-8 is well on its way to being a universal standard, and when looking at this list of languages by number of native speakers and this list of top 30 languages by native/secondary usage, it is important to point out a simple variable-byte character-friendly (not byte-based) technique, using cut -c and tr/sed with character-classes.

Compare the following which doubly fails due to two common Latin-centric mistakes/presumptions regarding the bytes vs. characters issue (one is head vs. cut, the other is [a-z][A-Z] vs. [:upper:][:lower:]):

$ printf '??? µp??? ?a µ??? sa?s???t???;\n' | \
$     head -c 1 | \
$     sed -e 's/[A-Z]/[a-z]/g'
[[unreadable binary mess, or nothing if the terminal filtered it]]

to this (note: this worked fine on FreeBSD, but both cut & tr on GNU/Linux still mangled Greek in UTF-8 for me though):

$ printf '??? µp??? ?a µ??? sa?s???t???;\n' | \
$     cut -c 1 | \
$     tr '[:upper:]' '[:lower:]'
p

Another more recent answer had already proposed "cut", but only because of the side issue that it can be used to specify arbitrary offsets, not because of the directly relevant character vs. bytes issue.

If your cut doesn't handle -c with variable-byte encodings correctly, for "the first X characters" (replace X with your number) you could try:

  • sed -E -e '1 s/^(.{X}).*$/\1/' -e q - which is limited to the first line though
  • head -n 1 | grep -E -o '^.{X}' - which is limited to the first line and chains two commands though
  • dd - which has already been suggested in other answers, but is really cumbersome
  • A complicated sed script with sliding window buffer to handle characters spread over multiple lines, but that is probably more cumbersome/fragile than just using something like dd

If your tr doesn't handle character-classes with variable-byte encodings correctly you could try:

  • sed -E -e 's/[[:upper:]]/\L&/g (GNU-specific)

Responsive timeline UI with Bootstrap3

"Timeline (responsive)" snippet:

This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.

You can fork this and use it as a great starting point for your specific expectations:


Here are two screenshots I took for you... wide and thin:

wide thin

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I had this issue when attempting to import data from an excel file (xlsx) into a SQL Server DB using SSMS 2014.

The 2007 Office System Driver: Data Connectivity Components install did the trick for me.

Getting unix timestamp from Date()

Use SimpleDateFormat class. Take a look on its javadoc: it explains how to use format switches.

Printing 1 to 1000 without loop or conditionals

#include <iostream>
#include <vector>

using namespace std;
#define N 10    //10 or 1000, doesn't matter

class A{
public:
    A(){
        //cout << "A(): " << m_ << endl;    //uncomment to show the difference between gcc and Microsoft C++ compiler
    }
    A(const A&){
        ++m_;
        cout << m_ << endl;     
    }
private:
    static int m_;  //global counter
};

int A::m_(0);  //initialization

int main(int argc, char* argv[])
{
    //Creates a vector with N elements. Printing is from the copy constructor, 
    //which is called exactly N times.
    vector<A> v(N);  
    return 0;   
}

Implementation note:
With gcc: One "master" element is created by the default constructor. Then the element is copied N times by the copy constructor.
With Microsoft C++ compiler: all the elements are created by default constructor and then copied by the copy constructor.

Using setattr() in python

You are setting self.name to the string "get_thing", not the function get_thing.

If you want self.name to be a function, then you should set it to one:

setattr(self, 'name', self.get_thing)

However, that's completely unnecessary for your other code, because you could just call it directly:

value_returned = self.get_thing()

What's the best way to add a full screen background image in React Native

I've heard about having to use BackgroundImage because in future you are supposed to not be able to nest the Image tag. But I could not get BackgroudImage to properly display my background. What I did was nest my Image inside a View tag and style both the outer View as well as the image. Keys were setting width to null, and setting resizeMode to 'stretch'. Below is my code:

_x000D_
_x000D_
import React, {Component} from 'react';_x000D_
import { View, Text, StyleSheet, Image} from 'react-native';_x000D_
_x000D_
export default class BasicImage extends Component {_x000D_
 constructor(props) {_x000D_
   super(props);_x000D_
_x000D_
   this.state = {};_x000D_
 }_x000D_
_x000D_
 render() {_x000D_
  return (_x000D_
   <View style={styles.container}>_x000D_
       <Image _x000D_
         source={this.props.source}_x000D_
         style={styles.backgroundImage}_x000D_
       />_x000D_
      </View>_x000D_
  )_x000D_
 }_x000D_
}_x000D_
_x000D_
const styles = StyleSheet.create({   _x000D_
  container: {_x000D_
   flex: 1,_x000D_
   width: null,_x000D_
   height: null,_x000D_
   marginBottom: 50_x000D_
  },_x000D_
    text: {_x000D_
      marginLeft: 5,_x000D_
      marginTop: 22,_x000D_
      fontFamily: 'fontawesome',_x000D_
        color: 'black',_x000D_
        fontSize: 25,_x000D_
        backgroundColor: 'rgba(0,0,0,0)',_x000D_
    },_x000D_
  backgroundImage: {_x000D_
   flex: 1,_x000D_
   width: null,_x000D_
   height: null,_x000D_
   resizeMode: 'stretch',_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.