Programs & Examples On #I2c

I2C is a two-wire serial bus. It is used to interface with low-speed peripherals in embedded systems and computer motherboards.

How can you flush a write using a file descriptor?

fflush() only flushes the buffering added by the stdio fopen() layer, as managed by the FILE * object. The underlying file itself, as seen by the kernel, is not buffered at this level. This means that writes that bypass the FILE * layer, using fileno() and a raw write(), are also not buffered in a way that fflush() would flush.

As others have pointed out, try not mixing the two. If you need to use "raw" I/O functions such as ioctl(), then open() the file yourself directly, without using fopen<() and friends from stdio.

How to use QueryPerformanceCounter?

#include <windows.h>

double PCFreq = 0.0;
__int64 CounterStart = 0;

void StartCounter()
{
    LARGE_INTEGER li;
    if(!QueryPerformanceFrequency(&li))
    cout << "QueryPerformanceFrequency failed!\n";

    PCFreq = double(li.QuadPart)/1000.0;

    QueryPerformanceCounter(&li);
    CounterStart = li.QuadPart;
}
double GetCounter()
{
    LARGE_INTEGER li;
    QueryPerformanceCounter(&li);
    return double(li.QuadPart-CounterStart)/PCFreq;
}

int main()
{
    StartCounter();
    Sleep(1000);
    cout << GetCounter() <<"\n";
    return 0;
}

This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).

The StartCounter() function records the number of ticks the performance counter has in the CounterStart variable. The GetCounter() function returns the number of milliseconds since StartCounter() was last called as a double, so if GetCounter() returns 0.001 then it has been about 1 microsecond since StartCounter() was called.

If you want to have the timer use seconds instead then change

PCFreq = double(li.QuadPart)/1000.0;

to

PCFreq = double(li.QuadPart);

or if you want microseconds then use

PCFreq = double(li.QuadPart)/1000000.0;

But really it's about convenience since it returns a double.

How to reshape data from long to wide format

Other two options:

Base package:

df <- unstack(dat1, form = value ~ numbers)
rownames(df) <- unique(dat1$name)
df

sqldf package:

library(sqldf)
sqldf('SELECT name,
      MAX(CASE WHEN numbers = 1 THEN value ELSE NULL END) x1, 
      MAX(CASE WHEN numbers = 2 THEN value ELSE NULL END) x2,
      MAX(CASE WHEN numbers = 3 THEN value ELSE NULL END) x3,
      MAX(CASE WHEN numbers = 4 THEN value ELSE NULL END) x4
      FROM dat1
      GROUP BY name')

UIImageView aspect fit and center

This subclass uses center if the image is not larger than the view, otherwise it scales down. I found this useful for a UIImageView that changes the size.

The image it displays is smaller than the view for large sizes, but larger than the view for small sizes. I want it only to scale down, but not up.

class CenterScaleToFitImageView: UIImageView {
    override var bounds: CGRect {
        didSet {
            adjustContentMode()
        }
    }

    override var image: UIImage? {
        didSet {
            adjustContentMode()
        }
    }

    func adjustContentMode() {
        guard let image = image else {
            return
        }
        if image.size.width > bounds.size.width ||
            image.size.height > bounds.size.height {
            contentMode = .ScaleAspectFit
        } else {
            contentMode = .Center
        }
    }
}

How can I read and manipulate CSV file data in C++?

If what you're really doing is manipulating a CSV file itself, Nelson's answer makes sense. However, my suspicion is that the CSV is simply an artifact of the problem you're solving. In C++, that probably means you have something like this as your data model:

struct Customer {
    int id;
    std::string first_name;
    std::string last_name;
    struct {
        std::string street;
        std::string unit;
    } address;
    char state[2];
    int zip;
};

Thus, when you're working with a collection of data, it makes sense to have std::vector<Customer> or std::set<Customer>.

With that in mind, think of your CSV handling as two operations:

// if you wanted to go nuts, you could use a forward iterator concept for both of these
class CSVReader {
public:
    CSVReader(const std::string &inputFile);
    bool hasNextLine();
    void readNextLine(std::vector<std::string> &fields);
private:
    /* secrets */
};
class CSVWriter {
public:
    CSVWriter(const std::string &outputFile);
    void writeNextLine(const std::vector<std::string> &fields);
private:
    /* more secrets */
};
void readCustomers(CSVReader &reader, std::vector<Customer> &customers);
void writeCustomers(CSVWriter &writer, const std::vector<Customer> &customers);

Read and write a single row at a time, rather than keeping a complete in-memory representation of the file itself. There are a few obvious benefits:

  1. Your data is represented in a form that makes sense for your problem (customers), rather than the current solution (CSV files).
  2. You can trivially add adapters for other data formats, such as bulk SQL import/export, Excel/OO spreadsheet files, or even an HTML <table> rendering.
  3. Your memory footprint is likely to be smaller (depends on relative sizeof(Customer) vs. the number of bytes in a single row).
  4. CSVReader and CSVWriter can be reused as the basis for an in-memory model (such as Nelson's) without loss of performance or functionality. The converse is not true.

Append an empty row in dataframe using pandas

Add a new pandas.Series using pandas.DataFrame.append().

If you wish to specify the name (AKA the "index") of the new row, use:

df.append(pandas.Series(name='NameOfNewRow'))

If you don't wish to name the new row, use:

df.append(pandas.Series(), ignore_index=True)

where df is your pandas.DataFrame.

GridLayout and Row/Column Span Woe

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:columnCount="8"
        android:rowCount="7" >

        <TextView
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:layout_columnSpan="2"
            android:layout_rowSpan="2"
            android:background="#a30000"
            android:gravity="center"
            android:text="1"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="50dip"
            android:layout_height="25dip"
            android:layout_columnSpan="2"
            android:layout_rowSpan="1"
            android:background="#0c00a3"
            android:gravity="center"
            android:text="2"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="25dip"
            android:layout_height="100dip"
            android:layout_columnSpan="1"
            android:layout_rowSpan="4"
            android:background="#00a313"
            android:gravity="center"
            android:text="3"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="75dip"
            android:layout_height="50dip"
            android:layout_columnSpan="3"
            android:layout_rowSpan="2"
            android:background="#a29100"
            android:gravity="center"
            android:text="4"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="75dip"
            android:layout_height="25dip"
            android:layout_columnSpan="3"
            android:layout_rowSpan="1"
            android:background="#a500ab"
            android:gravity="center"
            android:text="5"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="50dip"
            android:layout_height="25dip"
            android:layout_columnSpan="2"
            android:layout_rowSpan="1"
            android:background="#00a9ab"
            android:gravity="center"
            android:text="6"
            android:textColor="@android:color/white"
            android:textSize="20dip" />
    </GridLayout>

</RelativeLayout>

ScreenShot

Comparing Java enum members: == or equals()?

In short, both have pros and cons.

On one hand, it has advantages to use ==, as described in the other answers.

On the other hand, if you for any reason replace the enums with a different approach (normal class instances), having used == bites you. (BTDT.)

Automating running command on Linux from Windows using PuTTY

There could be security issues with common methods for auto-login. One of the most easiest ways is documented below:

And as for the part the executes the command In putty UI, Connection>SSH> there's a field for remote command.

4.17 The SSH panel

The SSH panel allows you to configure options that only apply to SSH sessions.

4.17.1 Executing a specific command on the server

In SSH, you don't have to run a general shell session on the server. Instead, you can choose to run a single specific command (such as a mail user agent, for example). If you want to do this, enter the command in the "Remote command" box. http://the.earth.li/~sgtatham/putty/0.53/htmldoc/Chapter4.html

in short, your answers might just as well be similar to the text below:

Java Runtime.getRuntime(): getting output from executing a command line program

If use are already have Apache commons-io available on the classpath, you may use:

Process p = new ProcessBuilder("cat", "/etc/something").start();
String stderr = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());

List of lists into numpy array

If your list of lists contains lists with varying number of elements then the answer of Ignacio Vazquez-Abrams will not work. Instead there are at least 3 options:

1) Make an array of arrays:

x=[[1,2],[1,2,3],[1]]
y=numpy.array([numpy.array(xi) for xi in x])
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'numpy.ndarray'>

2) Make an array of lists:

x=[[1,2],[1,2,3],[1]]
y=numpy.array(x)
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'list'>

3) First make the lists equal in length:

x=[[1,2],[1,2,3],[1]]
length = max(map(len, x))
y=numpy.array([xi+[None]*(length-len(xi)) for xi in x])
y
>>>array([[1, 2, None],
>>>       [1, 2, 3],
>>>       [1, None, None]], dtype=object)

Accessing elements by type in javascript

If you are lucky and need to care only for recent browsers, you can use:

document.querySelectorAll('input[type=text]')

"recent" means not IE6 and IE7

Meaning of Open hashing and Closed hashing

The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).

For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.

The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.

Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".

In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".

Keyboard shortcut to comment lines in Sublime Text 3

I prefer pressing Ctrl + / to (un)comment the current line. Plus, I want the cursor to move down one line, thus this way I can (un)comment several lines easily. If you install the "Chain of Command" plugin, you can combine these two operations:

[
    { 
        "keys": ["ctrl+keypad_divide"], 
        "command": "chain",
        "args": {
            "commands": [
                ["toggle_comment", { "block": false }],
                ["move", {"by": "lines", "forward": true}]
            ]
        }
    }
]

What's a good (free) visual merge tool for Git? (on windows)

I've been using P4Merge, it's free and cross platform.

P4Merge

How to include quotes in a string

string str = @"""Hi, "" I am programmer";

OUTPUT - "Hi, " I am programmer

How to style readonly attribute with CSS?

Note that textarea[readonly="readonly"] works if you set readonly="readonly" in HTML but it does NOT work if you set the readOnly-attribute to true or "readonly" via JavaScript.

For the CSS selector to work if you set readOnly with JavaScript you have to use the selector textarea[readonly].

Same behavior in Firefox 14 and Chrome 20.

To be on the safe side, i use both selectors.

textarea[readonly="readonly"], textarea[readonly] {
...
}

RunAs A different user when debugging in Visual Studio

I'm using Visual Studio 2015 and attempting to debug a website with different credentials.

(I'm currently testing a website on a development network that has a copy of the live active directory; I can "hijack" user accounts to test permissions in a safe way)

  1. Begin debugging with your normal user, ensure you can get to http://localhost:8080 as normal etc
  2. Give the other user "Full Control" access to your normal user's home directory, ie, C:\Users\Colin
  3. Make the other user an administrator on your machine. Right click Computer > Manage > Add other user to Administrator group
  4. Run Internet Explorer as the other user (Shift + Right Click Internet Explorer, Run as different user)
  5. Go to your localhost URL in that IE window

Really convenient to do some quick testing. The Full Control access is probably overkill but I develop on an isolated network. If anyone adds notes about more specific settings I'll gladly edit this post in future.

Test if remote TCP port is open from a shell script

In some cases where tools like curl, telnet, nc o nmap are unavailable you still have a chance with wget

if [[ $(wget -q -t 1 --spider --dns-timeout 3 --connect-timeout 10  host:port; echo $?) -eq 0 ]]; then echo "OK"; else echo "FAIL"; fi

.Net picking wrong referenced assembly version

I was getting:

Could not load file or assembly 'XXX-new-3.3.0.0' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

It was because I changed the name of the assembly from XXX.dll to XXX-new-3.3.0.0.dll. Reverting name back to the original fixed the error.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

If the 2nd company is happy for you to access their content in an IFrame then they need to take the restriction off - they can do this fairly easily in the IIS config.

There's nothing you can do to circumvent it and anything that does work should get patched quickly in a security hotfix. You can't tell the browser to just render the frame if the source content header says not allowed in frames. That would make it easier for session hijacking.

If the content is GET only you don't post data back then you could get the page server side and proxy the content without the header, but then any post back should get invalidated.

Bootstrap push div content to new line

Do a row div.

Like this:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
        <div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Execution failed for task ':app:compileDebugAidl': aidl is missing

I was able to get build to work with Build Tools 23.0.0 rc1 if I also opened the project level build.gradle file and set the version of the android build plugin to 1.3.0-beta1. Also, I'm tracking the canary and preview builds and just updated a few seconds before, so perhaps that helped.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0-beta1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Assigning a function to a variable

lambda should be useful for this case. For example,

  1. create function y=x+1 y=lambda x:x+1

  2. call the function y(1) then return 2.

How to get a Docker container's IP address from the host

Along with the accepted answer if you need a specific handy alias to get a specific container ip use this alias

alias dockerip='f(){ docker inspect $1|grep -i "ipaddress.*[12]*\.[0-9]*"|sed -e "s/^  *//g" -e "s/[\",]//g" -e "s/[*,]//g" -e "s/[a-zA-Z: ]//g" | sort --unique;  unset -f f; }; f'

and then you can get your container ip with

dockerip <containername>  

You can also use containerid instead of containername

BTW accepted great answer doenst produce a clean output so I edited it and using like this ;

alias dockerips='for NAME in $(docker ps --format {{.Names}}); do echo -n "$NAME:"; docker inspect $NAME|grep -i "ipaddress.*[12]*\.[0-9]*"|sed -e "s/^  *//g" -e "s/[\",]//g" -e "s/[_=*,]//g" -e "s/[a-zA-Z: ]//g "| sort --unique;done'

Refreshing Web Page By WebDriver When Waiting For Specific Condition

In R you can use the refresh method, but to start with we navigate to a url using navigate method:

remDr$navigate("https://...")
remDr$refresh()

Spell Checker for Python

You can use the autocorrect lib to spell check in python.
Example Usage:

from autocorrect import Speller

spell = Speller(lang='en')

print(spell('caaaar'))
print(spell('mussage'))
print(spell('survice'))
print(spell('hte'))

Result:

caesar
message
service
the

How to set Grid row and column positions programmatically

Here is an example which might help someone:

Grid test = new Grid();
test.ColumnDefinitions.Add(new ColumnDefinition());
test.ColumnDefinitions.Add(new ColumnDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());

Label t1 = new Label();
t1.Content = "Test1";
Label t2 = new Label();
t2.Content = "Test2";
Label t3 = new Label();
t3.Content = "Test3";
Label t4 = new Label();
t4.Content = "Test4";
Label t5 = new Label();
t5.Content = "Test5";
Label t6 = new Label();
t6.Content = "Test6";

Grid.SetColumn(t1, 0);
Grid.SetRow(t1, 0);
test.Children.Add(t1);

Grid.SetColumn(t2, 1);
Grid.SetRow(t2, 0);
test.Children.Add(t2);

Grid.SetColumn(t3, 0);
Grid.SetRow(t3, 1);
test.Children.Add(t3);

Grid.SetColumn(t4, 1);
Grid.SetRow(t4, 1);
test.Children.Add(t4);

Grid.SetColumn(t5, 0);
Grid.SetRow(t5, 2);
test.Children.Add(t5);

Grid.SetColumn(t6, 1);
Grid.SetRow(t6, 2);
test.Children.Add(t6);

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

How To Create Table with Identity Column

[id] [int] IDENTITY(1,1) NOT NULL,

of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.

enter image description here

How to set the From email address for mailx command?

The package nail provides an enhanced mailx like interface. It includes the -r option.

On Centos 5 installing the package mailx gives you a program called mail, which doesn't support the mailx options.

How can I store and retrieve images from a MySQL database using PHP?

Instead of storing images in database store them in a folder in your disk and store their location in your data base.

ToString() function in Go

Attach a String() string method to any named type and enjoy any custom "ToString" functionality:

package main

import "fmt"

type bin int

func (b bin) String() string {
        return fmt.Sprintf("%b", b)
}

func main() {
        fmt.Println(bin(42))
}

Playground: http://play.golang.org/p/Azql7_pDAA


Output

101010

LINQ .Any VS .Exists - What's the difference?

Additionally, this will only work if Value is of type bool. Normally this is used with predicates. Any predicate would be generally used find whether there is any element satisfying a given condition. Here you're just doing a map from your element i to a bool property. It will search for an "i" whose Value property is true. Once done, the method will return true.

Is there any way to start with a POST request using Selenium?

If you are using Python selenium bindings, nowadays, there is an extension to selenium - selenium-requests:

Extends Selenium WebDriver classes to include the request function from the Requests library, while doing all the needed cookie and request headers handling.

Example:

from seleniumrequests import Firefox

webdriver = Firefox()
response = webdriver.request('POST', 'url here', data={"param1": "value1"})
print(response)

How to change font size on part of the page in LaTeX?

\begingroup
    \fontsize{10pt}{12pt}\selectfont
    \begin{verbatim}  
        % how to set font size here to 10 px ?  
    \end{verbatim}  
\endgroup

Can JavaScript connect with MySQL?

You can connect to MySQL from Javascript through a JAVA applet. The JAVA applet would embed the JDBC driver for MySQL that will allow you to connect to MySQL.

Remember that if you want to connect to a remote MySQL server (other than the one you downloaded the applet from) you will need to ask users to grant extended permissions to applet. By default, applet can only connect to the server they are downloaded from.

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

How do I select a sibling element using jQuery?

Use jQuery .siblings() to select the matching sibling.

$(this).siblings('.bidbutton');

Use of "global" keyword in Python

The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.

def bob():
    me = "locally defined"    # Defined only in local context
    print(me)

bob()
print(me)     # Asking for a global variable

The above will give you:

locally defined
Traceback (most recent call last):
  File "file.py", line 9, in <module>
    print(me)
NameError: name 'me' is not defined

While if you use the global statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.

def bob():
    global me
    me = "locally defined"   # Defined locally but declared as global
    print(me)

bob()
print(me)     # Asking for a global variable

So the above code will give you:

locally defined
locally defined

In addition, due to the nature of python, you could also use global to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

ALTER TABLE public.contract_termination_requests
ALTER COLUMN management_company_id DROP NOT NULL;

How can I detect when the mouse leaves the window?

$(window).mouseleave(function(event) {
  if (event.toElement == null) {
    //Do something
  }
})

This might be a bit hacky but it will only trigger when the mouse leaves the window. I kept catching child events and this resolved it

How can I present a file for download from an MVC controller?

Although standard action results FileContentResult or FileStreamResult may be used for downloading files, for reusability, creating a custom action result might be the best solution.

As an example let's create a custom action result for exporting data to Excel files on the fly for download.

ExcelResult class inherits abstract ActionResult class and overrides the ExecuteResult method.

We are using FastMember package for creating DataTable from IEnumerable object and ClosedXML package for creating Excel file from the DataTable.

public class ExcelResult<T> : ActionResult
{
    private DataTable dataTable;
    private string fileName;

    public ExcelResult(IEnumerable<T> data, string filename, string[] columns)
    {
        this.dataTable = new DataTable();
        using (var reader = ObjectReader.Create(data, columns))
        {
            dataTable.Load(reader);
        }
        this.fileName = filename;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context != null)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}""", fileName));
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dataTable, "Sheet1");
                using (MemoryStream stream = new MemoryStream())
                {
                    wb.SaveAs(stream);
                    response.BinaryWrite(stream.ToArray());
                }
            }
        }
    }
}

In the Controller use the custom ExcelResult action result as follows

[HttpGet]
public async Task<ExcelResult<MyViewModel>> ExportToExcel()
{
    var model = new Models.MyDataModel();
    var items = await model.GetItems();
    string[] columns = new string[] { "Column1", "Column2", "Column3" };
    string filename = "mydata.xlsx";
    return new ExcelResult<MyViewModel>(items, filename, columns);
}

Since we are downloading the file using HttpGet, create an empty View without model and empty layout.

Blog post about custom action result for downloading files that are created on the fly:

https://acanozturk.blogspot.com/2019/03/custom-actionresult-for-files-in-aspnet.html

Using "&times" word in html changes to ×

&times; stands for × in html. Use &amp;times to get &times

Fatal error: unexpectedly found nil while unwrapping an Optional values

I searched around for a solution to this myself. only my problem was related to UITableViewCell Not UICollectionView as your mentioning here.

First off, im new to iOS development. like brand new, sitting here trying to get trough my first tutorial, so dont take my word for anything. (unless its working ;) )

I was getting a nil reference to cell.detailTextLabel.text - After rewatching the tutorial video i was following, it didnt look like i had missed anything. So i entered the header file for the UITableViewCell and found this.

var detailTextLabel: UILabel! { get } // default is nil. label will be created if necessary (and the current style supports a detail label).

So i noticed that it says (and the current style supports a detail label) - Well, Custom style does not have a detailLabel on there by default. so i just had to switch the style of the cell in the Storyboard, and all was fine.

Im guesssing your label should always be there?

So if your following connor`s advice, that basically means, IF that label is available, then use it. If your style is correctly setup and the reuse identifier matches the one set in the Storyboard you should not have to do this check unless your using more then one custom cell.

Couldn't load memtrack module Logcat Error

I faced the same problem but When I changed the skin of AVD device to HVGA, it worked.

How can I call a method in Objective-C?

calling the method is like this

[className methodName] 

however if you want to call the method in the same class you can use self

[self methodName] 

all the above is because your method was not taking any parameters

however if your method takes parameters you will need to do it like this

[self methodName:Parameter]

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

The easiest way was to (prior to Java 8) use,

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

But SimpleDateFormat is not thread-safe. Neither java.util.Date. This will lead to leading to potential concurrency issues for users. And there are many problems in those existing designs. To overcome these now in Java 8 we have a separate package called java.time. This Java SE 8 Date and Time document has a good overview about it.

So in Java 8 something like below will do the trick (to format the current date/time),

LocalDateTime.now()
   .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));

And one thing to note is it was developed with the help of the popular third party library joda-time,

The project has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under JSR 310, and will appear in the new Java SE 8 package java.time.

But now the joda-time is becoming deprecated and asked the users to migrate to new java.time.

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project

Anyway having said that,

If you have a Calendar instance you can use below to convert it to the new java.time,

    Calendar calendar = Calendar.getInstance();
    long longValue = calendar.getTimeInMillis();         

    LocalDateTime date =
            LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
    String formattedString = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));

    System.out.println(date.toString()); // 2018-03-06T15:56:53.634
    System.out.println(formattedString); // 2018-03-06 15:56:53.634

If you had a Date object,

    Date date = new Date();
    long longValue2 = date.getTime();

    LocalDateTime dateTime =
            LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue2), ZoneId.systemDefault());
    String formattedString = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));

    System.out.println(dateTime.toString()); // 2018-03-06T15:59:30.278
    System.out.println(formattedString);     // 2018-03-06 15:59:30.278

If you just had the epoch milliseconds,

LocalDateTime date =
        LocalDateTime.ofInstant(Instant.ofEpochMilli(epochLongValue), ZoneId.systemDefault());

How to read numbers from file in Python?

is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4)

with open('in.txt') as f:
  rows,cols=np.fromfile(f, dtype=int, count=2, sep=" ")
  data = np.fromfile(f, dtype=int, count=cols*rows, sep=" ").reshape((rows,cols))

another way: is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4), as well for complex matrices see the example below (only change int to complex)

with open('in.txt') as f:
   data = []
   cols,rows=list(map(int, f.readline().split()))
   for i in range(0, rows):
      data.append(list(map(int, f.readline().split()[:cols])))
print (data)

I updated the code, this method is working for any number of matrices and any kind of matrices(int,complex,float) in the initial in.txt file.

This program yields matrix multiplication as an application. Is working with python2, in order to work with python3 make the following changes

print to print()

and

print "%7g" %a[i,j],    to     print ("%7g" %a[i,j],end="")

the script:

import numpy as np

def printMatrix(a):
   print ("Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]")
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print "%7g" %a[i,j],
      print
   print      

def readMatrixFile(FileName):
   rows,cols=np.fromfile(FileName, dtype=int, count=2, sep=" ")
   a = np.fromfile(FileName, dtype=float, count=rows*cols, sep=" ").reshape((rows,cols))
   return a

def readMatrixFileComplex(FileName):
   data = []
   rows,cols=list(map(int, FileName.readline().split()))
   for i in range(0, rows):
      data.append(list(map(complex, FileName.readline().split()[:cols])))
   a = np.array(data)
   return a

f = open('in.txt')
a=readMatrixFile(f)
printMatrix(a)
b=readMatrixFile(f)
printMatrix(b)
a1=readMatrixFile(f)
printMatrix(a1)
b1=readMatrixFile(f)
printMatrix(b1)
f.close()

print ("matrix multiplication")
c = np.dot(a,b)
printMatrix(c)
c1 = np.dot(a1,b1)
printMatrix(c1)

with open('complex_in.txt') as fid:
  a2=readMatrixFileComplex(fid)
  print(a2)
  b2=readMatrixFileComplex(fid)
  print(b2)

print ("complex matrix multiplication")
c2 = np.dot(a2,b2)
print(c2)
print ("real part of complex matrix")
printMatrix(c2.real)
print ("imaginary part of complex matrix")
printMatrix(c2.imag)

as input file I take in.txt:

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.02 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
3 4
1 2 -2 0
-3 4 7 2
6 0 3 1
4 2
-1 3
0 9
1 -11
4 -5

and complex_in.txt

3 4
1+1j 2+2j -2-2j 0+0j
-3-3j 4+4j 7+7j 2+2j
6+6j 0+0j 3+3j 1+1j
4 2
-1-1j 3+3j
0+0j 9+9j
1+1j -11-11j
4+4j -5-5j

and the output look like:

Matrix[4][4]
     1      1      1      1
     2      4      8     16
     3      9     27     81
     4     16     64    256

Matrix[4][3]
  4.02     -3      4
   -13     19     -7
     3     -2      7
    -1      1     -1

Matrix[3][4]
     1      2     -2      0
    -3      4      7      2
     6      0      3      1

Matrix[4][2]
    -1      3
     0      9
     1    -11
     4     -5

matrix multiplication
Matrix[4][3]
  -6.98      15       3
 -35.96      70      20
-104.94     189      57
-255.92     420      96

Matrix[3][2]
    -3     43
    18    -60
     1    -20

[[ 1.+1.j  2.+2.j -2.-2.j  0.+0.j]
 [-3.-3.j  4.+4.j  7.+7.j  2.+2.j]
 [ 6.+6.j  0.+0.j  3.+3.j  1.+1.j]]
[[ -1. -1.j   3. +3.j]
 [  0. +0.j   9. +9.j]
 [  1. +1.j -11.-11.j]
 [  4. +4.j  -5. -5.j]]
complex matrix multiplication
[[ 0.  -6.j  0. +86.j]
 [ 0. +36.j  0.-120.j]
 [ 0.  +2.j  0. -40.j]]
real part of complex matrix
Matrix[3][2]
      0       0
      0       0
      0       0

imaginary part of complex matrix
Matrix[3][2]
     -6      86
     36    -120
      2     -40

Batch file to delete folders older than 10 days in Windows 7

Adapted from this answer to a very similar question:

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

You should run this command from within your d:\study folder. It will delete all subfolders which are older than 10 days.

The /S /Q after the rd makes it delete folders even if they are not empty, without prompting.

I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat.

Switch/toggle div (jQuery)

function toggling_fields_contact_bank(class_name) {
    jQuery("." + class_name).animate({
        height: 'toggle'
    });
}

Facebook user url by id

I've collected info together:

And finaly: it doen't work without additional Facebook permission check:(

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

Where does System.Diagnostics.Debug.Write output appear?

The Diagnostics messages are displayed in the Output Window.

org.hibernate.MappingException: Could not determine type for: java.util.Set

I got the same problem with @ManyToOne column. It was solved... in stupid way. I had all other annotations for public getter methods, because they were overridden from parent class. But last field was annotated for private variable like in all other classes in my project. So I got the same MappingException without the reason.

Solution: I placed all annotations at public getter methods. I suppose, Hibernate can't handle cases, when annotations for private fields and public getters are mixed in one class.

Remove a file from a Git repository without deleting it from the local filesystem

Git lets you ignore those files by assuming they are unchanged. This is done by running the git update-index --assume-unchanged path/to/file.txt command. Once marking a file as such, git will completely ignore any changes on that file; they will not show up when running git status or git diff, nor will they ever be committed.

(From https://help.github.com/articles/ignoring-files)

Hence, not deleting it, but ignoring changes to it forever. I think this only works locally, so co-workers can still see changes to it unless they run the same command as above. (Still need to verify this though.)

Note: This isn't answering the question directly, but is based on follow up questions in the comments of the other answers.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

I had same error, I think the problem is that the error text is confusing, because its giving a false key name.

In your case It should say "There is no ViewData item of type 'IEnumerable' that has the key "Submarkets"".

My error was a misspelling in the view code (your "Submarkets"), but the error text made me go crazy.

I post this answer because I want to say people looking for this error, like I was, that the problem is that its not finding the IENumerable, but in the var that its supposed to look for it ("Submarkets" in this case), not in the one showed in error ("submarket_0").

Accepted answer is very interesting, but as you said the convention is applied if you dont specify the 2nd parameter, in this case it was specified, but the var was not found (in your case because the viewdata had not it, in my case because I misspelled the var name)

Hope this helps!

Replace substring with another substring C++

There is no one built-in function in C++ to do this. If you'd like to replace all instances of one substring with another, you can do so by intermixing calls to string::find and string::replace. For example:

size_t index = 0;
while (true) {
     /* Locate the substring to replace. */
     index = str.find("abc", index);
     if (index == std::string::npos) break;

     /* Make the replacement. */
     str.replace(index, 3, "def");

     /* Advance index forward so the next iteration doesn't pick it up as well. */
     index += 3;
}

In the last line of this code, I've incremented index by the length of the string that's been inserted into the string. In this particular example - replacing "abc" with "def" - this is not actually necessary. However, in a more general setting, it is important to skip over the string that's just been replaced. For example, if you want to replace "abc" with "abcabc", without skipping over the newly-replaced string segment, this code would continuously replace parts of the newly-replaced strings until memory was exhausted. Independently, it might be slightly faster to skip past those new characters anyway, since doing so saves some time and effort by the string::find function.

Hope this helps!

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

To sum up based on answers here and elsewhere:

  1. Check the .NET version of the app pool (e.g. 2.0 vs 4.0)
  2. Check that all IIS referenced modules are installed. In this case it was the AJAX extensions (probably not the case these days), but URL Rewrite is a common one.

Simple if else onclick then do?

you call function on page load time but not call on button event, you will need to call function onclick event, you may add event inline element style or event bining

_x000D_
_x000D_
 function Choice(elem) {_x000D_
   var box = document.getElementById("box");_x000D_
   if (elem.id == "no") {_x000D_
     box.style.backgroundColor = "red";_x000D_
   } else if (elem.id == "yes") {_x000D_
     box.style.backgroundColor = "green";_x000D_
   } else {_x000D_
     box.style.backgroundColor = "purple";_x000D_
   };_x000D_
 };
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes" onclick="Choice(this);">yes</button>_x000D_
<button id="no" onclick="Choice(this);">no</button>_x000D_
<button id="other" onclick="Choice(this);">other</button>
_x000D_
_x000D_
_x000D_

or event binding,

_x000D_
_x000D_
window.onload = function() {_x000D_
  var box = document.getElementById("box");_x000D_
  document.getElementById("yes").onclick = function() {_x000D_
    box.style.backgroundColor = "red";_x000D_
  }_x000D_
  document.getElementById("no").onclick = function() {_x000D_
    box.style.backgroundColor = "green";_x000D_
  }_x000D_
}
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes">yes</button>_x000D_
<button id="no">no</button>
_x000D_
_x000D_
_x000D_

How do I divide in the Linux console?

You should try to use:

echo "scale=4;$variablename/3"|bc

How to unescape a Java string literal in Java?

Java 13 added a method which does this: String#translateEscapes.

It was a preview feature in Java 13 and 14, but was promoted to a full feature in Java 15.

Up, Down, Left and Right arrow keys do not trigger KeyDown event

protected override bool IsInputKey(Keys keyData)
{
    if (((keyData & Keys.Up) == Keys.Up)
        || ((keyData & Keys.Down) == Keys.Down)
        || ((keyData & Keys.Left) == Keys.Left)
        || ((keyData & Keys.Right) == Keys.Right))
        return true;
    else
        return base.IsInputKey(keyData);
}

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

Essentially you want to add code to the Calculate event of the relevant Worksheet.

In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.

Alternatively, copy the code below into the editor of the sheet you want to use:

Private Sub Worksheet_Calculate()

If Sheets("MySheet").Range("A1").Value > 0.5 Then
    MsgBox "Over 50%!", vbOKOnly
End If

End Sub

This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.

android : Error converting byte to dex

For some reasons, @ChintanSoni's answer didn't worked. I tried deleting the build folder manually but couldn't delete some files since they were being used by some process. Cleaning and re-building the project didn't help so I opened task manager, selected JAVA(TM) Platform SE binary and pressed on 'End task`.

Then I tried to run the project once again and it started compiling fine.

How might I convert a double to the nearest integer value?

I'm developing a scientific calculator that sports an Int button. I've found the following is a simple, reliable solution:

double dblInteger;
if( dblNumber < 0 )
   dblInteger = Math.Ceiling(dblNumber);
else
   dblInteger = Math.Floor(dblNumber);

Math.Round sometimes produces unexpected or undesirable results, and explicit conversion to integer (via cast or Convert.ToInt...) often produces wrong values for higher-precision numbers. The above method seems to always work.

Disabling Minimize & Maximize On WinForm?

Right Click the form you want to hide them on, choose Controls -> Properties.

In Properties, set

  • Control Box -> False
  • Minimize Box -> False
  • Maximize Box -> False

You'll do this in the designer.

Removing u in list

[u'{email:[email protected],gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test1,gem:0}']

'u' denotes unicode characters. We can easily remove this with map function on the final list element

map(str, test)

Another way is when you are appending it to the list

test.append(str(a))

Why use HttpClient for Synchronous Connection

In my case the accepted answer did not work. I was calling the API from an MVC application which had no async actions.

This is how I managed to make it work:

private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static T RunSync<T>(Func<Task<T>> func)
    {           
        CultureInfo cultureUi = CultureInfo.CurrentUICulture;
        CultureInfo culture = CultureInfo.CurrentCulture;
        return _myTaskFactory.StartNew<Task<T>>(delegate
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = cultureUi;
            return func();
        }).Unwrap<T>().GetAwaiter().GetResult();
    }

Then I called it like this:

Helper.RunSync(new Func<Task<ReturnTypeGoesHere>>(async () => await AsyncCallGoesHere(myparameter)));

Gradle: Could not determine java version from '11.0.2'

I ran into the same issue in Ubuntu 18.04.3 LTS. In my case, apt installed gradle version 4.4.1. The already-install java version was 11.0.4

The build message I got was

Could not determine java version from '11.0.4'.

At the time, most of the online docs referenced gradle version 5.6, so I did the following:

sudo add-apt-repository ppa:cwchien/gradle
sudo apt update
sudo apt upgrade gradle

Then I repeated the project initialiation (using "gradle init" with the defaults). After that, "./gradlew build" worked correctly.

I later read a comment regarding a change in format of the output from "java --version" that caused gradle to break, which was fixed in a later version of gradle.

Gerrit error when Change-Id in commit messages are missing

1) gitdir=$(git rev-parse --git-dir);

2) scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg ${gitdir}/hooks/

a) I don't know how to execute step 1 in windows so skipped it and used hardcoded path in step 2 scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg .git/hooks/

b) In case you get below error, manually create "hooks" directory in .git folder

protocol error: expected control record

c) if you have submodule let's say "XX" then you need to repeat step 2 there as well and this time replace ${gitdir} with that submodules path

d) In case scp is not recognized by windows give full path of scp

"C:\Program Files\Git\usr\bin\scp.exe"

e) .git folder is present in your project repo and it's hidden folder

How to avoid the "divide by zero" error in SQL?

EDIT: I'm getting a lot of downvotes on this recently...so I thought I'd just add a note that this answer was written before the question underwent it's most recent edit, where returning null was highlighted as an option...which seems very acceptable. Some of my answer was addressed to concerns like that of Edwardo, in the comments, who seemed to be advocating returning a 0. This is the case I was railing against.

ANSWER: I think there's an underlying issue here, which is that division by 0 is not legal. It's an indication that something is fundementally wrong. If you're dividing by zero, you're trying to do something that doesn't make sense mathematically, so no numeric answer you can get will be valid. (Use of null in this case is reasonable, as it is not a value that will be used in later mathematical calculations).

So Edwardo asks in the comments "what if the user puts in a 0?", and he advocates that it should be okay to get a 0 in return. If the user puts zero in the amount, and you want 0 returned when they do that, then you should put in code at the business rules level to catch that value and return 0...not have some special case where division by 0 = 0.

That's a subtle difference, but it's important...because the next time someone calls your function and expects it to do the right thing, and it does something funky that isn't mathematically correct, but just handles the particular edge case it's got a good chance of biting someone later. You're not really dividing by 0...you're just returning an bad answer to a bad question.

Imagine I'm coding something, and I screw it up. I should be reading in a radiation measurement scaling value, but in a strange edge case I didn't anticipate, I read in 0. I then drop my value into your function...you return me a 0! Hurray, no radiation! Except it's really there and it's just that I was passing in a bad value...but I have no idea. I want division to throw the error because it's the flag that something is wrong.

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

You are missing setter for salt property as indicated by the exception

Please add the setter as

 public void setSalt(long salt) {
      this.salt=salt;
 }

Multi column forms with fieldsets

There are a couple of things that need to be adjusted in your layout:

  1. You are nesting col elements within form-group elements. This should be the other way around (the form-group should be within the col-sm-xx element).

  2. You should always use a row div for each new "row" in your design. In your case, you would need at least 5 rows (Username, Password and co, Title/First/Last name, email, Language). Otherwise, your problematic .col-sm-12 is still on the same row with the above 3 .col-sm-4 resulting in a total of columns greater than 12, and causing the overlap problem.

Here is a fixed demo.

And an excerpt of what the problematic section HTML should become:

<fieldset>
    <legend>Personal Information</legend>
    <div class='row'>
        <div class='col-sm-4'>    
            <div class='form-group'>
                <label for="user_title">Title</label>
                <input class="form-control" id="user_title" name="user[title]" size="30" type="text" />
            </div>
        </div>
        <div class='col-sm-4'>
            <div class='form-group'>
                <label for="user_firstname">First name</label>
                <input class="form-control" id="user_firstname" name="user[firstname]" required="true" size="30" type="text" />
            </div>
        </div>
        <div class='col-sm-4'>
            <div class='form-group'>
                <label for="user_lastname">Last name</label>
                <input class="form-control" id="user_lastname" name="user[lastname]" required="true" size="30" type="text" />
            </div>
        </div>
    </div>
    <div class='row'>
        <div class='col-sm-12'>
            <div class='form-group'>

                <label for="user_email">Email</label>
                <input class="form-control required email" id="user_email" name="user[email]" required="true" size="30" type="text" />
            </div>
        </div>
    </div>
</fieldset>

Edit a text file on the console using Powershell

Well there are thousand ways to edit a Text file on windows 7. Usually people Install Sublime , Atom and Notepad++ as an editor. For command line , I think the Basic Edit command (by the way which does not work on 64 bit computers) is good;Alternatively I find type con > filename as a very Applaudable method.If windows is newly installed and One wants to avoid Notepad. This might be it!! The perfect usage of Type as an editor :)

reference of the Image:- https://www.codeproject.com/Articles/34280/How-to-Write-Applet-Code

Assign command output to variable in batch file

A method has already been devised, however this way you don't need a temp file.

for /f "delims=" %%i in ('command') do set output=%%i

However, I'm sure this has its own exceptions and limitations.

How do I find out if first character of a string is a number?

Character.isDigit(string.charAt(0))

Note that this will allow any Unicode digit, not just 0-9. You might prefer:

char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');

Or the slower regex solutions:

s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")

However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.

To make the entire condition one line and avoid length checks, you can alter the regexes to the following:

s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")

If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Since you are running it in servlet, you need to have the jar accessible by the servlet container. You either include the connector as part of your application war or put it as part of the servlet container's extended library and datasource management stuff, if it has one. The second part is totally depend on the container that you have.

Copying and pasting data using VBA code

'So from this discussion i am thinking this should be the code then.

Sub Button1_Click()
    Dim excel As excel.Application
    Dim wb As excel.Workbook
    Dim sht As excel.Worksheet
    Dim f As Object

    Set f = Application.FileDialog(3)
    f.AllowMultiSelect = False
    f.Show

    Set excel = CreateObject("excel.Application")
    Set wb = excel.Workbooks.Open(f.SelectedItems(1))
    Set sht = wb.Worksheets("Data")

    sht.Activate
    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues


    wb.Close
End Sub

'Let me know if this is correct or a step was missed. Thx.

Returning a C string from a function

Your function prototype states your function will return a char. Thus, you can't return a string in your function.

How to parse Excel (XLS) file in Javascript/HTML5

var excel=new ActiveXObject("Excel.Application"); var book=excel.Workbooks.Open(your_full_file_name_here.xls); var sheet=book.Sheets.Item(1); var value=sheet.Range("A1");

when you have the sheet. You could use VBA functions as you do in Excel.

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Use this function which suits every situation.

CREATE FUNCTION dbo.fnNumPadLeft (@input INT, @pad tinyint)
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @NumStr VARCHAR(250)

    SET @NumStr = LTRIM(@input)

    IF(@pad > LEN(@NumStr))
        SET @NumStr = REPLICATE('0', @Pad - LEN(@NumStr)) + @NumStr;

    RETURN @NumStr;
END

Sample output

SELECT [dbo].[fnNumPadLeft] (2016,10) -- returns 0000002016
SELECT [dbo].[fnNumPadLeft] (2016,5) -- returns 02016
SELECT [dbo].[fnNumPadLeft] (2016,2) -- returns 2016
SELECT [dbo].[fnNumPadLeft] (2016,0) -- returns 2016 

How to check if an environment variable exists and get its value?

There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.

You can check if a variable is defined:

if [ -z "$a" ]
then
    echo "not defined"
else 
    echo "defined"
fi

and then set a default value for undefined variables or do something else.

The -z checks for a zero-length (i.e. empty) string. See man bash and look for the CONDITIONAL EXPRESSIONS section.

You can also use set -u at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.

Sleep/Wait command in Batch

ping localhost -n (your time) >nul

example

@echo off
title Test
echo hi
ping localhost -n 3 >nul && :: will wait 3 seconds before going next command (it will not display)
echo bye! && :: still wont be any spaces (just below the hi command)
ping localhost -n 2 >nul && :: will wait 2 seconds before going to next command (it will not display)
@exit

how to read xml file from url using php

Your code seems right, check if you have fopen wrappers enabled (allow_url_fopen = On on php.ini)

Also, as mentioned by other answers, you should provide a properly encoded URI or encode it using urlencode() function. You should also check if there is any error fetching the XML string and if there is any parsing error, which you can output using libxml_get_errors() as follows:

<?php
if (($response_xml_data = file_get_contents($map_url))===false){
    echo "Error fetching XML\n";
} else {
   libxml_use_internal_errors(true);
   $data = simplexml_load_string($response_xml_data);
   if (!$data) {
       echo "Error loading XML\n";
       foreach(libxml_get_errors() as $error) {
           echo "\t", $error->message;
       }
   } else {
      print_r($data);
   }
}
?>

If the problem is you can't fetch the XML code maybe it's because you need to include some custom headers in your request, check how to use stream_context_create() to create a custom stream context for use when calling file_get_contents() on example 4 at http://php.net/manual/en/function.file-get-contents.php

Border in shape xml

If you want make a border in a shape xml. You need to use:

For the external border,you need to use:

<stroke/>

For the internal background,you need to use:

<solid/>

If you want to set corners,you need to use:

<corners/>

If you want a padding betwen border and the internal elements,you need to use:

<padding/>

Here is a shape xml example using the above items. It works for me

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="2dp" android:color="#D0CFCC" /> 
  <solid android:color="#F8F7F5" /> 
  <corners android:radius="10dp" />
  <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" />
</shape>

How can I align text in columns using Console.WriteLine?

You could use tabs instead of spaces between columns, and/or set maximum size for a column in format strings ...

How to set initial value and auto increment in MySQL?

Alternatively, If you are too lazy to write the SQL query. Then this solution is for you. enter image description here

  1. Open phpMyAdmin
  2. Select desired Table
  3. Click on Operations tab
  4. Set your desired initial Value for AUTO_INCREMENT
  5. Done..!

Sorting a Python list by two fields

list1 = sorted(csv1, key=lambda x: (x[1], x[2]) )

Text that shows an underline on hover

You just need to specify text-decoration: underline; with pseudo-class :hover.

HTML

<span class="underline-on-hover">Hello world</span>

CSS

.underline-on-hover:hover {
    text-decoration: underline;
}

I have whipped up a working Code Pen Demo.

How to select first parent DIV using jQuery?

Use .closest(), which gets the first ancestor element that matches the given selector 'div':

var classes = $(this).closest('div').attr('class').split(' ');

EDIT:

As @Shef noted, .closest() will return the current element if it happens to be a DIV also. To take that into account, use .parent() first:

var classes = $(this).parent().closest('div').attr('class').split(' ');

Python: "Indentation Error: unindent does not match any outer indentation level"

It's possible that you have mixed tabs and spaces in your file. You can have python help check for such errors with

python -m tabnanny <name of python file>

'cannot find or open the pdb file' Visual Studio C++ 2013

Try go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically.

PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for.[...]

See Cannot find or open the PDB file in Visual Studio C++ 2010

Cannot change column used in a foreign key constraint

When you set keys (primary or foreign) you are setting constraints on how they can be used, which in turn limits what you can do with them. If you really want to alter the column, you could re-create the table without the constraints, although I'd recommend against it. Generally speaking, if you have a situation in which you want to do something, but it is blocked by a constraint, it's best resolved by changing what you want to do rather than the constraint.

Install msi with msiexec in a Specific Directory

In my case all of them did not work and finally it was

msiexec /i "msinamebla.msi" INSTALLFOLDER="C:\test\" /qb

I checked the log.txt as described by ezzadeen and found "INSTALLFOLDER" in there.

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

For many it's a permission issue, but for me it turns out the error was brought about by a mistake in the form I was trying to submit. To be specific i had accidentally put a "greater than" sign after the value of "action". So I would suggest you take a second look at your code.

CSS Flex Box Layout: full-width row and columns

Just use another container to wrap last two divs. Don't forget to use CSS prefixes.

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
   display: flex;_x000D_
   flex-direction: column;_x000D_
   height: 600px;_x000D_
   width: 580px;_x000D_
   background-color: rgb(240, 240, 240);_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
   height: 100px;_x000D_
   background-color: rgb(200, 200, 200);_x000D_
}_x000D_
_x000D_
#anotherContainer{_x000D_
   display: flex;_x000D_
   height: 100%;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
   background-color: red;_x000D_
   flex: 4;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
   background-color: blue;_x000D_
   flex: 1;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
   <div id="productShowcaseTitle">1</div>_x000D_
   <div id="anotherContainer">_x000D_
      <div id="productShowcaseDetail">2</div>_x000D_
      <div id="productShowcaseThumbnailContainer">3</div>_x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Save multiple sheets to .pdf

In Excel 2013 simply select multiple sheets and do a "Save As" and select PDF as the file type. The multiple pages will open in PDF when you click save.

How to analyse the heap dump using jmap in java

If you just run jmap -histo:live or jmap -histo, it outputs the contents on the console!

Cannot edit in read-only editor VS Code

I received this error during a code compare with previous version and it wasn't letting me edit the current version in the Right-Window. Unrelated to what I suspect OP's issue but this was the first thread that came up for my search and the error was the same. anyway...

My issue was that the particular file was 'Staged' in my source control at the time. This appears to restrict editing by opening an 'index' version for the compare.

Solution: Un-stage the file, and reopen the comparative window.

Selecting non-blank cells in Excel with VBA

This might be completely off base, but can't you just copy the whole column into a new spreadsheet and then sort the column? I'm assuming that you don't need to maintain the order integrity.

What does "exited with code 9009" mean during this build?

At least in Visual Studio Ultimate 2013, Version 12.0.30723.00 Update 3, it's not possible to separate an if/else statement with a line break:

works:

if '$(BuildingInsideVisualStudio)' == 'true' (echo local) else (echo server)

doesn't work:

if '$(BuildingInsideVisualStudio)' == 'true' (echo local) 
else (echo server)

Iterate over object in Angular

There's another way to loop over objects, using structural directives:

I prefer this approach because it "feels" most like the normal ngFor loop. :-)

(In this case for example I added Angular's context variables let i = index | even | odd | first | last | count) that are accessible inside my loop).

@Directive({
  selector: '[ngForObj]'
})
export class NgForObjDirective implements OnChanges {

  @Input() ngForObjOf: { [key: string]: any };

  constructor(private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef) { }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.ngForObjOf && changes.ngForObjOf.currentValue) {
      // remove all views
      this.viewContainerRef.clear();

      // create a new view for each property
      const propertyNames = Object.keys(changes.ngForObjOf.currentValue);
      const count = propertyNames.length;

      propertyNames.forEach((key: string, index: number) => {
        const even = ((index % 2) === 0);
        const odd = !even;
        const first = (index === 0);
        const last = index === (count - 1);

        this.viewContainerRef.createEmbeddedView(this.templateRef, {
          $implicit: changes.ngForObjOf.currentValue[key],
          index,
          even,
          odd,
          count,
          first,
          last
        });
      });
    }
  }
}

Usage in your template:

<ng-container *ngForObj="let item of myObject; let i = index"> ... </ng-container>

And if you want to loop using an integer value, you can use this directive:

@Directive({
   selector: '[ngForInt]'
})
export class NgForToDirective implements OnChanges {

  @Input() ngForIntTo: number;
 
  constructor(private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef) {

  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.ngForIntTo && changes.ngForIntTo.currentValue) {
      // remove all views
      this.viewContainerRef.clear();

      let currentValue = parseInt(changes.ngForIntTo.currentValue);
      for (let index = 0; index < currentValue; index++) {
        this.viewContainerRef.createEmbeddedView(this.templateRef, {
          $implicit: index,
          index
        });
      }

    }

  }
}

Usage in your template (example: loop from 0 to 14 (= 15 iterations):

<ng-container *ngForInt="let x to 15"> ... </ng-container>

Double border with different color

Use of pseudo-element as suggested by Terry has one PRO and one CON:

  1. PRO - great cross-browser compatibility because pseudo-element are supported also on older IE.
  2. CON - it requires to create an extra (even if generated) element, that infact is defined pseudo-element.

Anyway is a great solution.


OTHER SOLUTIONS:

If you can accept compatibility since IE9 (IE8 does not have support for this), you can achieve desired result in other two possible ways:

  1. using outline property combined with border and a single inset box-shadow
  2. using two box-shadow combined with border.

Here a jsFiddle with Terry's modified code that shows, side by side, these other possible solutions. Main specific properties for each one are the following (others are shared in .double-border class):

.left
{
  outline: 4px solid #fff;
  box-shadow:inset 0 0 0 4px #fff;
}

.right
{
  box-shadow:0 0 0 4px #fff, inset 0 0 0 4px #fff;
}

LESS code:

You asked for possible advantages about using a pre-processor like LESS. I this specific case, utility is not so great, but anyway you could optimize something, declaring colors and border/ouline/shadow with @variable.

Here an example of my CSS code, declared in LESS (changing colors and border-width becomes very quick):

@double-border-size:4px;
@inset-border-color:#fff;
@content-color:#ccc;

.double-border 
{
  background-color: @content-color;
  border: @double-border-size solid @content-color;
  padding: 2em;
  width: 16em;
  height: 16em;
  float:left;
  margin-right:20px;
  text-align:center;
}

.left
{
  outline: @double-border-size solid @inset-border-color;
  box-shadow:inset 0 0 0 @double-border-size @inset-border-color;
}

.right
{
  box-shadow:0 0 0 @double-border-size @inset-border-color, inset 0 0 0 @double-border-size @inset-border-color;
}

Request format is unrecognized for URL unexpectedly ending in

a WebMethod which requires a ContextKey,

[WebMethod]
public string[] GetValues(string prefixText, int count, string contextKey)

when this key is not set, got the exception.

Fixing it by assigning AutoCompleteExtender's key.

ac.ContextKey = "myKey";

css display table cell requires percentage width

You just need to add 'table-layout: fixed;'

.table {
   display: table;
   height: 100px;
   width: 100%;
   table-layout: fixed;
}

http://www.w3schools.com/cssref/pr_tab_table-layout.asp

MySQL "Group By" and "Order By"

Do a GROUP BY after the ORDER BY by wrapping your query with the GROUP BY like this:

SELECT t.* FROM (SELECT * FROM table ORDER BY time DESC) t GROUP BY t.from

Change the color of cells in one column when they don't match cells in another column

you could try this:

I have these two columns (column "A" and column "B"). I want to color them when the values between cells in the same row mismatch.

Follow these steps:

  1. Select the elements in column "A" (excluding A1);

  2. Click on "Conditional formatting -> New Rule -> Use a formula to determine which cells to format";

  3. Insert the following formula: =IF(A2<>B2;1;0);

  4. Select the format options and click "OK";

  5. Select the elements in column "B" (excluding B1) and repeat the steps from 2 to 4.

Using setImageDrawable dynamically to set image in an ImageView

If You cannot get Resources object like this in a class which is not an Activity, you have to add getContext() method for getResources() for example

ImageView image = (ImageView) v.findViewById(R.id.item_image);
int id = getContext().getResources().getIdentifier(imageName, "drawable", getContext().getPackageName());
image.setImageResource(id);

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

The answer is to not use a regular expression. This is sets and counting.

Regular expressions are about order.

In your life as a programmer you will asked to do many things that do not make sense. Learn to dig a level deeper. Learn when the question is wrong.

The question (if it mentioned regular expressions) is wrong.

Pseudocode (been switching between too many languages, of late):

if s.length < 8:
    return False
nUpper = nLower = nAlphanum = nSpecial = 0
for c in s:
    if isUpper(c):
        nUpper++
    if isLower(c):
        nLower++
    if isAlphanumeric(c):
        nAlphanum++
    if isSpecial(c):
        nSpecial++
return (0 < nUpper) and (0 < nAlphanum) and (0 < nSpecial)

Bet you read and understood the above code almost instantly. Bet you took much longer with the regex, and are less certain it is correct. Extending the regex is risky. Extended the immediate above, much less so.

Note also the question is imprecisely phrased. Is the character set ASCII or Unicode, or ?? My guess from reading the question is that at least one lowercase character is assumed. So I think the assumed last rule should be:

return (0 < nUpper) and (0 < nLower) and (0 < nAlphanum) and (0 < nSpecial)

(Changing hats to security-focused, this is a really annoying/not useful rule.)

Learning to know when the question is wrong is massively more important than clever answers. A clever answer to the wrong question is almost always wrong.

Getting Index of an item in an arraylist;

You could implement hashCode/equals of your AuctionItem so that two of them are equal if they have the same name. When you do this you can use the methods indexOf and contains of the ArrayList like this: arrayList.indexOf(new AuctionItem("The name")). Or when you assume in the equals method that a String is passed: arrayList.indexOf("The name"). But that's not the best design.

But I would also prefer using a HashMap to map the name to the item.

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

How to compare two dates?

Use time

Let's say you have the initial dates as strings like these:
date1 = "31/12/2015"
date2 = "01/01/2016"

You can do the following:
newdate1 = time.strptime(date1, "%d/%m/%Y") and newdate2 = time.strptime(date2, "%d/%m/%Y") to convert them to python's date format. Then, the comparison is obvious:

newdate1 > newdate2 will return False
newdate1 < newdate2 will return True

How to get row count in sqlite using Android?

c.getCount() returns 1 because the cursor contains a single row (the one with the real COUNT(*)). The count you need is the int value of first row in cursor.

public int getTaskCount(long tasklist_Id) {

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor= db.rawQuery(
        "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
         new String[] { String.valueOf(tasklist_Id) }
    );
    int count = 0;
    if(null != cursor)
        if(cursor.getCount() > 0){
          cursor.moveToFirst();    
          count = cursor.getInt(0);
        }
        cursor.close();
    }

    db.close();
    return count;
}   

What is the difference between MySQL, MySQLi and PDO?

mysqli is the enhanced version of mysql.

PDO extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions.

undefined reference to `WinMain@16'

My situation was that I did not have a main function.

Java - get index of key in HashMap?

Posting this as an equally viable alternative to @Binil Thomas's answer - tried to add it as a comment, but was not convinced of the readability of it all.

int index = 0;

for (Object key : map.keySet()) {
   Object value = map.get(key);
   ++index;
}

Probably doesn't help the original question poster since this is the literal situation they were trying to avoid, but may aid others searching for an easy answer.

IIS w3svc error

Make sure these 2 services running and their startup type is automatic.If they disabled and not running right click on them and go to properties and change from there.

  1. Windows process activation service
  2. Worldwide web publishing service.

How to import other Python files?

In case the module you want to import is not in a sub-directory, then try the following and run app.py from the deepest common parent directory:

Directory Structure:

/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json

In app.py, append path of client to sys.path:

import os, sys, inspect

sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()

Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)

# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")

Run

user@host:/path/to/common_dir$ python3 application/app.py

This solution works for me in cli, as well as PyCharm.

Changing three.js background to transparent or other color

I'd also like to add that if using the three.js editor don't forget to set the background colour to clear as well in the index.html.

background-color:#00000000

adding child nodes in treeview

I needed to do something similar and came across the same issues. I used the AfterSelect event to make sure I wasn't getting the previously selected node.

It's actually really easy to reference the correct node to receive the new child node.

private void TreeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
   //show dialogbox to let user name the new node
   frmDialogInput f = new frmDialogInput();
   f.ShowDialog();

    //find the node that was selected
    TreeNode myNode = TreeView1.SelectedNode;
    //create the new node to add
    TreeNode newNode = new TreeNode(f.EnteredText);
    //add the new child to the selected node
    myNode.Nodes.Add(newNode);
}

Using CRON jobs to visit url?

you can use this for url with parameters:

lynx -dump "http://vps-managed.com/tasks.php?code=23456"

lynx is available on all systems by default.

How do I exit the Vim editor?

Once you have made your choice of the exit command, press enter to finally quit Vim and close the editor (but not the terminal).

Do note that when you press shift + “:” the editor will have the next keystrokes displayed at the bottom left of the terminal. Now if you want to simply quit, write exit or wq (save and exit)

How to ignore a particular directory or file for tslint?

There are others who encountered the problem. Unfortunately, there is only an open issue for excluding files: https://github.com/palantir/tslint/issues/73

So I'm afraid the answer is no.

How to get key names from JSON using jq

Here's another way of getting a Bash array with the example JSON given by @anubhava in his answer:

arr=($(jq --raw-output 'keys_unsorted | @sh' file.json))

echo ${arr[0]}    # 'Archiver-Version'
echo ${arr[1]}    # 'Build-Id'
echo ${arr[2]}    # 'Build-Jdk'

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

after studying above that package name in manifest file and application id in gradle build file should be same. my issue didn't resolved.

Actually your application id in gradle build file should be same as your package name in google-services.json file. if your google-services.json file has different package name. delete that app from google analytics or firebase console. and get a new file.

Simulating a click in jQuery/JavaScript on a link

Try this

function submitRequest(buttonId) {
    if (document.getElementById(buttonId) == null
            || document.getElementById(buttonId) == undefined) {
        return;
    }
    if (document.getElementById(buttonId).dispatchEvent) {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById(buttonId).dispatchEvent(e);
    } else {
        document.getElementById(buttonId).click();
    }
}

and you can use it like

submitRequest("target-element-id");

Best way to work with dates in Android SQLite

Best way to store datein SQlite DB is to store the current DateTimeMilliseconds. Below is the code snippet to do so_

  1. Get the DateTimeMilliseconds
public static long getTimeMillis(String dateString, String dateFormat) throws ParseException {
    /*Use date format as according to your need! Ex. - yyyy/MM/dd HH:mm:ss */
    String myDate = dateString;//"2017/12/20 18:10:45";
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);
    Date date = sdf.parse(myDate);
    long millis = date.getTime();

    return millis;
}
  1. Insert the data in your DB
public void insert(Context mContext, long dateTimeMillis, String msg) {
    //Your DB Helper
    MyDatabaseHelper dbHelper = new MyDatabaseHelper(mContext);
    database = dbHelper.getWritableDatabase();

    ContentValues contentValue = new ContentValues();
    contentValue.put(MyDatabaseHelper.DATE_MILLIS, dateTimeMillis);
    contentValue.put(MyDatabaseHelper.MESSAGE, msg);

    //insert data in DB
    database.insert("your_table_name", null, contentValue);

   //Close the DB connection.
   dbHelper.close(); 

}

Now, your data (date is in currentTimeMilliseconds) is get inserted in DB .

Next step is, when you want to retrieve data from DB you need to convert the respective date time milliseconds in to corresponding date. Below is the sample code snippet to do the same_

  1. Convert date milliseconds in to date string.
public static String getDate(long milliSeconds, String dateFormat)
{
    // Create a DateFormatter object for displaying date in specified format.
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);

    // Create a calendar object that will convert the date and time value in milliseconds to date.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliSeconds);
    return formatter.format(calendar.getTime());
}
  1. Now, Finally fetch the data and see its working...
public ArrayList<String> fetchData() {

    ArrayList<String> listOfAllDates = new ArrayList<String>();
    String cDate = null;

    MyDatabaseHelper dbHelper = new MyDatabaseHelper("your_app_context");
    database = dbHelper.getWritableDatabase();

    String[] columns = new String[] {MyDatabaseHelper.DATE_MILLIS, MyDatabaseHelper.MESSAGE};
    Cursor cursor = database.query("your_table_name", columns, null, null, null, null, null);

    if (cursor != null) {

        if (cursor.moveToFirst()){
            do{
                //iterate the cursor to get data.
                cDate = getDate(cursor.getLong(cursor.getColumnIndex(MyDatabaseHelper.DATE_MILLIS)), "yyyy/MM/dd HH:mm:ss");

                listOfAllDates.add(cDate);

            }while(cursor.moveToNext());
        }
        cursor.close();

    //Close the DB connection.
    dbHelper.close(); 

    return listOfAllDates;

}

Hope this will help all! :)

Change Primary Key

You will need to drop and re-create the primary key like this:

alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

However, if there are other tables with foreign keys that reference this primary key, then you will need to drop those first, do the above, and then re-create the foreign keys with the new column list.

An alternative syntax to drop the existing primary key (e.g. if you don't know the constraint name):

alter table my_table drop primary key;

How do I find if a string starts with another string in Ruby?

puts 'abcdefg'.start_with?('abc')  #=> true

[edit] This is something I didn't know before this question: start_with takes multiple arguments.

'abcdefg'.start_with?( 'xyz', 'opq', 'ab')

Join String list elements with a delimiter in one step

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

Using CSS how to change only the 2nd column of a table

on this web http://quirksmode.org/css/css2/columns.html i found that easy way

<table>
<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />
<tr>..

Using a remote repository with non-standard port

SSH doesn't use the : syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config file and add:

Host git.host.de
  Port 4019

Then specify just git.host.de without a port number.

How to force link from iframe to be opened in the parent window

You can use any options

in case of only parent page:

if you want to open all link into parent page or parent iframe, then you use following code in head section of iframe:

<base target="_parent" />

OR

if you want to open a specific link into parent page or parent iframe, then you use following way:

<a target="_parent" href="http://specific.org">specific Link</a>
<a  href="http://normal.org">Normal Link</a>

OR

in case of nested iframe:

If want to open all link into browser window (redirect in browser url), then you use following code in head section of iframe:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
    $(window).load(function(){
        $("a").click(function(){
            top.window.location.href=$(this).attr("href");
            return true;
        })
    })
</script>

OR

if you want to open a specific link into browser window (redirect in browser url), then you use following way:

<a  href="http://specific.org"   target="_top" >specific Link</a>

or

<a  href="javascript:top.window.location.href='your_link'">specific Link</a>
<a  href="javascript:top.window.location.href='http://specific.org'">specific Link</a>
<a  href="http://normal.org">Normal Link</a>

How to decompile to java files intellij idea

The decompiler of IntelliJ IDEA was not built with this kind of usage in mind. It is only meant to help programmers peek at the bytecode of the java classes that they are developing. For decompiling lots of class files of which you do not have source code, you will need some other java decompiler, which is specialized for this job, and most likely runs standalone. If you google you should find a bunch.

Git mergetool generates unwanted .orig files

You have to be a little careful with using kdiff3 as while git mergetool can be configured to save a .orig file during merging, the default behaviour for kdiff3 is to also save a .orig backup file independently of git mergetool.

You have to make sure that mergetool backup is off:

git config --global mergetool.keepBackup false

and also that kdiff3's settings are set to not create a backup:

Configure/Options => Directory Merge => Backup Files (*.orig)

How to add subject alernative name to ssl certs?

When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR

keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com

complete example here: How to create CSR with SANs using keytool

What is the most efficient way to get first and last line of a text file?

with open(filename, "rb") as f:#Needs to be in binary mode for the seek from the end to work
    first = f.readline()
    if f.read(1) == '':
        return first
    f.seek(-2, 2)  # Jump to the second last byte.
    while f.read(1) != b"\n":  # Until EOL is found...
        f.seek(-2, 1)  # ...jump back the read byte plus one more.
    last = f.readline()  # Read last line.
    return last

The above answer is a modified version of the above answers which handles the case that there is only one line in the file

How to use hex color values

Just some addiotion to the first answer

(haven't cehcked the alpha, may need to add an if netHext > 0xffffff):

extension UIColor {

struct COLORS_HEX {
    static let Primary = 0xffffff
    static let PrimaryDark = 0x000000
    static let Accent = 0xe89549
    static let AccentDark = 0xe27b2a
    static let TextWhiteSemiTransparent = 0x80ffffff
}

convenience init(red: Int, green: Int, blue: Int, alphaH: Int) {
    assert(red >= 0 && red <= 255, "Invalid red component")
    assert(green >= 0 && green <= 255, "Invalid green component")
    assert(blue >= 0 && blue <= 255, "Invalid blue component")
    assert(alphaH >= 0 && alphaH <= 255, "Invalid alpha component")

    self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alphaH) / 255.0)
}

convenience init(netHex:Int) {
    self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff, alphaH: (netHex >> 24) & 0xff)
}

}

Add Favicon with React and Webpack

In my case -- I am running Visual Studio (Professional 2017) in debug mode with webpack 2.4.1 -- it was necessary to put the favicon.ico into the root directory of the project, right where the folder src is rather than in a folder public, even though according to https://create-react-app.dev/docs/using-the-public-folder the latter should be the official location.

select records from postgres where timestamp is in certain range

Search till the seconds for the timestamp column in postgress

select * from "TableName" e
    where timestamp >= '2020-08-08T13:00:00' and timestamp < '2020-08-08T17:00:00';

Determine which MySQL configuration file is being used

Some servers have multiple MySQL versions installed and configured. Make sure you are dealing with the correct version running with a Unix command of:

ps -ax | grep mysql

How to clear an ImageView in Android?

I was able to achieve this by defining a drawable (something like blank_white_shape.xml):

<shape xmlns:android="http://schemas.android.com/apk/res/android"       
       android:shape="rectangle">
    <solid android:color="@android:color/white"/>
</shape>

Then when I want to clear the image view I just call

 imageView.setImage(R.drawable.blank_white_shape);

This works beautifully for me!

Forward declaration of a typedef in C++

To "fwd declare a typedef" you need to fwd declare a class or a struct and then you can typedef declared type. Multiple identical typedefs are acceptable by compiler.

long form:

class MyClass;
typedef MyClass myclass_t;

short form:

typedef class MyClass myclass_t;

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I, too, have need for this! My situation involves comparing actuals with budget for cost centers, where expenses may have been mis-applied and therefore need to be re-allocated to the correct cost center so as to match how they were budgeted. It is very time consuming to try and scan row-by-row to see if each expense item has been correctly allocated. I decided that I should apply conditional formatting to highlight any cells where the actuals did not match the budget. I set up the conditional formatting to change the background color if the actual amount under the cost center did not match the budgeted amount.

Here's what I did:

Start in cell A1 (or the first cell you want to have the formatting). Open the Conditional Formatting dialogue box and select Apply formatting based on a formula. Then, I wrote a formula to compare one cell to another to see if they match:

=A1=A50

If the contents of cells A1 and A50 are equal, the conditional formatting will be applied. NOTICE: no $$, so the cell references are RELATIVE! Therefore, you can copy the formula from cell A1 and PasteSpecial (format). If you only click on the cells that you reference as you write your conditional formatting formula, the cells are by default locked, so then you wouldn't be able to apply them anywhere else (you would have to write out a new rule for each line- YUK!)

What is really cool about this is that if you insert rows under the conditionally formatted cell, the conditional formatting will be applied to the inserted rows as well!

Something else you could also do with this: Use ISBLANK if the amounts are not going to be exact matches, but you want to see if there are expenses showing up in columns where there are no budgeted amounts (i.e., BLANK) .

This has been a real time-saver for me. Give it a try and enjoy!

bootstrap responsive table content wrapping

So you can use the following :

td {
  white-space: normal !important; // To consider whitespace.
}

If this doesn't work:

td {
  white-space: normal !important; 
  word-wrap: break-word;  
}
table {
  table-layout: fixed;
}

Parsing JSON in Java without knowing JSON format

To get JSON quickly into Java objects (Maps) that you can then 'drill' and work with, you can use json-io (https://github.com/jdereg/json-io). This library will let you read in a JSON String, and get back a 'Map of Maps' representation.

If you have the corresponding Java classes in your JVM, you can read the JSON in and it will parse it directly into instances of the Java classes.

JsonReader.jsonToMaps(String json)

where json is the String containing the JSON to be read. The return value is a Map where the keys will contain the JSON fields, and the values will contain the associated values.

JsonReader.jsonToJava(String json) 

will read the same JSON string in, and the return value will be the Java instance that was serialized into the JSON. Use this API if you have the classes in your JVM that were written by

JsonWriter.objectToJson(MyClass foo).

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

I highly recommend underscore or lo-dash libraries:

http://underscorejs.org/#range

(Almost completely compatible, apparently lodash runs quicker but underscore has better doco IMHO)

_.range([start], stop, [step])

Both libraries have bunch of very useful utilities.

what are the .map files used for in Bootstrap 3.x?

From Working with CSS preprocessors in Chrome DevTools:

Many developers generate CSS style sheets using a CSS preprocessor, such as Sass, Less, or Stylus. Because the CSS files are generated, editing the CSS files directly is not as helpful.

For preprocessors that support CSS source maps, DevTools lets you live-edit your preprocessor source files in the Sources panel, and view the results without having to leave DevTools or refresh the page. When you inspect an element whose styles are provided by a generated CSS file, the Elements panel displays a link to the original source file, not the generated .css file.

sqlalchemy filter multiple columns

You can simply call filter multiple times:

query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
                                 filter(User.lastname.like(searchVar2))

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

WAMP Cannot access on local network 403 Forbidden

I got this answer from here. and its works for me

Require local

Change to

Require all granted
Order Deny,Allow
Allow from all

Find unique lines

I find this easier.

sort -u input_filename > output_filename

-u stands for unique.

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

Force IE10 to run in IE10 Compatibility View?

The X-UA-Compatible meta element only changes the Document mode, not the Browser mode. The Browser mode is chosen before the page is requested, so there is no way to include any markup, JavaScript or such to change this. While the Document mode falls back to older standards and quirks modes of the rendering engine, the Browser mode just changes things like how the browser identifies, such as the User Agent string.

If you’d like to change the Browser mode for all users (rather than changing it manually in the tools or through the settings), the only way (AFAICT) is to get your site added to Microsoft’s Copat View List. This is maintained by Microsoft to apply overrides to sites which break. There is information on how to remove your site from the compat view list, but none I can find to request that you're added.

The preferred method however is to try to fix any issues on the site first, as when you don’t run using the latest document and browser mode you can not take advantage of improvements in the browser, such as increased performance.

Instance member cannot be used on type

Your initial problem was:

class ReportView: NSView {
  var categoriesPerPage = [[Int]]()
  var numPages: Int = { return categoriesPerPage.count }
}

Instance member 'categoriesPerPage' cannot be used on type 'ReportView'

previous posts correctly point out, if you want a computed property, the = sign is errant.

Additional possibility for error:

If your intent was to "Setting a Default Property Value with a Closure or Function", you need only slightly change it as well. (Note: this example was obviously not intended to do that)

class ReportView: NSView {
  var categoriesPerPage = [[Int]]()
  var numPages: Int = { return categoriesPerPage.count }()
}

Instead of removing the =, we add () to denote a default initialization closure. (This can be useful when initializing UI code, to keep it all in one place.)

However, the exact same error occurs:

Instance member 'categoriesPerPage' cannot be used on type 'ReportView'

The problem is trying to initialize one property with the value of another. One solution is to make the initializer lazy. It will not be executed until the value is accessed.

class ReportView: NSView {
  var categoriesPerPage = [[Int]]()
  lazy var numPages: Int = { return categoriesPerPage.count }()
}

now the compiler is happy!

Powershell Log Off Remote Session

You can use Invoke-RDUserLogoff

An example logging off Active Directory users of a specific Organizational Unit:

$users = Get-ADUser -filter * -SearchBase "ou=YOUR_OU_NAME,dc=contoso,dc=com"

Get-RDUserSession | where { $users.sAMAccountName -contains $_.UserName } | % { $_ | Invoke-RDUserLogoff -Force }

At the end of the pipe, if you try to use only foreach (%), it will log off only one user. But using this combination of foreach and pipe:

| % { $_ | command }

will work as expected.

Ps. Run as Adm.

Click button copy to clipboard using jQuery

Update 2020: This solution uses execCommand. While that feature was fine at the moment of writing this answer, it is now considered obsolete. It will still work on many browsers, but its use is discouraged as support may be dropped.

There is another non-Flash way (apart from the Clipboard API mentioned in jfriend00's answer). You need to select the text and then execute the command copy to copy to the clipboard whatever text is currently selected on the page.

For example, this function will copy the content of the passed element into the clipboard (updated with suggestion in the comments from PointZeroTwo):

function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
}

This is how it works:

  1. Creates a temporarily hidden text field.
  2. Copies the content of the element to that text field.
  3. Selects the content of the text field.
  4. Executes the command copy like: document.execCommand("copy").
  5. Removes the temporary text field.

NOTE that the inner text of the element can contain whitespace. So if you want to use if for example for passwords you may trim the text by using $(element).text().trim() in the code above.

You can see a quick demo here:

_x000D_
_x000D_
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('#p1')">Copy P1</button>
<button onclick="copyToClipboard('#p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />
_x000D_
_x000D_
_x000D_

The main issue is that not all browsers support this feature at the moment, but you can use it on the main ones from:

  • Chrome 43
  • Internet Explorer 10
  • Firefox 41
  • Safari 10

Update 1: This can be achieved also with a pure JavaScript solution (no jQuery):

_x000D_
_x000D_
function copyToClipboard(elementId) {

  // Create a "hidden" input
  var aux = document.createElement("input");

  // Assign it the value of the specified element
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);

  // Append it to the body
  document.body.appendChild(aux);

  // Highlight its content
  aux.select();

  // Copy the highlighted text
  document.execCommand("copy");

  // Remove it from the body
  document.body.removeChild(aux);

}
_x000D_
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />
_x000D_
_x000D_
_x000D_

Notice that we pass the id without the # now.

As madzohan reported in the comments below, there is some strange issue with the 64-bit version of Google Chrome in some cases (running the file locally). This issue seems to be fixed with the non-jQuery solution above.

Madzohan tried in Safari and the solution worked but using document.execCommand('SelectAll') instead of using .select() (as specified in the chat and in the comments below).

As PointZeroTwo points out in the comments, the code could be improved so it would return a success/failure result. You can see a demo on this jsFiddle.


UPDATE: COPY KEEPING THE TEXT FORMAT

As a user pointed out in the Spanish version of StackOverflow, the solutions listed above work perfectly if you want to copy the content of an element literally, but they don't work that great if you want to paste the copied text with format (as it is copied into an input type="text", the format is "lost").

A solution for that would be to copy into a content editable div and then copy it using the execCommand in a similar way. Here there is an example - click on the copy button and then paste into the content editable box below:

_x000D_
_x000D_
function copy(element_id){
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.innerHTML = document.getElementById(element_id).innerHTML;
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)"); 
  document.body.appendChild(aux);
  aux.focus();
  document.execCommand("copy");
  document.body.removeChild(aux);
}
_x000D_
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
_x000D_
<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('demo')">Copy Keeping Format</button> 

<div id="target" contentEditable="true"></div>
_x000D_
_x000D_
_x000D_

And in jQuery, it would be like this:

_x000D_
_x000D_
function copy(selector){
  var $temp = $("<div>");
  $("body").append($temp);
  $temp.attr("contenteditable", true)
       .html($(selector).html()).select()
       .on("focus", function() { document.execCommand('selectAll',false,null); })
       .focus();
  document.execCommand("copy");
  $temp.remove();
}
_x000D_
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('#demo')">Copy Keeping Format</button> 

<div id="target" contentEditable="true"></div>
_x000D_
_x000D_
_x000D_

Refresh a page using JavaScript or HTML

You can also use

<input type="button" value = "Refresh" onclick="history.go(0)" />

It works fine for me.

Are dictionaries ordered in Python 3.6+?

Are dictionaries ordered in Python 3.6+?

They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior[1]).

As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:

Make it so. "Dict keeps insertion order" is the ruling. Thanks!

This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.


How does the Python 3.6 dictionary implementation perform better[2] than the older one while preserving element order?

Essentially, by keeping two arrays.

  • The first array, dk_entries, holds the entries (of type PyDictKeyEntry) for the dictionary in the order that they were inserted. Preserving order is achieved by this being an append only array where new items are always inserted at the end (insertion order).

  • The second, dk_indices, holds the indices for the dk_entries array (that is, values that indicate the position of the corresponding entry in dk_entries). This array acts as the hash table. When a key is hashed it leads to one of the indices stored in dk_indices and the corresponding entry is fetched by indexing dk_entries. Since only indices are kept, the type of this array depends on the overall size of the dictionary (ranging from type int8_t(1 byte) to int32_t/int64_t (4/8 bytes) on 32/64 bit builds)

In the previous implementation, a sparse array of type PyDictKeyEntry and size dk_size had to be allocated; unfortunately, it also resulted in a lot of empty space since that array was not allowed to be more than 2/3 * dk_size full for performance reasons. (and the empty space still had PyDictKeyEntry size!).

This is not the case now since only the required entries are stored (those that have been inserted) and a sparse array of type intX_t (X depending on dict size) 2/3 * dk_sizes full is kept. The empty space changed from type PyDictKeyEntry to intX_t.

So, obviously, creating a sparse array of type PyDictKeyEntry is much more memory demanding than a sparse array for storing ints.

You can see the full conversation on Python-Dev regarding this feature if interested, it is a good read.


In the original proposal made by Raymond Hettinger, a visualization of the data structures used can be seen which captures the gist of the idea.

For example, the dictionary:

d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}

is currently stored as [keyhash, key, value]:

entries = [['--', '--', '--'],
           [-8522787127447073495, 'barry', 'green'],
           ['--', '--', '--'],
           ['--', '--', '--'],
           ['--', '--', '--'],
           [-9092791511155847987, 'timmy', 'red'],
           ['--', '--', '--'],
           [-6480567542315338377, 'guido', 'blue']]

Instead, the data should be organized as follows:

indices =  [None, 1, None, None, None, 0, None, 2]
entries =  [[-9092791511155847987, 'timmy', 'red'],
            [-8522787127447073495, 'barry', 'green'],
            [-6480567542315338377, 'guido', 'blue']]

As you can visually now see, in the original proposal, a lot of space is essentially empty to reduce collisions and make look-ups faster. With the new approach, you reduce the memory required by moving the sparseness where it's really required, in the indices.


[1]: I say "insertion ordered" and not "ordered" since, with the existence of OrderedDict, "ordered" suggests further behavior that the dict object doesn't provide. OrderedDicts are reversible, provide order sensitive methods and, mainly, provide an order-sensive equality tests (==, !=). dicts currently don't offer any of those behaviors/methods.


[2]: The new dictionary implementations performs better memory wise by being designed more compactly; that's the main benefit here. Speed wise, the difference isn't so drastic, there's places where the new dict might introduce slight regressions (key-lookups, for example) while in others (iteration and resizing come to mind) a performance boost should be present.

Overall, the performance of the dictionary, especially in real-life situations, improves due to the compactness introduced.

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

How to set a Header field on POST a form?

It cannot be done - AFAIK.

However you may use for example jquery (although you can do it with plain javascript) to serialize the form and send (using AJAX) while adding your custom header.

Look at the jquery serialize which changes an HTML FORM into form-url-encoded values ready for POST.

UPDATE

My suggestion is to include either

  • a hidden form element
  • a query string parameter

How to parse JSON boolean value?

You can cast this value to a Boolean in a very simple manner: by comparing it with integer value 1, like this:

boolean multipleContacts = new Integer(1).equals(jsonObject.get("MultipleContacts"))

If it is a String, you could do this:

boolean multipleContacts = "1".equals(jsonObject.get("MultipleContacts"))

C# '@' before a String

What is this for and why would I use @":\" instead of ":\"?

Because when you have a long string with many \ you don't need to escape them all and the \n, \r and \f won't work too.

Javascript - removing undefined fields from an object

This one is easy to remember, but might be slow. Use jQuery to copy non-null properties to an empty object. No deep copy unless you add true as first argument.

myObj = $.extend({}, myObj);

Append Char To String in C?

If Linux is your concern, the easiest way to append two strings:

char * append(char * string1, char * string2)
{
    char * result = NULL;
    asprintf(&result, "%s%s", string1, string2);
    return result;
}

This won't work with MS Visual C.

Note: you have to free() the memory returned by asprintf()

Execute method on startup in Spring

For a file StartupHousekeeper.java located in package com.app.startup,

Do this in StartupHousekeeper.java:

@Component
public class StartupHousekeeper {

  @EventListener(ContextRefreshedEvent.class)
  public void keepHouse() {
    System.out.println("This prints at startup.");
  }
}

And do this in myDispatcher-servlet.java:

<?xml version="1.0" encoding="UTF-8"?>
<beans>

    <mvc:annotation-driven />
    <context:component-scan base-package="com.app.startup" />

</beans>

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I know this is an oldie, but thought I might add some value. For those of us running Server Core outside of a domain (domain members can just run Server Manager remotely to add/remove features/roles), you have to resort to command lines.

Powershell users can type "Install-WindowsFeature Web-Asp-Net45"

That should be equivalent to using server manager.

How to set image to fit width of the page using jsPDF?

This is how I've achieved in Reactjs.

Main problem were ratio and scale If you do a quick window.devicePixelRatio, it's default value is 2 which was causing the half image issue.

const printDocument = () => {
  const input = document.getElementById('divToPrint');
  const divHeight = input.clientHeight
  const divWidth = input.clientWidth
  const ratio = divHeight / divWidth;

  html2canvas(input, { scale: '1' }).then((canvas) => {
    const imgData = canvas.toDataURL('image/jpeg');
    const pdfDOC = new JSPDF("l", "mm", "a0"); //  use a4 for smaller page

    const width = pdfDOC.internal.pageSize.getWidth();
    let height = pdfDOC.internal.pageSize.getHeight();
    height = ratio * width;

    pdfDOC.addImage(imgData, 'JPEG', 0, 0, width - 20, height - 10);
    pdfDOC.save('summary.pdf');   //Download the rendered PDF.
  })
}

Validate decimal numbers in JavaScript - IsNumeric()

I realize this has been answered many times, but the following is a decent candidate which can be useful in some scenarios.

it should be noted that it assumes that '.42' is NOT a number, and '4.' is NOT a number, so this should be taken into account.

function isDecimal(x) {
  return '' + x === '' + +x;
}

function isInteger(x) {
  return '' + x === '' + parseInt(x);
}

The isDecimal passes the following test:

function testIsNumber(f) {
  return f('-1') && f('-1.5') && f('0') && f('0.42')
    && !f('.42') && !f('99,999') && !f('0x89f')
    && !f('#abcdef') && !f('1.2.3') && !f('') && !f('blah');
}

The idea here is that every number or integer has one "canonical" string representation, and every non-canonical representation should be rejected. So we cast to a number and back, and see if the result is the original string.

Whether these functions are useful for you depends on the use case. One feature is that distinct strings represent distinct numbers (if both pass the isNumber() test).

This is relevant e.g. for numbers as object property names.

var obj = {};
obj['4'] = 'canonical 4';
obj['04'] = 'alias of 4';
obj[4];  // prints 'canonical 4' to the console.

How SID is different from Service name in Oracle tnsnames.ora

Please see: http://www.sap-img.com/oracle-database/finding-oracle-sid-of-a-database.htm

What is the difference between Oracle SIDs and Oracle SERVICE NAMES. One config tool looks for SERVICE NAME and then the next looks for SIDs! What's going on?!

Oracle SID is the unique name that uniquely identifies your instance/database where as Service name is the TNS alias that you give when you remotely connect to your database and this Service name is recorded in Tnsnames.ora file on your clients and it can be the same as SID and you can also give it any other name you want.

SERVICE_NAME is the new feature from oracle 8i onwards in which database can register itself with listener. If database is registered with listener in this way then you can use SERVICE_NAME parameter in tnsnames.ora otherwise - use SID in tnsnames.ora.

Also if you have OPS (RAC) you will have different SERVICE_NAME for each instance.

SERVICE_NAMES specifies one or more names for the database service to which this instance connects. You can specify multiple services names in order to distinguish among different uses of the same database. For example:

SERVICE_NAMES = sales.acme.com, widgetsales.acme.com

You can also use service names to identify a single service that is available from two different databases through the use of replication.

In an Oracle Parallel Server environment, you must set this parameter for every instance.

In short: SID = the unique name of your DB instance, ServiceName = the alias used when connecting

Count number of rows per group and add result to original data frame

This should do your work :

df_agg <- aggregate(num~name+type,df,FUN=NROW)
names(df_agg)[3] <- "count"
df <- merge(df,df_agg,by=c('name','type'),all.x=TRUE)

Use Excel pivot table as data source for another Pivot Table

In a new sheet (where you want to create a new pivot table) press the key combination (Alt+D+P). In the list of data source options choose "Microsoft Excel list of database". Click Next and select the pivot table that you want to use as a source (select starting with the actual headers of the fields). I assume that this range is rather static and if you refresh the source pivot and it changes it's size you would have to re-size the range as well. Hope this helps.

Pan & Zoom Image

Try this Zoom Control: http://wpfextensions.codeplex.com

usage of the control is very simple, reference to the wpfextensions assembly than:

<wpfext:ZoomControl>
    <Image Source="..."/>
</wpfext:ZoomControl>

Scrollbars not supported at this moment. (It will be in the next release which will be available in one or two week).

socket.shutdown vs socket.close

Calling close and shutdown have two different effects on the underlying socket.

The first thing to point out is that the socket is a resource in the underlying OS and multiple processes can have a handle for the same underlying socket.

When you call close it decrements the handle count by one and if the handle count has reached zero then the socket and associated connection goes through the normal close procedure (effectively sending a FIN / EOF to the peer) and the socket is deallocated.

The thing to pay attention to here is that if the handle count does not reach zero because another process still has a handle to the socket then the connection is not closed and the socket is not deallocated.

On the other hand calling shutdown for reading and writing closes the underlying connection and sends a FIN / EOF to the peer regardless of how many processes have handles to the socket. However, it does not deallocate the socket and you still need to call close afterward.

if variable contains

If you have a lot of these to check you might want to store a list of the mappings and just loop over that, instead of having a bunch of if/else statements. Something like:

var CODE_TO_LOCATION = {
  'ST1': 'stoke central',
  'ST2': 'stoke north',
  // ...
};

function getLocation(text) {
  for (var code in CODE_TO_LOCATION) {
    if (text.indexOf(code) != -1) {
      return CODE_TO_LOCATION[code];
    }
  }
  return null;
}

This way you can easily add more code/location mappings. And if you want to handle more than one location you could just build up an array of locations in the function instead of just returning the first one you find.

Embedding DLLs in a compiled executable

Generally you would need some form of post build tool to perform an assembly merge like you are describing. There is a free tool called Eazfuscator (eazfuscator.blogspot.com/) which is designed for bytecode mangling that also handles assembly merging. You can add this into a post build command line with Visual Studio to merge your assemblies, but your mileage will vary due to issues that will arise in any non trival assembly merging scenarios.

You could also check to see if the build make untility NANT has the ability to merge assemblies after building, but I am not familiar enough with NANT myself to say whether the functionality is built in or not.

There are also many many Visual Studio plugins that will perform assembly merging as part of building the application.

Alternatively if you don't need this to be done automatically, there are a number of tools like ILMerge that will merge .net assemblies into a single file.

The biggest issue I've had with merging assemblies is if they use any similar namespaces. Or worse, reference different versions of the same dll (my problems were generally with the NUnit dll files).

How do I execute code AFTER a form has loaded?

This an old question and depends more upon when you need to start your routines. Since no one wants a null reference exception it is always best to check for null first then use as needed; that alone may save you a lot of grief.

The most common reason for this type of question is when a container or custom control type attempts to access properties initialized outside of a custom class where those properties have not yet been initialized thus potentially causing null values to populate and can even cause a null reference exceptions on object types. It means your class is running before it is fully initialized - before you have finished setting your properties etc. Another possible reason for this type of question is when to perform custom graphics.

To best answer the question about when to start executing code following the form load event is to monitor the WM_Paint message or hook directly in to the paint event itself. Why? The paint event only fires when all modules have fully loaded with respect to your form load event. Note: This.visible == true is not always true when it is set true so it is not used at all for this purpose except to hide a form.

The following is a complete example of how to start executing you code following the form load event. It is recommended that you do not unnecessarily tie up the paint message loop so we'll create an event that will start executing your code outside that loop.

using System.Windows.Forms;

namespace MyProgramStartingPlaceExample {

/// <summary>
/// Main UI form object
/// </summary>
public class Form1 : Form
{

    /// <summary>
    /// Main form load event handler
    /// </summary>
    public Form1()
    {
        // Initialize ONLY. Setup your controls and form parameters here. Custom controls should wait for "FormReady" before starting up too.
        this.Text = "My Program title before form loaded";
        // Size need to see text. lol
        this.Width = 420;

        // Setup the sub or fucntion that will handle your "start up" routine
        this.StartUpEvent += StartUPRoutine;

        // Optional: Custom control simulation startup sequence:
        // Define your class or control in variable. ie. var MyControlClass new CustomControl;
        // Setup your parameters only. ie. CustomControl.size = new size(420, 966); Do not validate during initialization wait until "FormReady" is set to avoid possible null values etc. 
        // Inside your control or class have a property and assign it as bool FormReady - do not validate anything until it is true and you'll be good! 
    }

    /// <summary>
    /// The main entry point for the application which sets security permissions when set.
    /// </summary>
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }


    #region "WM_Paint event hooking with StartUpEvent"            
    //
    // Create a delegate for our "StartUpEvent"
    public delegate void StartUpHandler();
    //
    // Create our event handle "StartUpEvent"
    public event StartUpHandler StartUpEvent;
    //
    // Our FormReady will only be set once just he way we intendded
    // Since it is a global variable we can poll it else where as well to determine if we should begin code execution !!
    bool FormReady;
    //
    // The WM_Paint message handler: Used mostly to paint nice things to controls and screen
    protected override void OnPaint(PaintEventArgs e)
    {
        // Check if Form is ready for our code ?
        if (FormReady == false) // Place a break point here to see the initialized version of the title on the form window
        {
            // We only want this to occur once for our purpose here.
            FormReady = true;
            //
            // Fire the start up event which then will call our "StartUPRoutine" below.
            StartUpEvent();
        }
        //
        // Always call base methods unless overriding the entire fucntion
        base.OnPaint(e);
    }
    #endregion


    #region "Your StartUp event Entry point"
    //
    // Begin executuing your code here to validate properties etc. and to run your program. Enjoy!
    // Entry point is just following the very first WM_Paint message - an ideal starting place following form load
    void StartUPRoutine()
    {
        // Replace the initialized text with the following
        this.Text = "Your Code has executed after the form's load event";
        //
        // Anyway this is the momment when the form is fully loaded and ready to go - you can also use these methods for your classes to synchronize excecution using easy modifications yet here is a good starting point. 
        // Option: Set FormReady to your controls manulaly ie. CustomControl.FormReady = true; or subscribe to the StartUpEvent event inside your class and use that as your entry point for validating and unleashing its code.
        //
        // Many options: The rest is up to you!
    }
    #endregion

}

}

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

After upgrading lots of packages (Spyder 3 to 4, Keras and Tensorflow and lots of their dependencies), I had the same problem today! I cannot figure out what happened; but the (conda-based) virtual environment that kept using Spyder 3 did not have the problem. Although installing tkinter or changing the backend, via matplotlib.use('TkAgg) as shown above, or this nice post on how to change the backend, might well resolve the problem, I don't see these as rigid solutions. For me, uninstalling matplotlib and reinstalling it was magic and the problem was solved.

pip uninstall matplotlib

... then, install

pip install matplotlib

From all the above, this could be a package management problem, and BTW, I use both conda and pip, whenever feasible.

Using DateTime in a SqlParameter for Stored Procedure, format error

How are you setting up the SqlParameter? You should set the SqlDbType property to SqlDbType.DateTime and then pass the DateTime directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).

You should be able to get the value into the DB. If not, here is a very simple example of how to do it:

static void Main(string[] args)
{
    // Create the connection.
    using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
    {
        // Open the connection.
        connection.Open();

        // Create the command.
        using (SqlCommand command = new SqlCommand("xsp_Test", connection))
        {
            // Set the command type.
            command.CommandType = System.Data.CommandType.StoredProcedure;

            // Add the parameter.
            SqlParameter parameter = command.Parameters.Add("@dt",
                System.Data.SqlDbType.DateTime);

            // Set the value.
            parameter.Value = DateTime.Now;

            // Make the call.
            command.ExecuteNonQuery();
        }
    }
}

I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.

If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the DateTime, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the DateTime struct will easily do).

All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the ToUniversalTime method, not by converting to a string) to the stored procedure.

And when you get the value back, call the ToLocalTime method to get the time in the local time zone.

How do I check if a string contains a specific word?

If you want to avoid the "falsey" and "truthy" problem, you can use substr_count:

if (substr_count($a, 'are') > 0) {
    echo "at least one 'are' is present!";
}

It's a bit slower than strpos but it avoids the comparison problems.

How do I do redo (i.e. "undo undo") in Vim?

Practically speaking, the :undolist is hard to use and Vim’s :earlier and :later time tracking of changes is only usable for course-grain fixes.

Given that, I resort to a plug-in that combines these features to provide a visual tree of browsable undos, called “Gundo.”

Obviously, this is something to use only when you need a fine-grained fix, or you are uncertain of the exact state of the document you wish to return to. See: Gundo. Graph your Vim undo tree in style

Get last record of a table in Postgres

you can use

SELECT timestamp, value, card 
FROM my_table 
ORDER BY timestamp DESC 
LIMIT 1

assuming you want also to sort by timestamp?

How do you setLayoutParams() for an ImageView?

An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view

Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'

The best way to do this:

ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);

How to repair COMException error 80040154?

WORKAROUND:

The possible workaround is modify your project's platform from 'Any CPU' to 'X86' (in Project's Properties, Build/Platform's Target)

ROOTCAUSE

The VSS Interop is a managed assembly using 32-bit Framework and the dll contains a 32-bit COM object. If you run this COM dll in 64 bit environment, you will get the error message.

How to know when a web page was last updated?

Take a look at archive.org

You can find almost everything about the past of a website there.

GitHub relative link in Markdown file

If you want a relative link to your wiki page on GitHub, use this:

Read here: [Some other wiki page](path/to/some-other-wiki-page)

If you want a link to a file in the repository, let us say, to reference some header file, and the wiki page is at the root of the wiki, use this:

Read here: [myheader.h](../tree/master/path/to/myheader.h)

The rationale for the last is to skip the "/wiki" path with "../", and go to the master branch in the repository tree without specifying the repository name, that may change in the future.

C++ "was not declared in this scope" compile error

grid is not present on nonrecursivecountcells's scope.

Either make grid a global array, or pass it as a parameter to the function.

Windows Forms ProgressBar: Easiest way to start/stop marquee?

Use a progress bar with the style set to Marquee. This represents an indeterminate progress bar.

myProgressBar.Style = ProgressBarStyle.Marquee;

You can also use the MarqueeAnimationSpeed property to set how long it will take the little block of color to animate across your progress bar.

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

To center it, you can use the technique shown here: Absolute centering.

To make it as big as possible, give it max-width and max-height of 100%.

To maintain the aspect ratio (even when the width is specifically set like in the snippet below), use object-fit as explained here.

_x000D_
_x000D_
.className {
    max-width: 100%;
    max-height: 100%;
    bottom: 0;
    left: 0;
    margin: auto;
    overflow: auto;
    position: fixed;
    right: 0;
    top: 0;
    -o-object-fit: contain;
    object-fit: contain;
}
_x000D_
<img src="https://i.imgur.com/HmezgW6.png" class="className" />

<!-- Slider to control the image width, only to make demo clearer !-->
<input type="range" min="10" max="2000" value="276" step="10" oninput="document.querySelector('img').style.width = (this.value +'px')" style="width: 90%; position: absolute; z-index: 2;" >
_x000D_
_x000D_
_x000D_

Passing the argument to CMAKE via command prompt

CMake 3.13 on Ubuntu 16.04

This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:

$ cat CMakeLists.txt 
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE ) 
    message("MY_VARIABLE evaluates to True")
endif()

$ mkdir build && cd build

$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

How can I set the request header for curl?

Sometimes changing the header is not enough, some sites check the referer as well:

curl -v \
     -H 'Host: restapi.some-site.com' \
     -H 'Connection: keep-alive' \
     -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
     -H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
     -e localhost \
     -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36' \
     'http://restapi.some-site.com/getsomething?argument=value&argument2=value'

In this example the referer (-e or --referer in curl) is 'localhost'.

Spring boot - Not a managed type

You either missed @Entity on class definition or you have explicit component scan path and this path does not contain your class

How to update a record using sequelize for node?

I did it like this:

Model.findOne({
    where: {
      condtions
    }
  }).then( j => {
    return j.update({
      field you want to update
    }).then( r => {
      return res.status(200).json({msg: 'succesfully updated'});
    }).catch(e => {
      return res.status(400).json({msg: 'error ' +e});
    })
  }).catch( e => {
    return res.status(400).json({msg: 'error ' +e});
  });

Can't compare naive and aware datetime.now() <= challenge.datetime_end

It is working form me. Here I am geeting the table created datetime and adding 10 minutes on the datetime. later depending on the current time, Expiry Operations are done.

from datetime import datetime, time, timedelta
import pytz

Added 10 minutes on database datetime

table_datetime = '2019-06-13 07:49:02.832969' (example)

# Added 10 minutes on database datetime
# table_datetime = '2019-06-13 07:49:02.832969' (example)

table_expire_datetime = table_datetime + timedelta(minutes=10 )

# Current datetime
current_datetime = datetime.now()


# replace the timezone in both time
expired_on = table_expire_datetime.replace(tzinfo=utc)
checked_on = current_datetime.replace(tzinfo=utc)


if expired_on < checked_on:
    print("Time Crossed)
else:
    print("Time not crossed ")

It worked for me.

Automatically create requirements.txt

You can use the following code to generate a requirements.txt file:

pip install pipreqs

pipreqs /path/to/project

more info related to pipreqs can be found here.

Sometimes you come across pip freeze, but this saves all packages in the environment including those that you don't use in your current project.