Programs & Examples On #Int64

Trying to merge 2 dataframes but get ValueError

@Arnon Rotem-Gal-Oz answer is right for the most part. But I would like to point out the difference between df['year']=df['year'].astype(int) and df.year.astype(int). df.year.astype(int) returns a view of the dataframe and doesn't not explicitly change the type, atleast in pandas 0.24.2. df['year']=df['year'].astype(int) explicitly change the type because it's an assignment. I would argue that this is the safest way to permanently change the dtype of a column.

Example:

df = pd.DataFrame({'Weed': ['green crack', 'northern lights', 'girl scout cookies'], 'Qty':[10,15,3]}) df.dtypes

Weed object, Qty int64

df['Qty'].astype(str) df.dtypes

Weed object, Qty int64

Even setting the inplace arg to True doesn't help at times. I don't know why this happens though. In most cases inplace=True equals an explicit assignment.

df['Qty'].astype(str, inplace = True) df.dtypes

Weed object, Qty int64

Now the assignment,

df['Qty'] = df['Qty'].astype(str) df.dtypes

Weed object, Qty object

iOS Swift - Get the Current Local Time and Date Timestamp

When we convert a UTC timestamp (2017-11-06 20:15:33 -08:00) into a Date object, the time zone is zeroed out to GMT. For calculating time intervals, this isn't an issue, but it can be for rendering times in the UI.

I favor the RFC3339 format (2017-11-06T20:15:33-08:00) for its universality. The date format in Swift is yyyy-MM-dd'T'HH:mm:ssXXXXX but RFC3339 allows us to take advantage of the ISO8601DateFormatter:

func getDateFromUTC(RFC3339: String) -> Date? {
    let formatter = ISO8601DateFormatter()
    return formatter.date(from: RFC3339)
}

RFC3339 also makes time-zone extraction simple:

func getTimeZoneFromUTC(RFC3339: String) -> TimeZone? {

    switch RFC3339.suffix(6) {

    case "+05:30":
        return TimeZone(identifier: "Asia/Kolkata")

    case "+05:45":
        return TimeZone(identifier: "Asia/Kathmandu")

    default:
        return nil

    }

}

There are 37 or so other time zones we'd have to account for and it's up to you to determine which ones, because there is no definitive list. Some standards count fewer time zones, some more. Most time zones break on the hour, some on the half hour, some on 0:45, some on 0:15.

We can combine the two methods above into something like this:

func getFormattedDateFromUTC(RFC3339: String) -> String? {

    guard let date = getDateFromUTC(RFC3339: RFC3339),
        let timeZone = getTimeZoneFromUTC(RFC3339: RFC3339) else {
            return nil
    }

    let formatter = DateFormatter()
    formatter.dateFormat = "h:mma EEE, MMM d yyyy"
    formatter.amSymbol = "AM"
    formatter.pmSymbol = "PM"
    formatter.timeZone = timeZone // preserve local time zone
    return formatter.string(from: date)

}

And so the string "2018-11-06T17:00:00+05:45", which represents 5:00PM somewhere in Kathmandu, will print 5:00PM Tue, Nov 6 2018, displaying the local time, regardless of where the machine is.

As an aside, I recommend storing dates as strings remotely (including Firestore which has a native date object) because, I think, remote data should agnostic to create as little friction between servers and clients as possible.

Convert float64 column to int64 in Pandas

This seems to be a little buggy in Pandas 0.23.4?

If there are np.nan values then this will throw an error as expected:

df['col'] = df['col'].astype(np.int64)

But doesn't change any values from float to int as I would expect if "ignore" is used:

df['col'] = df['col'].astype(np.int64,errors='ignore') 

It worked if I first converted np.nan:

df['col'] = df['col'].fillna(0).astype(np.int64)
df['col'] = df['col'].astype(np.int64)

Now I can't figure out how to get null values back in place of the zeroes since this will convert everything back to float again:

df['col']  = df['col'].replace(0,np.nan)

How to program a delay in Swift 3

After a lot of research, I finally figured this one out.

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
   // Code you want to be delayed
}

This creates the desired "wait" effect in Swift 3 and Swift 4.

Inspired by a part of this answer.

How do I write dispatch_after GCD in Swift 3, 4, and 5?

Swift 4:

DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
   // Code
}

For the time .seconds(Int), .microseconds(Int) and .nanoseconds(Int) may also be used.

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

Since the beginning, Swift has provided some facilities for making ObjC and C more Swifty, adding more with each version. Now, in Swift 3, the new "import as member" feature lets frameworks with certain styles of C API -- where you have a data type that works sort of like a class, and a bunch of global functions to work with it -- act more like Swift-native APIs. The data types import as Swift classes, their related global functions import as methods and properties on those classes, and some related things like sets of constants can become subtypes where appropriate.

In Xcode 8 / Swift 3 beta, Apple has applied this feature (along with a few others) to make the Dispatch framework much more Swifty. (And Core Graphics, too.) If you've been following the Swift open-source efforts, this isn't news, but now is the first time it's part of Xcode.

Your first step on moving any project to Swift 3 should be to open it in Xcode 8 and choose Edit > Convert > To Current Swift Syntax... in the menu. This will apply (with your review and approval) all of the changes at once needed for all the renamed APIs and other changes. (Often, a line of code is affected by more than one of these changes at once, so responding to error fix-its individually might not handle everything right.)

The result is that the common pattern for bouncing work to the background and back now looks like this:

// Move to a background thread to do some long running work
DispatchQueue.global(qos: .userInitiated).async {
    let image = self.loadOrGenerateAnImage()
    // Bounce back to the main thread to update the UI
    DispatchQueue.main.async {
        self.imageView.image = image
    }
}

Note we're using .userInitiated instead of one of the old DISPATCH_QUEUE_PRIORITY constants. Quality of Service (QoS) specifiers were introduced in OS X 10.10 / iOS 8.0, providing a clearer way for the system to prioritize work and deprecating the old priority specifiers. See Apple's docs on background work and energy efficiency for details.

By the way, if you're keeping your own queues to organize work, the way to get one now looks like this (notice that DispatchQueueAttributes is an OptionSet, so you use collection-style literals to combine options):

class Foo { 
    let queue = DispatchQueue(label: "com.example.my-serial-queue",
                           attributes: [.serial, .qosUtility])
    func doStuff() {
        queue.async {
            print("Hello World")
        }
    }
}

Using dispatch_after to do work later? That's a method on queues, too, and it takes a DispatchTime, which has operators for various numeric types so you can just add whole or fractional seconds:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // in half a second...
    print("Are we there yet?")
}

You can find your way around the new Dispatch API by opening its interface in Xcode 8 -- use Open Quickly to find the Dispatch module, or put a symbol (like DispatchQueue) in your Swift project/playground and command-click it, then brouse around the module from there. (You can find the Swift Dispatch API in Apple's spiffy new API Reference website and in-Xcode doc viewer, but it looks like the doc content from the C version hasn't moved into it just yet.)

See the Migration Guide for more tips.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I had exact issue and here is how I fixed:

I found out that I had first installed Keras then installed pandas in my virtual env. When you install keras, pandas is shipped with it. Do not need to pip install pandas.

I tested this hypothesis by creating new virtual environment and wala... pandas appeared without me installing it. Thus I came to the conclusion that pandas is automatically installed when you pip install keras.

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

Convert categorical data in pandas dataframe

You can do it less code like below :

f = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'),'col3':list('ababb')})

f['col1'] =f['col1'].astype('category').cat.codes
f['col2'] =f['col2'].astype('category').cat.codes
f['col3'] =f['col3'].astype('category').cat.codes

f

enter image description here

Drop rows containing empty cells from a pandas DataFrame

There's a situation where the cell has white space, you can't see it, use

df['col'].replace('  ', np.nan, inplace=True)

to replace white space as NaN, then

df= df.dropna(subset=['col'])

What does `ValueError: cannot reindex from a duplicate axis` mean?

Simple Fix that Worked for Me

Run df.reset_index(inplace=True) before grouping.

Thank you to this github comment for the solution.

Remove inplace if you want it to return the dataframe.

Converting map to struct

There are two steps:

  1. Convert interface to JSON Byte
  2. Convert JSON Byte to struct

Below is an example:

dbByte, _ := json.Marshal(dbContent)
_ = json.Unmarshal(dbByte, &MyStruct)

NumPy array is not JSON serializable

I found the best solution if you have nested numpy arrays in a dictionary:

import json
import numpy as np

class NumpyEncoder(json.JSONEncoder):
    """ Special json encoder for numpy types """
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

dumped = json.dumps(data, cls=NumpyEncoder)

with open(path, 'w') as f:
    json.dump(dumped, f)

Thanks to this guy.

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

Check these steps.

  1. go to Sql Server Configuration management->SQL Server network config->protocols for 'servername' and check TCP/IP is enabled.
  2. Open SSMS in run, and check you are able to login to server using specfied username/password and/or using windows authentication.
  3. repeat step 1 for SQL native client config also

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

This is not an answer, but it's hard to read if I put results in comment.

I get these results with a Mac Pro (Westmere 6-Cores Xeon 3.33 GHz). I compiled it with clang -O3 -msse4 -lstdc++ a.cpp -o a (-O2 get same result).

clang with uint64_t size=atol(argv[1])<<20;

unsigned    41950110000 0.811198 sec    12.9263 GB/s
uint64_t    41950110000 0.622884 sec    16.8342 GB/s

clang with uint64_t size=1<<20;

unsigned    41950110000 0.623406 sec    16.8201 GB/s
uint64_t    41950110000 0.623685 sec    16.8126 GB/s

I also tried to:

  1. Reverse the test order, the result is the same so it rules out the cache factor.
  2. Have the for statement in reverse: for (uint64_t i=size/8;i>0;i-=4). This gives the same result and proves the compile is smart enough to not divide size by 8 every iteration (as expected).

Here is my wild guess:

The speed factor comes in three parts:

  • code cache: uint64_t version has larger code size, but this does not have an effect on my Xeon CPU. This makes the 64-bit version slower.

  • Instructions used. Note not only the loop count, but the buffer is accessed with a 32-bit and 64-bit index on the two versions. Accessing a pointer with a 64-bit offset requests a dedicated 64-bit register and addressing, while you can use immediate for a 32-bit offset. This may make the 32-bit version faster.

  • Instructions are only emitted on the 64-bit compile (that is, prefetch). This makes 64-bit faster.

The three factors together match with the observed seemingly conflicting results.

In Swift how to call method with parameters on GCD main thread?

//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {  
    // Call your function here
    DispatchQueue.main.async {  
        // Update UI
        self.tableView.reloadData()  
    }
}

//To call or execute function after some time
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    //Here call your function
}

//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
    //Update UI
    self.tableView.reloadData()
})

How to print struct variables in console?

very simple I don't have the structure of Data and Commits So I changed the

package main

import (
    "fmt"
)

type Project struct {
    Id      int64   `json:"project_id"`
    Title   string  `json:"title"`
    Name    string  `json:"name"`
    Data    string  `json:"data"`
    Commits string  `json:"commits"`
}

func main() {
    p := Project{
    1,
    "First",
    "Ankit",
    "your data",
    "Commit message",
    }
    fmt.Println(p)
}

For learning you can take help from here : https://gobyexample.com/structs

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

From your stack trace, EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) occurred because dispatch_group_t was released while it was still locking (waiting for dispatch_group_leave).

According to what you found, this was what happened :

  • dispatch_group_t group was created. group's retain count = 1.
  • -[self webservice:onCompletion:] captured the group. group's retain count = 2.
  • dispatch_async(...., ^{ dispatch_group_wait(group, ...) ... }); captured the group again. group's retain count = 3.
  • Exit the current scope. group was released. group's retain count = 2.
  • dispatch_group_leave was never called.
  • dispatch_group_wait was timeout. The dispatch_async block was completed. group was released. group's retain count = 1.
  • You called this method again. When -[self webservice:onCompletion:] was called again, the old onCompletion block was replaced with the new one. So, the old group was released. group's retain count = 0. group was deallocated. That resulted to EXC_BAD_INSTRUCTION.

To fix this, I suggest you should find out why -[self webservice:onCompletion:] didn't call onCompletion block, and fix it. Then make sure the next call to the method will happen after the previous call did finish.


In case you allow the method to be called many times whether the previous calls did finish or not, you might find someone to hold group for you :

  • You can change the timeout from 2 seconds to DISPATCH_TIME_FOREVER or a reasonable amount of time that all -[self webservice:onCompletion] should call their onCompletion blocks by the time. So that the block in dispatch_async(...) will hold it for you.
    OR
  • You can add group into a collection, such as NSMutableArray.

I think it is the best approach to create a dedicate class for this action. When you want to make calls to webservice, you then create an object of the class, call the method on it with the completion block passing to it that will release the object. In the class, there is an ivar of dispatch_group_t or dispatch_semaphore_t.

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

Swift performSelector:withObject:afterDelay: is unavailable

Swift is statically typed so the performSelector: methods are to fall by the wayside.

Instead, use GCD to dispatch a suitable block to the relevant queue — in this case it'll presumably be the main queue since it looks like you're doing UIKit work.

EDIT: the relevant performSelector: is also notably missing from the Swift version of the NSRunLoop documentation ("1 Objective-C symbol hidden") so you can't jump straight in with that. With that and its absence from the Swiftified NSObject I'd argue it's pretty clear what Apple is thinking here.

Go / golang time.Now().UnixNano() convert to milliseconds?

As @Jono points out in @OneOfOne's answer, the correct answer should take into account the duration of a nanosecond. Eg:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

OneOfOne's answer works because time.Nanosecond happens to be 1, and dividing by 1 has no effect. I don't know enough about go to know how likely this is to change in the future, but for the strictly correct answer I would use this function, not OneOfOne's answer. I doubt there is any performance disadvantage as the compiler should be able to optimize this perfectly well.

See https://en.wikipedia.org/wiki/Dimensional_analysis

Another way of looking at this is that both time.Now().UnixNano() and time.Millisecond use the same units (Nanoseconds). As long as that is true, OneOfOne's answer should work perfectly well.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Make sure that registry HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\ODP.NET\4.112.# DIIPath key is pointing to 32 bit Oarcle client BIN directory. For example, DIIPath value can be C:\app\User_name\11.2.0\client_32bit\bin

size of uint8, uint16 and uint32?

uint8, uint16, uint32, and uint64 are probably Microsoft-specific types.

As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>: uint8_t, uint16_t, uint32_t, and uint64_t. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>, at least as of Visual Studio 2010, but older code may use uint8 et al.

The predefined types char, short, int et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char is at least 8 bits, short and int are at least 16, long is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int is 16, 32, or 64 bits.

char is almost always exactly 8 bits, but it's permitted to be wider. And plain char may be either signed or unsigned.

uint8_t is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char, though it might be a typedef for plain char if plain char happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t will not be defined at all.

Similarly, each uintN_t type is an unsigned type that's exactly N bits wide.

In addition, <stdint.h> defines corresponding signed intN_t types, as well as int_fastN_t and int_leastN_t types that are at least the specified width.

The [u]intN_t types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t types are required to use a 2's-complement representation.

Although uint32_t might be the same as unsigned int, for example, you shouldn't assume that. Use unsigned int when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t when you need an unsigned integer type that's exactly 32 bits wide.

(And no, uint64 or uint64_t is not the same as double; double is a floating-point type.)

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

Can you try to change your json without data key like below?

[{"target_id":9503123,"target_type":"user"}]

Assign pandas dataframe column dtypes

you can set the types explicitly with pandas DataFrame.astype(dtype, copy=True, raise_on_error=True, **kwargs) and pass in a dictionary with the dtypes you want to dtype

here's an example:

import pandas as pd
wheel_number = 5
car_name = 'jeep'
minutes_spent = 4.5

# set the columns
data_columns = ['wheel_number', 'car_name', 'minutes_spent']

# create an empty dataframe
data_df = pd.DataFrame(columns = data_columns)
df_temp = pd.DataFrame([[wheel_number, car_name, minutes_spent]],columns = data_columns)
data_df = data_df.append(df_temp, ignore_index=True) 

In [11]: data_df.dtypes
Out[11]:
wheel_number     float64
car_name          object
minutes_spent    float64
dtype: object

data_df = data_df.astype(dtype= {"wheel_number":"int64",
        "car_name":"object","minutes_spent":"float64"})

now you can see that it's changed

In [18]: data_df.dtypes
Out[18]:
wheel_number       int64
car_name          object
minutes_spent    float64

"The system cannot find the file specified"

I got this error when starting my ASP.NET application and in my case the problem was that the SQL Server service was not running. Starting that cleared it up.

Combine two pandas Data Frames (join on a common column)

In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!

T1 and T2 are dataframes that have the same indices

import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')

P.S. I had to use merge because append would fill NaNs in unnecessarily.

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

For the people stumbling across this question and getting a similar error message in regards to an nvarchar instead of money:

The given value of type String from the data source cannot be converted to type nvarchar of the specified target column.

This could be caused by a too-short column.

For example, if your column is defined as nvarchar(20) and you have a 40 character string, you may get this error.

Source

get dataframe row count based on conditions

For increased performance you should not evaluate the dataframe using your predicate. You can just use the outcome of your predicate directly as illustrated below:

In [1]: import pandas as pd
        import numpy as np
        df = pd.DataFrame(np.random.randn(20,4),columns=list('ABCD'))


In [2]: df.head()
Out[2]:
          A         B         C         D
0 -2.019868  1.227246 -0.489257  0.149053
1  0.223285 -0.087784 -0.053048 -0.108584
2 -0.140556 -0.299735 -1.765956  0.517803
3 -0.589489  0.400487  0.107856  0.194890
4  1.309088 -0.596996 -0.623519  0.020400

In [3]: %time sum((df['A']>0) & (df['B']>0))
CPU times: user 1.11 ms, sys: 53 µs, total: 1.16 ms
Wall time: 1.12 ms
Out[3]: 4

In [4]: %time len(df[(df['A']>0) & (df['B']>0)])
CPU times: user 1.38 ms, sys: 78 µs, total: 1.46 ms
Wall time: 1.42 ms
Out[4]: 4

Keep in mind that this technique only works for counting the number of rows that comply with your predicate.

How to get column by number in Pandas?

The following is taken from http://pandas.pydata.org/pandas-docs/dev/indexing.html. There are a few more examples... you have to scroll down a little

In [816]: df1

           0         2         4         6
0   0.569605  0.875906 -2.211372  0.974466
2  -2.006747 -0.410001 -0.078638  0.545952
4  -1.219217 -1.226825  0.769804 -1.281247
6  -0.727707 -0.121306 -0.097883  0.695775
8   0.341734  0.959726 -1.110336 -0.619976
10  0.149748 -0.732339  0.687738  0.176444

Select via integer slicing

In [817]: df1.iloc[:3]

          0         2         4         6
0  0.569605  0.875906 -2.211372  0.974466
2 -2.006747 -0.410001 -0.078638  0.545952
4 -1.219217 -1.226825  0.769804 -1.281247

In [818]: df1.iloc[1:5,2:4]

          4         6
2 -0.078638  0.545952
4  0.769804 -1.281247
6 -0.097883  0.695775
8 -1.110336 -0.619976

Select via integer list

In [819]: df1.iloc[[1,3,5],[1,3]]

           2         6
2  -0.410001  0.545952
6  -0.121306  0.695775
10 -0.732339  0.176444

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

How to form tuple column from two columns in Pandas

Pandas has the itertuples method to do exactly this:

list(df[['lat', 'long']].itertuples(index=False, name=None))

Datetime in C# add days

Why do you use Int64? AddDays demands a double-value to be added. Then you'll need to use the return-value of AddDays. See here.

How to preview a part of a large pandas DataFrame, in iPython notebook?

In Python pandas provide head() and tail() to print head and tail data respectively.

import pandas as pd
train = pd.read_csv('file_name')
train.head() # it will print 5 head row data as default value is 5
train.head(n) # it will print n head row data
train.tail() #it will print 5 tail row data as default value is 5
train.tail(n) #it will print n tail row data

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

I went for JerKimballs solution, and thumbs up to that. However, I would like to add / point out that this is indeed a matter of controversy as a whole. In my research (for other reasons) I have come up with the following pieces of information.

When normal people (I have heard they exist) speak of gigabytes they refer to the metric system wherein 1000 to the power of 3 from the original number of bytes == the number of gigabytes. However, of course there is the IEC / JEDEC standards which is nicely summed up in wikipedia, which instead of 1000 to the power of x they have 1024. Which for physical storage devices (and I guess logical such as amazon and others) means an ever increasing difference between metric vs IEC. So for instance 1 TB == 1 terabyte metric is 1000 to the power of 4, but IEC officially terms the similar number as 1 TiB, tebibyte as 1024 to the power of 4. But, alas, in non-technical applications (I would go by audience) the norm is metric, and in my own app for internal use currently I explain the difference in documentation. But for display purposes I do not even offer anything but metric. Internally even though it's not relevant in my app I only store bytes and do the calculation for display.

As a side note I find it somewhat lackluster that the .Net framework AFAIK (and I am frequently wrong thank the powers that be) even in it's 4.5 incarnation does not contain anything about this in any libraries internally. One would expect an open source library of some kind to be NuGettable at some point, but I admit this is a small peeve. On the other hand System.IO.DriveInfo and others also only have bytes (as long) which is rather clear.

Definition of int64_t

My 2 cents, from a current implementation Point of View and for SWIG users on k8 (x86_64) architecture.

Linux

First long long and long int are different types but sizeof(long long) == sizeof(long int) == sizeof(int64_t)

Gcc

First try to find where and how the compiler define int64_t and uint64_t

grepc -rn "typedef.*INT64_TYPE" /lib/gcc
/lib/gcc/x86_64-linux-gnu/9/include/stdint-gcc.h:43:typedef __INT64_TYPE__ int64_t;
/lib/gcc/x86_64-linux-gnu/9/include/stdint-gcc.h:55:typedef __UINT64_TYPE__ uint64_t;

So we need to find this compiler macro definition

gcc -dM -E -x c /dev/null | grep __INT64                 
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int

gcc -dM -E -x c++ /dev/null | grep __INT64
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int

Clang

clang -dM -E -x c++ /dev/null | grep INT64_TYPE
#define __INT64_TYPE__ long int
#define __UINT64_TYPE__ long unsigned int

Clang, GNU compilers:
-dM dumps a list of macros.
-E prints results to stdout instead of a file.
-x c and -x c++ select the programming language when using a file without a filename extension, such as /dev/null

Ref: https://web.archive.org/web/20190803041507/http://nadeausoftware.com/articles/2011/12/c_c_tip_how_list_compiler_predefined_macros

note: for swig user, on Linux x86_64 use -DSWIGWORDSIZE64

MacOS

On Catalina 10.15 IIRC

Clang

clang -dM -E -x c++ /dev/null | grep INT64_TYPE
#define __INT64_TYPE__ long long int
#define __UINT64_TYPE__ long long unsigned int

Clang:
-dM dumps a list of macros.
-E prints results to stdout instead of a file.
-x c and -x c++ select the programming language when using a file without a filename extension, such as /dev/null

Ref: https://web.archive.org/web/20190803041507/http://nadeausoftware.com/articles/2011/12/c_c_tip_how_list_compiler_predefined_macros

note: for swig user, on macOS x86_64 don't use -DSWIGWORDSIZE64

Visual Studio 2019

First sizeof(long int) == 4 and sizeof(long long) == 8

in stdint.h we have:

#if _VCRT_COMPILER_PREPROCESSOR

typedef signed char        int8_t;
typedef short              int16_t;
typedef int                int32_t;
typedef long long          int64_t;
typedef unsigned char      uint8_t;
typedef unsigned short     uint16_t;
typedef unsigned int       uint32_t;
typedef unsigned long long uint64_t;

note: for swig user, on windows x86_64 don't use -DSWIGWORDSIZE64

SWIG Stuff

First see https://github.com/swig/swig/blob/3a329566f8ae6210a610012ecd60f6455229fe77/Lib/stdint.i#L20-L24 so you can control the typedef using SWIGWORDSIZE64 but...

now the bad: SWIG Java and SWIG CSHARP do not take it into account

So you may want to use

#if defined(SWIGJAVA)
#if defined(SWIGWORDSIZE64)
%define PRIMITIVE_TYPEMAP(NEW_TYPE, TYPE)
%clear NEW_TYPE;
%clear NEW_TYPE *;
%clear NEW_TYPE &;
%clear const NEW_TYPE &;
%apply TYPE { NEW_TYPE };
%apply TYPE * { NEW_TYPE * };
%apply TYPE & { NEW_TYPE & };
%apply const TYPE & { const NEW_TYPE & };
%enddef // PRIMITIVE_TYPEMAP
PRIMITIVE_TYPEMAP(long int, long long);
PRIMITIVE_TYPEMAP(unsigned long int, long long);
#undef PRIMITIVE_TYPEMAP
#endif // defined(SWIGWORDSIZE64)
#endif // defined(SWIGJAVA)

and

#if defined(SWIGCSHARP)
#if defined(SWIGWORDSIZE64)
%define PRIMITIVE_TYPEMAP(NEW_TYPE, TYPE)
%clear NEW_TYPE;
%clear NEW_TYPE *;
%clear NEW_TYPE &;
%clear const NEW_TYPE &;
%apply TYPE { NEW_TYPE };
%apply TYPE * { NEW_TYPE * };
%apply TYPE & { NEW_TYPE & };
%apply const TYPE & { const NEW_TYPE & };
%enddef // PRIMITIVE_TYPEMAP
PRIMITIVE_TYPEMAP(long int, long long);
PRIMITIVE_TYPEMAP(unsigned long int, unsigned long long);
#undef PRIMITIVE_TYPEMAP
#endif // defined(SWIGWORDSIZE64)
#endif // defined(SWIGCSHARP)

So int64_t aka long int will be bind to Java/C# long on Linux...

Import pandas dataframe column as string not int

This probably isn't the most elegant way to do it, but it gets the job done.

In[1]: import numpy as np

In[2]: import pandas as pd

In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])

In[4]: df
Out[4]: 
                       ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

Just replace '/Users/spencerlyon2/Desktop/test.csv' with the path to your file

How to change int into int64?

i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64

pandas read_csv index_col=None not working with delimiters at the end of each line

Quick Answer

Use index_col=False instead of index_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column.

More Detail

After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created):

index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.

from the documentation shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index.


EDIT 10/20/2014 - More information

I found another valuable entry that is specifically about trailing limiters and how to simply ignore them:

If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...

Ordinarily, you can achieve this behavior using the index_col option.

There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...

Pandas (python): How to add column to dataframe for index?

I stumbled on this question while trying to do the same thing (I think). Here is how I did it:

df['index_col'] = df.index

You can then sort on the new index column, if you like.

Output data from all columns in a dataframe in pandas

In ipython, I use this to print a part of the dataframe that works quite well (prints the first 100 rows):

print paramdata.head(100).to_string()

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

This is an old thread, but another solution, which I prefer, is just update the cityId and not assign the hole model City to Employee... to do that Employee should look like:

public class Employee{
    ...
    public int? CityId; //The ? is for allow City nullable
    public virtual City City;
}

Then it's enough assigning:

e1.CityId=city1.ID;

What is the difference between int, Int16, Int32 and Int64?

They both are indeed synonymous, However i found the small difference between them,

1)You cannot use Int32 while creatingenum

enum Test : Int32
{ XXX = 1   // gives you compilation error
}

enum Test : int
{ XXX = 1   // Works fine
}

2) Int32 comes under System declaration. if you remove using.System you will get compilation error but not in case for int

How to specify 64 bit integers in c

Append ll suffix to hex digits for 64-bit (long long int), or ull suffix for unsigned 64-bit (unsigned long long)

How to print a int64_t type in C

For int64_t type:

#include <inttypes.h>
int64_t t;
printf("%" PRId64 "\n", t);

for uint64_t type:

#include <inttypes.h>
uint64_t t;
printf("%" PRIu64 "\n", t);

you can also use PRIx64 to print in hexadecimal.

cppreference.com has a full listing of available macros for all types including intptr_t (PRIxPTR). There are separate macros for scanf, like SCNd64.


A typical definition of PRIu16 would be "hu", so implicit string-constant concatenation happens at compile time.

For your code to be fully portable, you must use PRId32 and so on for printing int32_t, and "%d" or similar for printing int.

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64 macro and other printf issues altogether:

#include <fmt/core.h>

int main() {
  uint64_t ui64 = 90;
  fmt::print("test uint64_t : {}\n", ui64);
}

The formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

Object cannot be cast from DBNull to other types

You need to check for DBNull, not null. Additionally, two of your three ReplaceNull methods don't make sense. double and DateTime are non-nullable, so checking them for null will always be false...

There is already an open DataReader associated with this Command which must be closed first

In my case, I had opened a query from data context, like

    Dim stores = DataContext.Stores _
        .Where(Function(d) filter.Contains(d.code)) _

... and then subsequently queried the same...

    Dim stores = DataContext.Stores _
        .Where(Function(d) filter.Contains(d.code)).ToList

Adding the .ToList to the first resolved my issue. I think it makes sense to wrap this in a property like:

Public ReadOnly Property Stores As List(Of Store)
    Get
        If _stores Is Nothing Then
            _stores = DataContext.Stores _
                .Where(Function(d) Filters.Contains(d.code)).ToList
        End If
        Return _stores
    End Get
End Property

Where _stores is a private variable, and Filters is also a readonly property that reads from AppSettings.

Are types like uint32, int32, uint64, int64 defined in any stdlib header?

If you are using C99 just include stdint.h. BTW, the 64bit types are there iff the processor supports them.

long long int vs. long int vs. int64_t in C++

Do you want to know if a type is the same type as int64_t or do you want to know if something is 64 bits? Based on your proposed solution, I think you're asking about the latter. In that case, I would do something like

template<typename T>
bool is_64bits() { return sizeof(T) * CHAR_BIT == 64; } // or >= 64

Using custom std::set comparator

Yacoby's answer inspires me to write an adaptor for encapsulating the functor boilerplate.

template< class T, bool (*comp)( T const &, T const & ) >
class set_funcomp {
    struct ftor {
        bool operator()( T const &l, T const &r )
            { return comp( l, r ); }
    };
public:
    typedef std::set< T, ftor > t;
};

// usage

bool my_comparison( foo const &l, foo const &r );
set_funcomp< foo, my_comparison >::t boo; // just the way you want it!

Wow, I think that was worth the trouble!

Error: "an object reference is required for the non-static field, method or property..."

You can't access non-static members from a static method. (Note that Main() is static, which is a requirement of .Net). Just make siprimo and volteado static, by placing the static keyword in front of them. e.g.:

 static private long volteado(long a)

"Invalid JSON primitive" in Ajax processing

I had the same issue. I was calling parent page "Save" from Popup window Close. Found that I was using ClientIDMode="Static" on both parent and popup page with same control id. Removing ClientIDMode="Static" from one of the pages solved the issue.

Java equivalent of unsigned long long?

Starting Java 8, there is support for unsigned long (unsigned 64 bits). The way you can use it is:

Long l1 = Long.parseUnsignedLong("17916881237904312345");

To print it, you can not simply print l1, but you have to first:

String l1Str = Long.toUnsignedString(l1)

Then

System.out.println(l1Str);

How to format a string as a telephone number in C#

The following will work with out use of regular expression

string primaryContactNumber = !string.IsNullOrEmpty(formData.Profile.Phone) ? String.Format("{0:###-###-####}", long.Parse(formData.Profile.Phone)) : "";

If we dont use long.Parse , the string.format will not work.

Is there a constraint that restricts my generic method to numeric types?

Unfortunately .NET doesn't provide a way to do that natively.

To address this issue I created the OSS library Genumerics which provides most standard numeric operations for the following built-in numeric types and their nullable equivalents with the ability to add support for other numeric types.

sbyte, byte, short, ushort, int, uint, long, ulong, float, double, decimal, and BigInteger

The performance is equivalent to a numeric type specific solution allowing you to create efficient generic numeric algorithms.

Here's an example of the code usage.

public static T Sum(T[] items)
{
    T sum = Number.Zero<T>();
    foreach (T item in items)
    {
        sum = Number.Add(sum, item);
    }
    return sum;
}
public static T SumAlt(T[] items)
{
    // implicit conversion to Number<T>
    Number<T> sum = Number.Zero<T>();
    foreach (T item in items)
    {
        // operator support
        sum += item;
    }
    // implicit conversion to T
    return sum;
}

Create a button with rounded border

For implementing the rounded border button with a border color use this

OutlineButton(
                    child: new Text("Button Text"),borderSide: BorderSide(color: Colors.blue),
                    onPressed: null,
                    shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(20.0))
                ),

Split value from one field to two

use this

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX( `membername` , ' ', 2 ),' ',1) AS b, 
SUBSTRING_INDEX(SUBSTRING_INDEX( `membername` , ' ', -1 ),' ',2) AS c FROM `users` WHERE `userid`='1'

Get domain name from given url

In my case i only needed the main domain and not the subdomain (no "www" or whatever the subdomain is) :

public static String getUrlDomain(String url) throws URISyntaxException {
    URI uri = new URI(url);
    String domain = uri.getHost();
    String[] domainArray = domain.split("\\.");
    if (domainArray.length == 1) {
        return domainArray[0];
    }
    return domainArray[domainArray.length - 2] + "." + domainArray[domainArray.length - 1];
}

With this method the url "https://rest.webtoapp.io/llSlider?lg=en&t=8" will have for domain "webtoapp.io".

Function Pointers in Java

Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:

http://code.google.com/p/lambdaj/wiki/Closures

Return value from exec(@sql)

that's my procedure

CREATE PROC sp_count
    @CompanyId sysname,
    @codition sysname
    AS
    SET NOCOUNT ON
    CREATE TABLE #ctr
    ( NumRows int )

    DECLARE @intCount int
         , @vcSQL varchar(255)

    SELECT    @vcSQL = ' INSERT #ctr FROM dbo.Comm_Services 
                       WHERE CompanyId = '+@CompanyId+' and '+@condition+')'
    EXEC      (@vcSQL)

    IF @@ERROR = 0
    BEGIN
         SELECT    @intCount = NumRows
         FROM #ctr

         DROP TABLE #ctr
         RETURN @intCount
    END
    ELSE
    BEGIN
         DROP TABLE #ctr
         RETURN -1
    END
    GO

Hosting a Maven repository on github

As an alternative, Bintray provides free hosting of maven repositories. That's probably a good alternative to Sonatype OSS and Maven Central if you absolutely don't want to rename the groupId. But please, at least make an effort to get your changes integrated upstream or rename and publish to Central. It makes it much easier for others to use your fork.

Open Redis port for remote connections

1- Comment out bind 127.0.0.1

2- set requirepass yourpassword

then check if the firewall blocked your port

iptables -L -n

service iptables stop

Check with jquery if div has overflowing elements

This is the jQuery solution that worked for me. offsetWidth etc. didn't work.

function is_overflowing(element, extra_width) {
    return element.position().left + element.width() + extra_width > element.parent().width();
}

If this doesn't work, ensure that elements' parent has the desired width (personally, I had to use parent().parent()). position is relative to the parent. I've also included extra_width because my elements ("tags") contain images which take small time to load, but during the function call they have zero width, spoiling the calculation. To get around that, I use the following calling code:

var extra_width = 0;
$(".tag:visible").each(function() {
    if (!$(this).find("img:visible").width()) {
        // tag image might not be visible at this point,
        // so we add its future width to the overflow calculation
        // the goal is to hide tags that do not fit one line
        extra_width += 28;
    }
    if (is_overflowing($(this), extra_width)) {
        $(this).hide();
    }
});

Hope this helps.

How do you convert Html to plain text?

It has limitation that not collapsing long inline whitespace, but it is definitely portable and respects layout like webbrowser.

static string HtmlToPlainText(string html) {
  string buf;
  string block = "address|article|aside|blockquote|canvas|dd|div|dl|dt|" +
    "fieldset|figcaption|figure|footer|form|h\\d|header|hr|li|main|nav|" +
    "noscript|ol|output|p|pre|section|table|tfoot|ul|video";

  string patNestedBlock = $"(\\s*?</?({block})[^>]*?>)+\\s*";
  buf = Regex.Replace(html, patNestedBlock, "\n", RegexOptions.IgnoreCase);

  // Replace br tag to newline.
  buf = Regex.Replace(buf, @"<(br)[^>]*>", "\n", RegexOptions.IgnoreCase);

  // (Optional) remove styles and scripts.
  buf = Regex.Replace(buf, @"<(script|style)[^>]*?>.*?</\1>", "", RegexOptions.Singleline);

  // Remove all tags.
  buf = Regex.Replace(buf, @"<[^>]*(>|$)", "", RegexOptions.Multiline);

  // Replace HTML entities.
  buf = WebUtility.HtmlDecode(buf);
  return buf;
}

How do I get the last word in each line with bash

there are many ways. as awk solutions shows, it's the clean solution

sed solution is to delete anything till the last space. So if there is no space at the end, it should work

sed 's/.* //g' <file>

you can avoid sed also and go for a while loop.

while read line
do [ -z "$line" ] && continue ;
echo $line|rev|cut -f1 -d' '|rev
done < file

it reads a line, reveres it, cuts the first (i.e. last in the original) and restores back

the same can be done in a pure bash way

while read line
do [ -z "$line" ] && continue ;
echo ${line##* }
done < file

it is called parameter expansion

Extracting text from a PDF file using PDFMiner in python?

This works in May 2020 using PDFminer six in Python3.

Installing the package

$ pip install pdfminer.six

Importing the package

from pdfminer.high_level import extract_text

Using a PDF saved on disk

text = extract_text('report.pdf')

Or alternatively:

with open('report.pdf','rb') as f:
    text = extract_text(f)

Using PDF already in memory

If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io library:

import io

response = requests.get(url)
text = extract_text(io.BytesIO(response.content))

Performance and Reliability compared with PyPDF2

PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7

However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.

I timed text extraction with timeit on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:

PDFminer.six: 2.88 sec
PyPDF2:       0.45 sec

pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.

iOS 7 - Failing to instantiate default view controller

Projects created in Xcode 11 and above, simply changing the Main Interface file from the project settings won't be enough.

You have to manually edit the Info.plist file and set the storyboard name for the UISceneStoryboardFile as well.

"while :" vs. "while true"

from manual:

: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.

As this returns always zero therefore is is similar to be used as true

Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?

How to draw an empty plot?

I suggest that someone needs to make empty plot in order to add some graphics on it later. So, using

plot(1, type="n", xlab="", ylab="", xlim=c(0, 10), ylim=c(0, 10))

you can specify the axes limits of your graphic.

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

You have to disable Memory Integrity.

Go to Device Security, then Core Isolation, disable Memory Integrity and reboot.

It seems that Memory Integrity virtualizes some processes (in this case, VMware) and we get that error.


You can also disable Memory Integrity from Registry Editor if your control panel was saying 'This is managed by your administrator'.

Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity

Double click on Enabled and change its value from 1 to 0 to disable it.


Helpful source: https://forums.virtualbox.org/viewtopic.php?t=86977#p420584

Undo git update-index --assume-unchanged <file>

If you want to undo all files that was applied assume unchanged with any status, not only cached (git marks them by character in lower case), you can use the following command:

git ls-files -v | grep '^[a-z]' | cut -c 3- | tr '\012' '\000' | xargs -0 git update-index --no-assume-unchanged
  1. git ls-files -v will print all files with their status
  2. grep '^[a-z]' will filter files and select only assume unchanged
  3. cut -c 3- will remove status and leave only paths, cutting from the 3-rd character to the end
  4. tr '\012' '\000' will replace end of line character (\012) to zero character (\000)
  5. xargs -0 git update-index --no-assume-unchanged will pass all paths separated by zero character to git update-index --no-assume-unchanged to undo

JavaScript: Class.method vs. Class.prototype.method

For visual learners, when defining the function without .prototype

ExampleClass = function(){};
ExampleClass.method = function(customString){
             console.log((customString !== undefined)? 
                          customString : 
                          "called from func def.");}
ExampleClass.method(); // >> output: `called from func def.`  

var someInstance = new ExampleClass();
someInstance.method('Called from instance');
    // >> error! `someInstance.method is not a function`  

With same code, if .prototype is added,

ExampleClass.prototype.method = function(customString){
             console.log((customString !== undefined)? 
                          customString : 
                          "called from func def.");}
ExampleClass.method();  
      // > error! `ExampleClass.method is not a function.`  

var someInstance = new ExampleClass();
someInstance.method('Called from instance');
                 // > output: `Called from instance`

To make it clearer,

ExampleClass = function(){};
ExampleClass.directM = function(){}  //M for method
ExampleClass.prototype.protoM = function(){}

var instanceOfExample = new ExampleClass();

ExampleClass.directM();     ? works
instanceOfExample.directM();   x Error!

ExampleClass.protoM();     x Error!
instanceOfExample.protoM();  ? works

****Note for the example above, someInstance.method() won't be executed as,
ExampleClass.method() causes error & execution cannot continue.
But for the sake of illustration & easy understanding, I've kept this sequence.****

Results generated from chrome developer console & JS Bin
Click on the jsbin link above to step through the code.
Toggle commented section with ctrl+/

How to un-commit last un-pushed git commit without losing the changes

2020 simple way :

git reset <commit_hash>

Commit hash of the last commit you want to keep.

How can I clear event subscriptions in C#?

This is my solution:

public class Foo : IDisposable
{
    private event EventHandler _statusChanged;
    public event EventHandler StatusChanged
    {
        add
        {
            _statusChanged += value;
        }
        remove
        {
            _statusChanged -= value;
        }
    }

    public void Dispose()
    {
        _statusChanged = null;
    }
}

You need to call Dispose() or use using(new Foo()){/*...*/} pattern to unsubscribe all members of invocation list.

Programmatically register a broadcast receiver

package com.example.broadcastreceiver;


import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

   UserDefinedBroadcastReceiver broadCastReceiver = new UserDefinedBroadcastReceiver();

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

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

   /**
    * This method enables the Broadcast receiver for
    * "android.intent.action.TIME_TICK" intent. This intent get
    * broadcasted every minute.
    *
    * @param view
    */
   public void registerBroadcastReceiver(View view) {

      this.registerReceiver(broadCastReceiver, new IntentFilter(
            "android.intent.action.TIME_TICK"));
      Toast.makeText(this, "Registered broadcast receiver", Toast.LENGTH_SHORT)
            .show();
   }

   /**
    * This method disables the Broadcast receiver
    *
    * @param view
    */
   public void unregisterBroadcastReceiver(View view) {

      this.unregisterReceiver(broadCastReceiver);

      Toast.makeText(this, "unregistered broadcst receiver", Toast.LENGTH_SHORT)
            .show();
   }
}

How can I find which tables reference a given table in Oracle SQL Developer?

You may be able to query this from the ALL_CONSTRAINTS view:

SELECT table_name
FROM ALL_CONSTRAINTS
WHERE constraint_type = 'R' -- "Referential integrity"
  AND r_constraint_name IN
    ( SELECT constraint_name
      FROM ALL_CONSTRAINTS
      WHERE table_name = 'EMP'
        AND constraint_type IN ('U', 'P') -- "Unique" or "Primary key"
    );

how to get GET and POST variables with JQuery?

Just for the record, I wanted to know the answer to this question, so I used a PHP method:

<script>
var jGets = new Array ();
<?
if(isset($_GET)) {
    foreach($_GET as $key => $val)
        echo "jGets[\"$key\"]=\"$val\";\n";
}
?>
</script>

That way all my javascript/jquery that runs after this can access everything in the jGets. Its an nice elegant solution I feel.

Run task only if host does not belong to a group

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names is a list (array) of all the groups the current host is in.

How to set java_home on Windows 7?

You may wanna look into Windows/System32 folder for the following files: - java.exe - javaw.exe - javaws.exe

Because, the path variable is including these files, you can get a headache trying to figure out why the java -version or javac -version keeps pointing to the old JAVA_HOME: rename those files, take out the extension with an underscore, for instance. And then, you only will have to create the JAVA_HOME variable, add it to the path variable (e.g., %JAVA_HOME%) and append the "\bin" particle. This way you need to only change the JAVA_HOME variable pointing to different JRE or JDK and have multiple installations of java just by setting JAVA_HOME.

This also means that it is better to install Java manually, without an installer, so you are able to toy with it.

List all employee's names and their managers by manager name using an inner join

select e.ename as Employee, m.ename as Manager
from emp e, emp m
where e.mgr = m.empno

If you want to get the result for all the records (irrespective of whether they report to anyone or not), append (+) on the second table's name

select e.ename as Employee, m.ename as Manager
from emp e, emp m
where e.mgr = m.empno(+)

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 do I center align horizontal <UL> menu?

div {
     text-align: center;
}
div ul {
     display: inline-table;
}

ul as inline-table fixes the with issue. I used the parent div to align the text to center. this way it looks good even in other languages (translation, different width)

How to get the client IP address in PHP

Here's a bit of code that should pick a valid IP by checking through various sources.

First, it checks if 'REMOTE_ADDR' is a public IP or not (and not one of your trusted reverse proxies), then goes through one of the HTTP headers until it finds a public IP and returns it. (PHP 5.2+)

It should be reliable as long as the reverse proxy is trusted or the server is directly connected with the client.

//Get client's IP or null if nothing looks valid
function ip_get($allow_private = false)
{
  //Place your trusted proxy server IPs here.
  $proxy_ip = ['127.0.0.1'];

  //The header to look for (Make sure to pick the one that your trusted reverse proxy is sending or else you can get spoofed)
  $header = 'HTTP_X_FORWARDED_FOR'; //HTTP_CLIENT_IP, HTTP_X_FORWARDED, HTTP_FORWARDED_FOR, HTTP_FORWARDED

  //If 'REMOTE_ADDR' seems to be a valid client IP, use it.
  if(ip_check($_SERVER['REMOTE_ADDR'], $allow_private, $proxy_ip)) return $_SERVER['REMOTE_ADDR'];

  if(isset($_SERVER[$header]))
  {
    //Split comma separated values [1] in the header and traverse the proxy chain backwards.
    //[1] https://en.wikipedia.org/wiki/X-Forwarded-For#Format
    $chain = array_reverse(preg_split('/\s*,\s*/', $_SERVER[$header]));
    foreach($chain as $ip) if(ip_check($ip, $allow_private, $proxy_ip)) return $ip;
  }

   return null;
}

//Check for valid IP. If 'allow_private' flag is set to truthy, it allows private IP ranges as valid client IP as well. (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
//Pass your trusted reverse proxy IPs as $proxy_ip to exclude them from being valid.
function ip_check($ip, $allow_private = false, $proxy_ip = [])
{
  if(!is_string($ip) || is_array($proxy_ip) && in_array($ip, $proxy_ip)) return false;
  $filter_flag = FILTER_FLAG_NO_RES_RANGE;

  if(!$allow_private)
  {
    //Disallow loopback IP range which doesn't get filtered via 'FILTER_FLAG_NO_PRIV_RANGE' [1]
    //[1] https://www.php.net/manual/en/filter.filters.validate.php
    if(preg_match('/^127\.$/', $ip)) return false;
    $filter_flag |= FILTER_FLAG_NO_PRIV_RANGE;
  }

  return filter_var($ip, FILTER_VALIDATE_IP, $filter_flag) !== false;
}

How do I move a file (or folder) from one folder to another in TortoiseSVN?

Subversion does not yet have a first-class rename operations.

There's a 6-year-old bug on the problem: http://subversion.tigris.org/issues/show_bug.cgi?id=898

It's being considered for 1.6, now that merge tracking (a higher priority) has been added (in 1.5).

Node: log in a file instead of the console

You can now use Caterpillar which is a streams based logging system, allowing you to log to it, then pipe the output off to different transforms and locations.

Outputting to a file is as easy as:

var logger = new (require('./').Logger)();
logger.pipe(require('fs').createWriteStream('./debug.log'));
logger.log('your log message');

Complete example on the Caterpillar Website

jquery how to catch enter key and change event to tab

I had the same requirement in my development so I did research on this. I have read many articles and tried many solutions during last two days like jQuery.tabNext() plugin.

I had some trouble with IE11 (all IE version has this bug). When an input text followed by non text input the selection was not cleared. So I have created my own tabNext() method based on @Sarfraz solution suggestion. I was also thinking on how it should behave (only circle in the current form or maybe through the full document). I still did not take care of the tabindex property mostly because I am using it occasionally. But I will not forget it.

In order to my contribution can be useful for everybody easily I have created jsfiddle example here https://jsfiddle.net/mkrivan/hohx4nes/

I include also the JavaScript part of the example here:

            function clearSelection() {
            if (document.getSelection) { // for all new browsers (IE9+, Chrome, Firefox)
                document.getSelection().removeAllRanges();
                document.getSelection().addRange(document.createRange());
                console.log("document.getSelection");
            } else if (window.getSelection) { // equals with the document.getSelection (MSDN info)
                if (window.getSelection().removeAllRanges) {  // for all new browsers (IE9+, Chrome, Firefox)
                    window.getSelection().removeAllRanges();
                    window.getSelection().addRange(document.createRange());
                    console.log("window.getSelection.removeAllRanges");
                } else if (window.getSelection().empty) {  // maybe for old Chrome
                    window.getSelection().empty();
                    console.log("window.getSelection.empty");
                }
            } else if (document.selection) {  // IE8- deprecated
                document.selection.empty();
                console.log("document.selection.empty");
            }
        }
        function focusNextInputElement(node) { // instead of jQuery.tabNext();
            // TODO: take the tabindex into account if defined
            if (node !== null) {
                // stay in the current form
                var inputs = $(node).parents("form").eq(0).find(":input:visible:not([disabled]):not([readonly])");
                // if you want through the full document (as TAB key is working)
                // var inputs = $(document).find(":input:visible:not([disabled]):not([readonly])");
                var idx = inputs.index(node) + 1; // next input element index
                if (idx === inputs.length) { // at the end start with the first one
                    idx = 0;
                }
                var nextInputElement = inputs[idx];
                nextInputElement.focus(); //  handles submit buttons
                try { // if next input element does not support select()
                    nextInputElement.select();
                } catch (e) {
                }
            }
        }
        function tabNext() {
            var currentActiveNode = document.activeElement;
            clearSelection();
            focusNextInputElement(currentActiveNode);
        }
        function stopReturnKey(e) {
            var e = (e) ? e : ((event) ? event : null);
            if (e !== null) {
                var node = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : null);
                if (node !== null) {
                    var requiredNode = $(node).is(':input')
                            // && !$(node).is(':input[button]')
                            // && !$(node).is(':input[type="submit"]')
                            && !$(node).is('textarea');
                    // console.log('event key code ' + e.keyCode + '; required node ' + requiredNode);
                    if ((e.keyCode === 13) && requiredNode) {
                        try {
                            tabNext();
                            // clearSelection();
                            // focusNextInputElement(node);
                            // jQuery.tabNext();
                            console.log("success");
                        } catch (e) {
                            console.log("error");
                        }
                        return false;
                    }
                }
            }
        }
        document.onkeydown = stopReturnKey;

I left commented rows as well so my thinking can be followed.

How could I use requests in asyncio?

aiohttp can be used with HTTP proxy already:

import asyncio
import aiohttp


@asyncio.coroutine
def do_request():
    proxy_url = 'http://localhost:8118'  # your proxy address
    response = yield from aiohttp.request(
        'GET', 'http://google.com',
        proxy=proxy_url,
    )
    return response

loop = asyncio.get_event_loop()
loop.run_until_complete(do_request())

restart mysql server on windows 7

Open the command prompt and enter the following commands:

net stop MySQL   
net start MySQL

the MySQL service name maybe changes based on the version you installed. In my situation, MySQL version is MySQL Server 5.7. So I use the following command

net stop MySQL57   
net start MySQL57

Specified argument was out of the range of valid values. Parameter name: site

I got this issue when trying to run a project targeting Framework 4.5 in VS2017. After changing it to Framework 4.6.X it got fixed by itself.

Regex for string contains?

Assuming regular PCRE-style regex flavors:

If you want to check for it as a single, full word, it's \bTest\b, with appropriate flags for case insensitivity if desired and delimiters for your programming language. \b represents a "word boundary", that is, a point between characters where a word can be considered to start or end. For example, since spaces are used to separate words, there will be a word boundary on either side of a space.

If you want to check for it as part of the word, it's just Test, again with appropriate flags for case insensitivity. Note that usually, dedicated "substring" methods tend to be faster in this case, because it removes the overhead of parsing the regex.

Get first row of dataframe in Python Pandas based on criteria

For existing matches, use query:

df.query(' A > 3' ).head(1)
Out[33]: 
   A  B  C
2  4  6  3

df.query(' A > 4 and B > 3' ).head(1)
Out[34]: 
   A  B  C
4  5  4  5

df.query(' A > 3 and (B > 3 or C > 2)' ).head(1)
Out[35]: 
   A  B  C
2  4  6  3

Adding/removing items from a JavaScript object with jQuery

That's not JSON at all, it's just Javascript objects. JSON is a text representation of data, that uses a subset of the Javascript syntax.

The reason that you can't find any information about manipulating JSON using jQuery is because jQuery has nothing that can do that, and it's generally not done at all. You manipulate the data in the form of Javascript objects, and then turn it into a JSON string if that is what you need. (jQuery does have methods for the conversion, though.)

What you have is simply an object that contains an array, so you can use all the knowledge that you already have. Just use data.items to access the array.

For example, to add another item to the array using dynamic values:

// The values to put in the item
var id = 7;
var name = "The usual suspects";
var type = "crime";
// Create the item using the values
var item = { id: id, name: name, type: type };
// Add the item to the array
data.items.push(item);

Launch an app on OS X with command line

An application bundle (a .app file) is actually a bunch of directories. Instead of using open and the .app name, you can actually move in to it and start the actual binary. For instance:

$ cd /Applications/LittleSnapper.app/
$ ls
Contents
$ cd Contents/MacOS/
$ ./LittleSnapper

That is the actual binary that might accept arguments (or not, in LittleSnapper's case).

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

Reposting this here for others from the requests issue page:

Requests' does not support doing this before version 1. Subsequent to version 1, you are expected to subclass the HTTPAdapter, like so:

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
import ssl

class MyAdapter(HTTPAdapter):
    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=ssl.PROTOCOL_TLSv1)

When you've done that, you can do this:

import requests
s = requests.Session()
s.mount('https://', MyAdapter())

Any request through that session object will then use TLSv1.

Fatal error: Class 'ZipArchive' not found in

For Centos 7 and PHP 7.3 on Remi

Search for the zip extension:

$ yum search php73 | grep zip
php73-php-pecl-zip.x86_64 : A ZIP archive management extension

The extension name is php73-php-pecl-zip.x86_64. To install it in server running single version of PHP, remove the prefix php73:

$ sudo yum --enablerepo=remi-php73 install php-pecl-zip #for server running single PHP7.3 version
$ #sudo yum --enablerepo=remi-php73 install php73-php-pecl-zip # for server running multiple PHP versions

Restart PHP:

$ sudo systemctl restart php-fpm

Check installed PHP extensions:

$ php -m
[PHP Modules]
apcu
bcmath
bz2
...
zip
zlib

Print DIV content by JQuery

I prefer this one, I have tested it and its working

https://github.com/jasonday/printThis

$("#mySelector").printThis();

or

$("#mySelector").printThis({
*      debug: false,              * show the iframe for debugging
*      importCSS: true,           * import page CSS
*      printContainer: true,      * grab outer container as well as the contents of the selector
*      loadCSS: "path/to/my.css", * path to additional css file
*      pageTitle: "",             * add title to print page
*      removeInline: false        * remove all inline styles from print elements
*  });

Regex expressions in Java, \\s vs. \\s+

The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times

Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}?   X, exactly n times
X{n,}?  X, at least n times
X{n,m}? X, at least n but not more than m times

Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+   X, exactly n times
X{n,}+  X, at least n times
X{n,m}+ X, at least n but not more than m times

How to rename a file using Python

os.rename(old, new)

This is found in the Python docs: http://docs.python.org/library/os.html

raw vs. html_safe vs. h to unescape html

  1. html_safe :

    Marks a string as trusted safe. It will be inserted into HTML with no additional escaping performed.

    "<a>Hello</a>".html_safe
    #=> "<a>Hello</a>"
    
    nil.html_safe
    #=> NoMethodError: undefined method `html_safe' for nil:NilClass
    
  2. raw :

    raw is just a wrapper around html_safe. Use raw if there are chances that the string will be nil.

    raw("<a>Hello</a>")
    #=> "<a>Hello</a>"
    
    raw(nil)
    #=> ""
    
  3. h alias for html_escape :

    A utility method for escaping HTML tag characters. Use this method to escape any unsafe content.

    In Rails 3 and above it is used by default so you don't need to use this method explicitly

How do I sort a two-dimensional (rectangular) array in C#?

If you could get the data as a generic tuple when you read it in or retrieved it, it would be a lot easier; then you would just have to write a Sort function that compares the desired column of the tuple, and you have a single dimension array of tuples.

How to generate a random number between a and b in Ruby?

For 10 and 10**24

rand(10**24-10)+10

The type java.lang.CharSequence cannot be resolved in package declaration

Make your Project and Workspace to point to JDK7 which will resolve the issue. https://developers.google.com/eclipse/docs/jdk_compliance has given ways to modify Compliance and Facet level changes.

What character represents a new line in a text area

It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:

The element's value is defined to be the element's raw value with the following transformation applied:

Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.

Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:

Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.

However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.

To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.

Restart node upon changing a file

Follow the steps:

  1. npm install --save-dev nodemon

  2. Add the following two lines to "script" section of package.json:

"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"

as shown below:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./bin/www",
    "devstart": "nodemon ./bin/www"
}
  1. npm run devstart

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website

Namenode not getting started

Did you change conf/hdfs-site.xml dfs.name.dir?

Format namenode after you change it.

$ bin/hadoop namenode -format
$ bin/hadoop start-all.sh

Deleting array elements in JavaScript - delete vs splice

From Core JavaScript 1.5 Reference > Operators > Special Operators > delete Operator :

When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined. This holds even if you delete the last element of the array (delete a[a.length-1]).

How to downgrade python from 3.7 to 3.6

I would just recommend creating a new virtual environment and installing all the packages from the start as the wheels for some packages might have been installed for the previous version of the Python. I believe this is the safest way and you have two options.

  1. Creating a new virtual environment with venv:

    python3.6 -m venv -n new_env
    source venv_env/bin/activate
    
  2. Creating a conda environment:

    conda create -n new_env python=3.6
    conda activate new_env
    

The packages you install in an environment are built based on the Python version of the environment and if you do not carefully modify the existing environment, then, you can cause some incompatibilities between packages. That is why I would recommend a using a new environment built with Python 3.6.

iCheck check if checkbox is checked

All callbacks and functions are documented here: http://fronteed.com/iCheck/#usage

$('input').iCheck('check'); — change input's state to checked
$('input').iCheck('uncheck'); — remove checked state
$('input').iCheck('toggle'); — toggle checked state
$('input').iCheck('disable'); — change input's state to disabled
$('input').iCheck('enable'); — remove disabled state
$('input').iCheck('indeterminate'); — change input's state to indeterminate
$('input').iCheck('determinate'); — remove indeterminate state
$('input').iCheck('update'); — apply input changes, which were done outside the plugin
$('input').iCheck('destroy'); — remove all traces of iCheck

How to compare two date values with jQuery

var startDate = $('#start_date').val().replace(/-/g,'/');
var endDate = $('#end_date').val().replace(/-/g,'/');

if(startDate > endDate){
   // do your stuff here...
}

Add days Oracle SQL

You can use the plus operator to add days to a date.

order_date + 20

"FATAL: Module not found error" using modprobe

Ensure that your network is brought down before loading module:

sudo stop networking

It helped me - https://help.ubuntu.com/community/UbuntuBonding

How to set editor theme in IntelliJ Idea

It's simple please follow the below step.

  1. On IntelliJ press 'Ctrl Alt + S' [ press ctrl alt and S together], this will open 'Setting popup'
  2. In Search panel 'left top search 'Theme' keyword.
  3. In left panel itself you can see 'Appearance', click on this
  4. Right side panel you can see Theme: and drop down with following option

    • Dracula
    • IntelliJ
    • Windows

just select which ever you want and click on apply and Ok.

I hope this may work for you..enter image description here

I misunderstood question. Sorry. for editor - File->Settings->Editor->Colors &Fonts and choose your scheme.... :)

How to vertically align <li> elements in <ul>?

I assume that since you're using an XML declaration, you're not worrying about IE or older browsers.

So you can use display:table-cell and display:table-row like so:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        .toolbar ul {
            display:table-row;
        }
        .toolbar ul li
        {
            display: table-cell;
            height: 100px;
            list-style-type: none;
            margin: 10px;
            vertical-align: middle;
        }
        .toolbar ul li a {
            display:table-cell;
            vertical-align: middle;
            height:100px;
            border: solid 1px black;
        }
        .toolbar ul li.button a {
            height:50px;
            border: solid 1px black;
        }
    </style>
</head>
<body>
    <div class="toolbar">
        <ul>
            <li><a href="#">first item<br />
                first item<br />
                first item</a></li>
            <li><a href="#">second item</a></li>
            <li><a href="#">last item</a></li>
            <li class="button"><a href="#">button<br />
                button</a></li>
        </ul>
    </div>
</body>
</html>

How do I split a string by a multi-character delimiter in C#?

http://msdn.microsoft.com/en-us/library/system.string.split.aspx

Example from the docs:

string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] {"[stop]"};
string[] result;

// ...
result = source.Split(stringSeparators, StringSplitOptions.None);

foreach (string s in result)
{
    Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}

How to combine multiple inline style objects?

Need to merge the properties in object. For Example,

const boxStyle = {
  width : "50px",
  height : "50px"
};
const redBackground = {
  ...boxStyle,
  background: "red",
};
const blueBackground = {
  ...boxStyle,
  background: "blue",
}




 <div style={redBackground}></div>
 <div style={blueBackground}></div>

How to do a deep comparison between 2 objects with lodash?

An easy and elegant solution is to use _.isEqual, which performs a deep comparison:

_x000D_
_x000D_
var a = {};
var b = {};

a.prop1 = 2;
a.prop2 = { prop3: 2 };

b.prop1 = 2;
b.prop2 = { prop3: 3 };

console.log(_.isEqual(a, b)); // returns false if different
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

However, this solution doesn't show which property is different.

Use own username/password with git and bitbucket

Well, it's part of BitBucket philosophy and workflow:

  • Repository may have only one user: owner
  • For ordinary accounts (end-user's) collaboration expect "fork-pull request" workflow

i.e you can't (in usual case) commit into foreign repo under own credentials.

You have two possible solutions:

  1. "Classic" BB-way: fork repo (get owned by you repository), make changes, send pull request to origin repo
  2. Create "Team", add user-accounts as members of team, make Team owner of repository - it this case for this "Shared central" repository every team memeber can push under own credentials - inspect thg repository and TortoiseHg Team, owner of this repository, as samples

Hide/Show components in react native

In react or react native the way component hide/show or add/remove does not work like in android or iOS. Most of us think there would be the similar strategy like

View.hide = true or parentView.addSubView(childView)

But the way react native work is completely different. The only way to achieve this kind of functionality is to include your component in your DOM or remove from DOM.

Here in this example I am going set the visibility of text view based on the button click.

enter image description here

The idea behind this task is the create a state variable called state having the initial value set to false when the button click event happens then it value toggles. Now we will use this state variable during the creation of component.

import renderIf from './renderIf'

class FetchSample extends Component {
  constructor(){
    super();
    this.state ={
      status:false
    }
  }

  toggleStatus(){
    this.setState({
      status:!this.state.status
    });
    console.log('toggle button handler: '+ this.state.status);
  }

  render() {
    return (
      <View style={styles.container}>
        {renderIf(this.state.status)(
          <Text style={styles.welcome}>
            I am dynamic text View
          </Text>
        )}

        <TouchableHighlight onPress={()=>this.toggleStatus()}>
          <Text>
            touchme
          </Text>
        </TouchableHighlight>
      </View>
    );
  }
}

the only one thing to notice in this snippet is renderIf which is actually a function which will return the component passed to it based on the boolean value passed to it.

renderIf(predicate)(element)

renderif.js

'use strict';
const isFunction = input => typeof input === 'function';
export default predicate => elemOrThunk =>
  predicate ? (isFunction(elemOrThunk) ? elemOrThunk() : elemOrThunk) : null;

OraOLEDB.Oracle provider is not registered on the local machine

My team would stumble upon this issue every now and then in random machines that we would try to install our platform in (we use oracle drivers 12c ver 12.2.0.4 but we came across this bug with other versions as well)

After quite a bit of experimentation we realized what was wrong:

Said machines would have apps that were using the machine-wide oracle drivers silently locking them and preventing the oracle driver-installer from working its magic when would attempt to upgrade/reinstall said oracle-drivers. The sneakiest "app" would be websites running in IIS and the like because these apps essentially auto-start on reboot. To counter this we do the following:

  1. Disable IIS from starting automagically on restart. Do the same for any other apps/services that auto-start themselves on reboot.
  2. Uninstall any previous Oracle driver and double-check that there are no traces left behind in registry or folders.
  3. Reboot the machine
  4. (Re)Install the Oracle drivers and re-enable IIS and other auto-start apps.
  5. Reboot the machine <- This is vital. Oracle's OLE DB drivers won't work unless you reboot the machine.

If this doesn't work then rinse repeat until the OLE DB drivers work. Hope this helps someone out there struggling to figure out what's going on.

MySQL with Node.js

You can skip the ORM, builders, etc. and simplify your DB/SQL management using sqler and sqler-mdb.

-- create this file at: db/mdb/setup/create.database.sql
CREATE DATABASE IF NOT EXISTS sqlermysql
const conf = {
  "univ": {
    "db": {
      "mdb": {
        "host": "localhost",
        "username":"admin",
        "password": "mysqlpassword"
      }
    }
  },
  "db": {
    "dialects": {
      "mdb": "sqler-mdb"
    },
    "connections": [
      {
        "id": "mdb",
        "name": "mdb",
        "dir": "db/mdb",
        "service": "MySQL",
        "dialect": "mdb",
        "pool": {},
        "driverOptions": {
          "connection": {
            "multipleStatements": true
          }
        }
      }
    ]
  }
};

// create/initialize manager
const manager = new Manager(conf);
await manager.init();

// .sql file path is path to db function
const result = await manager.db.mdb.setup.create.database();

console.log('Result:', result);

// after we're done using the manager we should close it
process.on('SIGINT', async function sigintDB() {
  await manager.close();
  console.log('Manager has been closed');
});

"Could not find the main class" error when running jar exported by Eclipse

Run it like this on the command line:

java -jar /path/to/your/jar/jarFile.jar

How to use fetch in typescript

Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.

That being said, the following works...

 fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json())
      .then((res: Actor) => {
          // res is now an Actor
      });

I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...

callBack: (response: any) => void

But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...

fetch(`http://swapi.co/api/people/1/`)
  .then(res => res.json())
  .then(res => {
      if (callback) {
        callback(res);    // Client receives the response as desired type.  
      }
  });

So that a client can call it with a callback like...

(response: IApigeeResponse) => {
    // Process response as an IApigeeResponse
}

Not Able To Debug App In Android Studio

You also should have Tools->Android->Enable ADB Integration active.

Lambda function in list comprehensions

The first one creates a single lambda function and calls it ten times.

The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:

[(lambda x: x*x)(x) for x in range(10)]

Or better yet:

[x*x for x in range(10)]

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

just do this

@Override
public void onBackPressed() {
    super.onBackPressed();
}

How to redirect to action from JavaScript method?

To redirect:

function DeleteJob() {
    if (confirm("Do you really want to delete selected job/s?"))
        window.location.href = "your/url";
    else
        return false;
}

Generating UML from C++ code?

UML Studio does this quite well in my experience, and will run in "freeware mode" for small projects.

Java switch statement: Constant expression required, but it IS constant

You can use an enum like in this example:

public class MainClass {
enum Choice { Choice1, Choice2, Choice3 }
public static void main(String[] args) {
Choice ch = Choice.Choice1;

switch(ch) {
  case Choice1:
    System.out.println("Choice1 selected");
    break;
 case Choice2:
   System.out.println("Choice2 selected");
   break;
 case Choice3:
   System.out.println("Choice3 selected");
   break;
    }
  }
}

Source: Switch statement with enum

What is the difference between re.search and re.match?

You can refer the below example to understand the working of re.match and re.search

a = "123abc"
t = re.match("[a-z]+",a)
t = re.search("[a-z]+",a)

re.match will return none, but re.search will return abc.

Stopping a windows service when the stop option is grayed out

If the stop option is greyed out then your service did not indicate that it was accepting SERVICE_ACCEPT_STOP when it last called SetServiceStatus. If you're using .NET, then you need to set the CanStop property in ServiceBase.

Of course, if you're accepting stop requests, then you'd better make sure that your service can safely handle those requests, especially if your service is still progressing through its startup code.

Is there a Social Security Number reserved for testing/examples?

If your testing requires pulling quasi-real credit reports from the bureaus, the inactive SSNs of other answers won't work and you'll need designated test numbers.

I found this site Which appears to contain test social security numbers with associated test names and credit card numbers.

Transunion has a test environment you can link and send data to, including associated dummy credit reports. Sending a SSN to them with certain numbers in certain positions will automatically route the inquiry to their test environment Other credit bureaus will have similar systems in place.

Formatting html email for Outlook

To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.

Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.

From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:

  • Various types of more sophisticated selectors, e.g. E:first-child, E:hover, E > F (Child combinator), E + F (Adjacent sibling combinator), E ~ F (General sibling combinator). This unfortunately means resorting to workarounds like inline styles.
  • Some font properties, e.g. white-space won't work.
  • The background-image property won't work.
  • There are several issues with the Box Model properties, most importantly height, width, and the max- versions are either not usable or have bugs for certain elements.
  • Positioning and Display issues (e.g. display, floats and position are all out).

In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.

PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top" where you probably meant to use vertical-align. Also: cell-padding for tds doesn't exist.

Extract / Identify Tables from PDF python

You should definitely have a look at this answer of mine:

and also have a look at all the links included therein.

Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.

printing a two dimensional array in python

A combination of list comprehensions and str joins can do the job:

inf = float('inf')
A = [[0,1,4,inf,3],
     [1,0,2,inf,4],
     [4,2,0,1,5],
     [inf,inf,1,0,3],
     [3,4,5,3,0]]

print('\n'.join([''.join(['{:4}'.format(item) for item in row]) 
      for row in A]))

yields

   0   1   4 inf   3
   1   0   2 inf   4
   4   2   0   1   5
 inf inf   1   0   3
   3   4   5   3   0

Using for-loops with indices is usually avoidable in Python, and is not considered "Pythonic" because it is less readable than its Pythonic cousin (see below). However, you could do this:

for i in range(n):
    for j in range(n):
        print '{:4}'.format(A[i][j]),
    print

The more Pythonic cousin would be:

for row in A:
    for val in row:
        print '{:4}'.format(val),
    print

However, this uses 30 print statements, whereas my original answer uses just one.

Pandas read_csv from url

To Import Data through URL in pandas just apply the simple below code it works actually better.

import pandas as pd
train = pd.read_table("https://urlandfile.com/dataset.csv")
train.head()

If you are having issues with a raw data then just put 'r' before URL

import pandas as pd
train = pd.read_table(r"https://urlandfile.com/dataset.csv")
train.head()

How do I get the path of a process in Unix / Linux

In Linux every process has its own folder in /proc. So you could use getpid() to get the pid of the running process and then join it with the path /proc to get the folder you hopefully need.

Here's a short example in Python:

import os
print os.path.join('/proc', str(os.getpid()))

Here's the example in ANSI C as well:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>


int
main(int argc, char **argv)
{
    pid_t pid = getpid();

    fprintf(stdout, "Path to current process: '/proc/%d/'\n", (int)pid);

    return EXIT_SUCCESS;
}

Compile it with:

gcc -Wall -Werror -g -ansi -pedantic process_path.c -oprocess_path 

Git:nothing added to commit but untracked files present

If you have already tried using the git add . command to add all your untracked files, make sure you're not under a subfolder of your root project.

git add . will stage all your files under the current subfolder.

Modifying a subset of rows in a pandas dataframe

For a massive speed increase, use NumPy's where function.

Setup

Create a two-column DataFrame with 100,000 rows with some zeros.

df = pd.DataFrame(np.random.randint(0,3, (100000,2)), columns=list('ab'))

Fast solution with numpy.where

df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)

Timings

%timeit df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)
685 µs ± 6.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit df.loc[df['a'] == 0, 'b'] = np.nan
3.11 ms ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Numpy's where is about 4x faster

How to display an activity indicator with text on iOS 8 with Swift?

For Swift 3

enter image description here

Usage

class LoginTVC: UITableViewController {
    var loadingView : LoadingView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // CASE 1: To Show loadingView on load

        loadingView = LoadingView(uiView: view, message: "Sending you verification code")
    }

    // CASE 2: To show loadingView on click of a button

    @IBAction func showLoadingView(_ sender: UIButton) {
        if let loaderView = loadingView{ // If loadingView already exists
            if loaderView.isHidden() {
                loaderView.show()  // To show activity indicator
            }
        }
        else{
            loadingView = LoadingView(uiView: view, message: "Sending you verification code")
         }
    }
}

    // CASE 3: To hide LoadingView on click of a button

    @IBAction func hideLoadingView(_ sender: UIButton) {
        if let loaderView = loadingView{ // If loadingView already exists 
            self.loadingView.hide()   
        }
    }
}

LoadingView Class

class LoadingView {

    let uiView          :   UIView
    let message         :   String
    let messageLabel    =   UILabel()

    let loadingSV       =   UIStackView()
    let loadingView     =   UIView()
    let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)

    init(uiView: UIView, message: String) {
        self.uiView     =   uiView
        self.message    =   message
        self.setup()
    }

    func setup(){
        let viewWidth   = uiView.bounds.width
        let viewHeight  = uiView.bounds.height

        // Configuring the message label
        messageLabel.text             = message
        messageLabel.textColor        = UIColor.darkGray
        messageLabel.textAlignment    = .center
        messageLabel.numberOfLines    = 3
        messageLabel.lineBreakMode    = .byWordWrapping

        // Creating stackView to center and align Label and Activity Indicator
        loadingSV.axis          = .vertical
        loadingSV.distribution  = .equalSpacing
        loadingSV.alignment     = .center
        loadingSV.addArrangedSubview(activityIndicator)
        loadingSV.addArrangedSubview(messageLabel)

        // Creating loadingView, this acts as a background for label and activityIndicator
        loadingView.frame           = uiView.frame
        loadingView.center          = uiView.center
        loadingView.backgroundColor = UIColor.darkGray.withAlphaComponent(0.3)
        loadingView.clipsToBounds   = true

        // Disabling auto constraints
        loadingSV.translatesAutoresizingMaskIntoConstraints = false

        // Adding subviews
        loadingView.addSubview(loadingSV)
        uiView.addSubview(loadingView)
        activityIndicator.startAnimating()

        // Views dictionary
        let views = [
            "loadingSV": loadingSV
        ]

        // Constraints for loadingSV
        uiView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[loadingSV(300)]-|", options: [], metrics: nil, views: views))
        uiView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(viewHeight / 3)-[loadingSV(50)]-|", options: [], metrics: nil, views: views))
    }

    // Call this method to hide loadingView
    func show() {
        loadingView.isHidden = false
    }

    // Call this method to show loadingView
    func hide(){
        loadingView.isHidden = true
    }

    // Call this method to check if loading view already exists
    func isHidden() -> Bool{
        if loadingView.isHidden == false{
            return false
        }
        else{
            return true
        }
    }
}

How to receive serial data using android bluetooth

Take a look at incredible Bluetooth Serial class that has onResume() ability that helped me so much. I hope this helps ;)

Resize svg when window is resized in d3.js

Look for 'responsive SVG' it is pretty simple to make a SVG responsive and you don't have to worry about sizes any more.

Here is how I did it:

_x000D_
_x000D_
d3.select("div#chartId")_x000D_
   .append("div")_x000D_
   // Container class to make it responsive._x000D_
   .classed("svg-container", true) _x000D_
   .append("svg")_x000D_
   // Responsive SVG needs these 2 attributes and no width and height attr._x000D_
   .attr("preserveAspectRatio", "xMinYMin meet")_x000D_
   .attr("viewBox", "0 0 600 400")_x000D_
   // Class to make it responsive._x000D_
   .classed("svg-content-responsive", true)_x000D_
   // Fill with a rectangle for visualization._x000D_
   .append("rect")_x000D_
   .classed("rect", true)_x000D_
   .attr("width", 600)_x000D_
   .attr("height", 400);
_x000D_
.svg-container {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  padding-bottom: 100%; /* aspect ratio */_x000D_
  vertical-align: top;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.svg-content-responsive {_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 10px;_x000D_
  left: 0;_x000D_
}_x000D_
_x000D_
svg .rect {_x000D_
  fill: gold;_x000D_
  stroke: steelblue;_x000D_
  stroke-width: 5px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>_x000D_
_x000D_
<div id="chartId"></div>
_x000D_
_x000D_
_x000D_

Note: Everything in the SVG image will scale with the window width. This includes stroke width and font sizes (even those set with CSS). If this is not desired, there are more involved alternate solutions below.

More info / tutorials:

http://thenewcode.com/744/Make-SVG-Responsive

http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php

How can I generate a list of consecutive numbers?

Depending on how you want the result, you can also print each number in a for loop:

def numbers():
    for i in range(int(input('How far do you wanna go? '))+1):
        print(i)

So if the user input was 7 for example:

How far do you wanna go? 7
0
1
2
3
4
5
6
7

You can also delete the '+1' in the for loop and place it on the print statement, which will change it to starting at 1 instead of 0.

Is there a way to avoid null check before the for-each loop iteration starts?

It's already 2017, and you can now use Apache Commons Collections4

The usage:

for(Object obj : CollectionUtils.emptyIfNull(list1)){
    // Do your stuff
}

Turning Sonar off for certain code

You can annotate a class or a method with SuppressWarnings

@java.lang.SuppressWarnings("squid:S00112")

squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.

How to add new item to hash

If you want to add new items from another hash - use merge method:

hash = {:item1 => 1}
another_hash = {:item2 => 2, :item3 => 3}
hash.merge(another_hash) # {:item1=>1, :item2=>2, :item3=>3}

In your specific case it could be:

hash = {:item1 => 1}
hash.merge({:item2 => 2}) # {:item1=>1, :item2=>2}

but it's not wise to use it when you should to add just one element more.

Pay attention that merge will replace the values with the existing keys:

hash = {:item1 => 1}
hash.merge({:item1 => 2}) # {:item1=>2}

exactly like hash[:item1] = 2

Also you should pay attention that merge method (of course) doesn't effect the original value of hash variable - it returns a new merged hash. If you want to replace the value of the hash variable then use merge! instead:

hash = {:item1 => 1}
hash.merge!({:item2 => 2})
# now hash == {:item1=>1, :item2=>2}

How do I get elapsed time in milliseconds in Ruby?

%L gives milliseconds in ruby

require 'time'
puts Time.now.strftime("%Y-%m-%dT%H:%M:%S.%L")

or

puts Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")

will give you current timestamp in milliseconds.

How can I define a composite primary key in SQL?

In Oracle database we can achieve like this.

CREATE TABLE Student(
  StudentID Number(38, 0) not null,
  DepartmentID Number(38, 0) not null,
  PRIMARY KEY (StudentID, DepartmentID)
);

Smooth scroll without the use of jQuery

With using the following smooth scrolling is working fine:

_x000D_
_x000D_
html {_x000D_
  scroll-behavior: smooth;_x000D_
}
_x000D_
_x000D_
_x000D_

How to print colored text to the terminal?

If you are programming a game perhaps you would like to change the background color and use only spaces? For example:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

How to completely remove a dialog on close

$(this).dialog('destroy').remove()

This will destroy the dialog and then remove the div that was "hosting" the dialog completely from the DOM

Android Studio: Application Installation Failed

This happens when your app is using any library and there is also an app installed in your device that is using the same library. Go to gradle and type:

android{
defaultConfig.applicationId="your package"
}

this will resolve your problem.

Convert.ToDateTime: how to set format

DateTime doesn't have a format. the format only applies when you're turning a DateTime into a string, which happens implicitly you show the value on a form, web page, etc.

Look at where you're displaying the DateTime and set the format there (or amend your question if you need additional guidance).

Is an HTTPS query string secure?

SSL first connects to the host, so the host name and port number are transferred as clear text. When the host responds and the challenge succeeds, the client will encrypt the HTTP request with the actual URL (i.e. anything after the third slash) and and send it to the server.

There are several ways to break this security.

It is possible to configure a proxy to act as a "man in the middle". Basically, the browser sends the request to connect to the real server to the proxy. If the proxy is configured this way, it will connect via SSL to the real server but the browser will still talk to the proxy. So if an attacker can gain access of the proxy, he can see all the data that flows through it in clear text.

Your requests will also be visible in the browser history. Users might be tempted to bookmark the site. Some users have bookmark sync tools installed, so the password could end up on deli.ci.us or some other place.

Lastly, someone might have hacked your computer and installed a keyboard logger or a screen scraper (and a lot of Trojan Horse type viruses do). Since the password is visible directly on the screen (as opposed to "*" in a password dialog), this is another security hole.

Conclusion: When it comes to security, always rely on the beaten path. There is just too much that you don't know, won't think of and which will break your neck.

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

I find, if the data is imported, you may need to use the trim command on top of it, to get your details. =LEFT(TRIM(B2),8) In my case, I was using it to find a IP range. 10.3.44.44 with mask 255.255.255.0, so response is: 10.3.44 Kind of handy.

Why does ENOENT mean "No such file or directory"?

It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE would have been too narrow in its meaning.

How to suppress scientific notation when printing float values?

If it is a string then use the built in float on it to do the conversion for instance: print( "%.5f" % float("1.43572e-03")) answer:0.00143572

Display current date and time without punctuation

Here you go:

date +%Y%m%d%H%M%S

As man date says near the top, you can use the date command like this:

date [OPTION]... [+FORMAT]

That is, you can give it a format parameter, starting with a +. You can probably guess the meaning of the formatting symbols I used:

  • %Y is for year
  • %m is for month
  • %d is for day
  • ... and so on

You can find this, and other formatting symbols in man date.

Adding a Time to a DateTime in C#

Combine both. The Date-Time-Picker does support picking time, too.

You just have to change the Format-Property and maybe the CustomFormat-Property.

How to check if a value is not null and not empty string in JS

Both null and empty could be validated as follows:

<script>
function getName(){
    var myname = document.getElementById("Name").value;
    if(myname != '' && myname != null){
        alert("My name is "+myname);
    }else{
        alert("Please Enter Your Name");
    }       
}

What Process is using all of my disk IO

iotop with the -a flag:

-a, --accumulated     show accumulated I/O instead of bandwidth

Difference between innerText, innerHTML and value?

In simple words:

  1. innerText will show the value as is and ignores any HTML formatting which may be included.
  2. innerHTML will show the value and apply any HTML formatting.

Get the current year in JavaScript

TL;DR

Most of the answers found here are correct only if you need the current year based on your local machine's time zone and offset (client side) - source which, in most scenarios, cannot be considered reliable (beause it can differ from machine to machine).

Reliable sources are:

  • Web server's clock (but make sure that it's updated)
  • Time APIs & CDNs

Details

A method called on the Date instance will return a value based on the local time of your machine.

Further details can be found in "MDN web docs": JavaScript Date object.

For your convenience, I've added a relevant note from their docs:

(...) the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.

Another source mentioning this is: JavaScript date and time object

it is important to note that if someone's clock is off by a few hours or they are in a different time zone, then the Date object will create a different times from the one created on your own computer.

Some reliable sources that you can use are:

But if you simply don't care about the time accuracy or if your use case requires a time value relative to local machine's time then you can safely use Javascript's Date basic methods like Date.now(), or new Date().getFullYear() (for current year).

Convert json data to a html table

Check out JSON2HTML http://json2html.com/ plugin for jQuery. It allows you to specify a transform that would convert your JSON object to HTML template. Use builder on http://json2html.com/ to get json transform object for any desired html template. In your case, it would be a table with row having following transform.

Example:

var transform = {"tag":"table", "children":[
    {"tag":"tbody","children":[
        {"tag":"tr","children":[
            {"tag":"td","html":"${name}"},
            {"tag":"td","html":"${age}"}
        ]}
    ]}
]};

var data = [
    {'name':'Bob','age':40},
    {'name':'Frank','age':15},
    {'name':'Bill','age':65},
    {'name':'Robert','age':24}
];

$('#target_div').html(json2html.transform(data,transform));

Use Font Awesome Icon in Placeholder

I added both text and icon together in a placeholder.

placeholder="Edit &nbsp; &#xf040;"

CSS :

font-family: FontAwesome,'Merriweather Sans', sans-serif;

How do I shrink my SQL Server Database?

ALTER DATABASE MyDatabase SET RECOVERY SIMPLE

GO

DBCC SHRINKFILE (MyDatabase_Log, 5)

GO

ALTER DATABASE MyDatabase SET RECOVERY FULL

GO

Using HttpClient and HttpPost in Android with post parameters

I've just checked and i have the same code as you and it works perferctly. The only difference is how i fill my List for the params :

I use a : ArrayList<BasicNameValuePair> params

and fill it this way :

 params.add(new BasicNameValuePair("apikey", apikey);

I do not use any JSONObject to send params to the webservices.

Are you obliged to use the JSONObject ?

How to include a class in PHP

Include a class example with the use keyword from Command Line Interface:

PHP Namespaces don't work on the commandline unless you also include or require the php file. When the php file is sitting in the webspace where it is interpreted by the php daemon then you don't need the require line. All you need is the 'use' line.

  1. Create a new directory /home/el/bin

  2. Make a new file called namespace_example.php and put this code in there:

    <?php
        require '/home/el/bin/mylib.php';
        use foobarwhatever\dingdong\penguinclass;
    
        $mypenguin = new penguinclass();
        echo $mypenguin->msg();
    ?>
    
  3. Make another file called mylib.php and put this code in there:

    <?php
    namespace foobarwhatever\dingdong;
    class penguinclass 
    {
        public function msg() {
            return "It's a beautiful day chris, come out and play! " . 
                   "NO!  *SLAM!*  taka taka taka taka."; 
        }   
    }
    ?>   
    
  4. Run it from commandline like this:

    el@apollo:~/bin$ php namespace_example.php 
    
  5. Which prints:

    It's a beautiful day chris, come out and play!
    NO!  *SLAM!*  taka taka taka taka
    

See notes on this in the comments here: http://php.net/manual/en/language.namespaces.importing.php

JS regex: replace all digits in string

The /g modifier is used to perform a global match (find all matches rather than stopping after the first)

You can use \d for digit, as it is shorter than [0-9].

JavaScript:

var s = "04.07.2012"; 
echo(s.replace(/\d/g, "X"));

Output:

XX.XX.XXXX

Partly cherry-picking a commit with Git

Assuming the changes you want are at the head of the branch you want the changes from, use git checkout

for a single file :

git checkout branch_that_has_the_changes_you_want path/to/file.rb

for multiple files just daisy chain :

git checkout branch_that_has_the_changes_you_want path/to/file.rb path/to/other_file.rb

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

open failed: EACCES (Permission denied)

In my case I used the option android:isolatedProcess="true" for a service in the AndroidManifest.xml.

As soon as I removed it, the error disappeared...

Strip out HTML and Special Characters

You can do it in one single line :) specially useful for GET or POST requests

$clear = preg_replace('/[^A-Za-z0-9\-]/', '', urldecode($_GET['id']));

find: missing argument to -exec

I figured it out now. When you need to run two commands in exec in a find you need to actually have two separate execs. This finally worked for me.

find . -type f -name "*.rm" -exec ffmpeg -i {} -sameq {}.mp3 \; -exec rm {} \;

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

Just solve the problem which come from java compiler instead of Build-Run task

How do I get an Excel range using row and column numbers in VSTO / C#?

Facing the same problem I found the quickest solution was to actually scan the rows of the cells I wished to sort, determine the last row with a non-blank element and then select and sort on that grouping.

    Dim lastrow As Integer
lastrow = 0
For r = 3 To 120
   If Cells(r, 2) = "" Then
        Dim rng As Range
        Set rng = Range(Cells(3, 2), Cells(r - 1, 2 + 6))
        rng.Select
        rng.Sort Key1:=Range("h3"), order1:=xlDescending, Header:=xlGuess, DataOption1:=xlSortNormal
        r = 205
    End If
Next r

iPhone get SSID without private library

For iOS 13

As from iOS 13 your app also needs Core Location access in order to use the CNCopyCurrentNetworkInfo function unless it configured the current network or has VPN configurations:
excerpt from https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo?language=objc

So this is what you need (see apple documentation):
- Link the CoreLocation.framework library
- Add location-services as a UIRequiredDeviceCapabilities Key/Value in Info.plist
- Add a NSLocationWhenInUseUsageDescription Key/Value in Info.plist describing why your app requires Core Location
- Add the "Access WiFi Information" entitlement for your app

Now as an Objective-C example, first check if location access has been accepted before reading the network info using CNCopyCurrentNetworkInfo:

- (void)fetchSSIDInfo {
    NSString *ssid = NSLocalizedString(@"not_found", nil);

    if (@available(iOS 13.0, *)) {
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
            NSLog(@"User has explicitly denied authorization for this application, or location services are disabled in Settings.");
        } else {
            CLLocationManager* cllocation = [[CLLocationManager alloc] init];
            if(![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
                [cllocation requestWhenInUseAuthorization];
                usleep(500);
                return [self fetchSSIDInfo];
            }
        }
    }

    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo(
            (__bridge CFStringRef)ifnam);

        NSDictionary *infoDict = (NSDictionary *)info;
        for (NSString *key in infoDict.allKeys) {
            if ([key isEqualToString:@"SSID"]) {
                ssid = [infoDict objectForKey:key];
            }
        }
    }        
        ...
    ...
}

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

I just went through troubleshooting this issue, and in my case it indeed was related to redirects, but not related to incorrect settings in my CloudFront Origin or Behavior. This will happen if your origin server is still redirecting to origin URLs, and not what you have set up for your cloudfront URLs. Seems this is very common if you forget to change configs. For example lets say if you have www.yoursite.com CNAME to your cloudfront distribution, with an origin of www.yoursiteorigin.com. Obviously people will come to www.yoursite.com. But if your code tries to redirect to any page on www.yoursiteorigin.com you WILL get this error.

For me, my origin was still doing the http->https redirects to my origin URLs and not my Cloudfront URLs.

How to get Last record from Sqlite?

I think it would be better if you use the method query from SQLiteDatabase class instead of the whole SQL string, which would be:

 Cursor cursor = sqLiteDatabase.query(TABLE, allColluns, null, null, null, null, ID +" DESC", "1");

The last two parameters are ORDER BY and LIMIT.

You can see more at: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

Detecting the character encoding of an HTTP POST request

The Charset used in the POST will match that of the Charset specified in the HTML hosting the form. Hence if your form is sent using UTF-8 encoding that is the encoding used for the posted content. The URL encoding is applied after the values are converted to the set of octets for the character encoding.

bootstrap 3 tabs not working properly

for some weird reason bootstrap tabs were not working for me until i was using href like:-

<li class="nav-item"><a class="nav-link" href="#a" data-toggle="tab">First</a></li>

but it started working as soon as i replaced href with data-target like:-

<li class="nav-item"><a class="nav-link" data-target="#a" data-toggle="tab">First</a></li>

How to use Macro argument as string literal?

You want to use the stringizing operator:

#define STRING(s) #s

int main()
{
    const char * cstr = STRING(abc); //cstr == "abc"
}

Show or hide element in React

Here is my approach.

import React, { useState } from 'react';

function ToggleBox({ title, children }) {
  const [isOpened, setIsOpened] = useState(false);

  function toggle() {
    setIsOpened(wasOpened => !wasOpened);
  }

  return (
    <div className="box">
      <div className="boxTitle" onClick={toggle}>
        {title}
      </div>
      {isOpened && (
        <div className="boxContent">
          {children}
        </div>
      )}
    </div>
  );
}

In code above, to achieve this, I'm using code like:

{opened && <SomeElement />}

That will render SomeElement only if opened is true. It works because of the way how JavaScript resolve logical conditions:

true && true && 2; // will output 2
true && false && 2; // will output false
true && 'some string'; // will output 'some string'
opened && <SomeElement />; // will output SomeElement if `opened` is true, will output false otherwise (and false will be ignored by react during rendering)
// be careful with 'falsy' values eg
const someValue = 0;
someValue && <SomeElement /> // will output 0, which will be rednered by react
// it'll be better to:
!!someValue && <SomeElement /> // will render nothing as we cast the value to boolean

Reasons for using this approach instead of CSS 'display: none';

  • While it might be 'cheaper' to hide an element with CSS - in such case 'hidden' element is still 'alive' in react world (which might make it actually way more expensive)
    • it means that if props of the parent element (eg. <TabView>) will change - even if you see only one tab, all 5 tabs will get re-rendered
    • the hidden element might still have some lifecycle methods running - eg. it might fetch some data from the server after every update even tho it's not visible
    • the hidden element might crash the app if it'll receive incorrect data. It might happen as you can 'forget' about invisible nodes when updating the state
    • you might by mistake set wrong 'display' style when making element visible - eg. some div is 'display: flex' by default, but you'll set 'display: block' by mistake with display: invisible ? 'block' : 'none' which might break the layout
    • using someBoolean && <SomeNode /> is very simple to understand and reason about, especially if your logic related to displaying something or not gets complex
    • in many cases, you want to 'reset' element state when it re-appears. eg. you might have a slider that you want to set to initial position every time it's shown. (if that's desired behavior to keep previous element state, even if it's hidden, which IMO is rare - I'd indeed consider using CSS if remembering this state in a different way would be complicated)

Get exception description and stack trace which caused an exception, all as a string

You might also consider using the built-in Python module, cgitb, to get some really good, nicely formatted exception information including local variable values, source code context, function parameters etc..

For instance for this code...

import cgitb
cgitb.enable(format='text')

def func2(a, divisor):
    return a / divisor

def func1(a, b):
    c = b - 5
    return func2(a, c)

func1(1, 5)

we get this exception output...

ZeroDivisionError
Python 3.4.2: C:\tools\python\python.exe
Tue Sep 22 15:29:33 2015

A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred.

 c:\TEMP\cgittest2.py in <module>()
    7 def func1(a, b):
    8   c = b - 5
    9   return func2(a, c)
   10
   11 func1(1, 5)
func1 = <function func1>

 c:\TEMP\cgittest2.py in func1(a=1, b=5)
    7 def func1(a, b):
    8   c = b - 5
    9   return func2(a, c)
   10
   11 func1(1, 5)
global func2 = <function func2>
a = 1
c = 0

 c:\TEMP\cgittest2.py in func2(a=1, divisor=0)
    3
    4 def func2(a, divisor):
    5   return a / divisor
    6
    7 def func1(a, b):
a = 1
divisor = 0
ZeroDivisionError: division by zero
    __cause__ = None
    __class__ = <class 'ZeroDivisionError'>
    __context__ = None
    __delattr__ = <method-wrapper '__delattr__' of ZeroDivisionError object>
    __dict__ = {}
    __dir__ = <built-in method __dir__ of ZeroDivisionError object>
    __doc__ = 'Second argument to a division or modulo operation was zero.'
    __eq__ = <method-wrapper '__eq__' of ZeroDivisionError object>
    __format__ = <built-in method __format__ of ZeroDivisionError object>
    __ge__ = <method-wrapper '__ge__' of ZeroDivisionError object>
    __getattribute__ = <method-wrapper '__getattribute__' of ZeroDivisionError object>
    __gt__ = <method-wrapper '__gt__' of ZeroDivisionError object>
    __hash__ = <method-wrapper '__hash__' of ZeroDivisionError object>
    __init__ = <method-wrapper '__init__' of ZeroDivisionError object>
    __le__ = <method-wrapper '__le__' of ZeroDivisionError object>
    __lt__ = <method-wrapper '__lt__' of ZeroDivisionError object>
    __ne__ = <method-wrapper '__ne__' of ZeroDivisionError object>
    __new__ = <built-in method __new__ of type object>
    __reduce__ = <built-in method __reduce__ of ZeroDivisionError object>
    __reduce_ex__ = <built-in method __reduce_ex__ of ZeroDivisionError object>
    __repr__ = <method-wrapper '__repr__' of ZeroDivisionError object>
    __setattr__ = <method-wrapper '__setattr__' of ZeroDivisionError object>
    __setstate__ = <built-in method __setstate__ of ZeroDivisionError object>
    __sizeof__ = <built-in method __sizeof__ of ZeroDivisionError object>
    __str__ = <method-wrapper '__str__' of ZeroDivisionError object>
    __subclasshook__ = <built-in method __subclasshook__ of type object>
    __suppress_context__ = False
    __traceback__ = <traceback object>
    args = ('division by zero',)
    with_traceback = <built-in method with_traceback of ZeroDivisionError object>

The above is a description of an error in a Python program.  Here is
the original traceback:

Traceback (most recent call last):
  File "cgittest2.py", line 11, in <module>
    func1(1, 5)
  File "cgittest2.py", line 9, in func1
    return func2(a, c)
  File "cgittest2.py", line 5, in func2
    return a / divisor
ZeroDivisionError: division by zero

JQuery How to extract value from href tag?

First of all you need to extract the path with something like this:

$("a#myLink").attr("href");

Then take a look at this plugin: http://plugins.jquery.com/project/query-object

It will help you handle all kinds of querystring things you want to do.

/Peter F

In jQuery, how do I get the value of a radio button when they all have the same name?

There is another way also. Try below code

$(document).ready(function(){

      $("input[name='gender']").on("click", function() {
            alert($(this).val());
        });
});

How to redirect Valgrind's output to a file?

By default, Valgrind writes its output to stderr. So you need to do something like:

valgrind a.out > log.txt 2>&1

Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).

python inserting variable string as file name

And with the new string formatting method...

f = open('{0}.csv'.format(name), 'wb')

is there a post render callback for Angular JS directive?

You can use the 'link' function, also known as postLink, which runs after the template is put in.

app.directive('myDirective', function() {
  return {
    link: function(scope, elm, attrs) { /*I run after template is put in */ },
    template: '<b>Hello</b>'
  }
});

Give this a read if you plan on making directives, it's a big help: http://docs.angularjs.org/guide/directive

Is there a simple JavaScript slider?

A simple slider: I have just tested this in pure HTML5, and it's so simple !

<input type="range">

It works like a charm on Chrome. I've not tested other browsers yet.

Style child element when hover on parent

Yes, you can do this use this below code it may help you.

_x000D_
_x000D_
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
  display : block;_x000D_
  padding : 10px;_x000D_
  text-align : center;_x000D_
  border: 5px solid #000;_x000D_
  margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
  <div class="childDiv1">_x000D_
    First Div Child_x000D_
  </div>_x000D_
  <div class="childDiv2">_x000D_
    Second Div Child_x000D_
  </div>_x000D_
  <div class="childDiv3">_x000D_
    Third Div Child_x000D_
  </div>_x000D_
  <div class="childDiv4">_x000D_
    Fourth Div Child_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to define multiple CSS attributes in jQuery?

Agree with redsquare however it is worth mentioning that if you have a two word property like text-align you would do this:

$("#message").css({ width: '30px', height: '10px', 'text-align': 'center'});

How to make JQuery-AJAX request synchronous

Can you try this,

var ajaxSubmit = function(formE1) {

            var password = $.trim($('#employee_password').val());

             $.ajax({
                type: "POST",
                async: "false",
                url: "checkpass.php",
                data: "password="+password,
                success: function(html) {
                    var arr=$.parseJSON(html);
                    if(arr == "Successful")
                    { 
                         **$("form[name='form']").submit();**
                        return true;
                    }
                    else
                    {    return false;
                    }
                }
            });
              **return false;**
        }

How do I launch a program from command line without opening a new cmd window?

In Windows 7+ the first quotations will be the title to the cmd window to open the program:

start "title" "C:\path\program.exe"

Formatting your command like the above will temporarily open a cmd window that goes away as fast as it comes up so you really never see it. It also allows you to open more than one program without waiting for the first one to close first.

HTTP response code for POST when resource already exists

Another potential treatment is using PATCH after all. A PATCH is defined as something that changes the internal state and is not restricted to appending.

PATCH would solve the problem by allowing you to update already existing items. See: RFC 5789: PATCH

How to make a background 20% transparent on Android

Make the color have 80% in the alpha channel. For example, for red use #CCFF0000:

<TextView
   ...
   android:background="#CCFF0000" />

In the example, CC is the hexadecimal number for 255 * 0.8 = 204. Note that the first two hexadecimal digits are for the alpha channel. The format is #AARRGGBB, where AA is the alpha channel, RR is the red channel, GG is the green channel and BB is the blue channel.

I'm assuming that 20% transparent means 80% opaque. If you meant the other way, instead of CC use 33 which is the hexadecimal for 255 * 0.2 = 51.

In order to calculate the proper value for an alpha transparency value you can follow this procedure:

  1. Given a transparency percentage, for example 20%, you know the opaque percentage value is 80% (this is 100-20=80)
  2. The range for the alpha channel is 8 bits (2^8=256), meaning the range goes from 0 to 255.
  3. Project the opaque percentage into the alpha range, that is, multiply the range (255) by the percentage. In this example 255 * 0.8 = 204. Round to the nearest integer if needed.
  4. Convert the value obtained in 3., which is in base 10, to hexadecimal (base 16). You can use Google for this or any calculator. Using Google, type "204 to hexa" and it will give you the hexadecimal value. In this case it is 0xCC.
  5. Prepend the value obtained in 4. to the desired color. For example, for red, which is FF0000, you will have CCFF0000.

You can take a look at the Android documentation for colors.

Generate PDF from Swagger API documentation

Handy way: Using Browser Printing/Preview

  1. Hide editor pane
  2. Print Preview (I used firefox, others also fine)
  3. Change its page setup and print to pdf

enter image description here

find if an integer exists in a list of integers

As long as your list is initialized with values and that value actually exists in the list, then Contains should return true.

I tried the following:

var list = new List<int> {1,2,3,4,5};
var intVar = 4;
var exists = list.Contains(intVar);

And exists is indeed set to true.

Bash ignoring error for a particular command

I have been using the snippet below when working with CLI tools and I want to know if some resource exist or not, but I don't care about the output.

if [ -z "$(cat no_exist 2>&1 >/dev/null)" ]; then
    echo "none exist actually exist!"
fi

Convert integers to strings to create output filenames at run time

Here is my subroutine approach to this problem. it transforms an integer in the range 0 : 9999 as a character. For example, the INTEGER 123 is transformed into the character 0123. hope it helps.

P.S. - sorry for the comments; they make sense in Romanian :P

 subroutine nume_fisier (i,filename_tot)

   implicit none
   integer :: i

   integer :: integer_zeci,rest_zeci,integer_sute,rest_sute,integer_mii,rest_mii
   character(1) :: filename1,filename2,filename3,filename4
   character(4) :: filename_tot

! Subrutina ce transforma un INTEGER de la 0 la 9999 in o serie de CARACTERE cu acelasi numar

! pentru a fi folosite in numerotarea si denumirea fisierelor de rezultate.

 if(i<=9) then

  filename1=char(48+0)
  filename2=char(48+0)
  filename3=char(48+0)
  filename4=char(48+i)  

 elseif(i>=10.and.i<=99) then

  integer_zeci=int(i/10)
  rest_zeci=mod(i,10)
  filename1=char(48+0)
  filename2=char(48+0)
  filename3=char(48+integer_zeci)
  filename4=char(48+rest_zeci)

 elseif(i>=100.and.i<=999) then

  integer_sute=int(i/100)
  rest_sute=mod(i,100)
  integer_zeci=int(rest_sute/10)
  rest_zeci=mod(rest_sute,10)
  filename1=char(48+0)
  filename2=char(48+integer_sute)
  filename3=char(48+integer_zeci)
  filename4=char(48+rest_zeci)

 elseif(i>=1000.and.i<=9999) then

  integer_mii=int(i/1000)
  rest_mii=mod(i,1000)
  integer_sute=int(rest_mii/100)
  rest_sute=mod(rest_mii,100)
  integer_zeci=int(rest_sute/10)
  rest_zeci=mod(rest_sute,10)
  filename1=char(48+integer_mii)
  filename2=char(48+integer_sute)
  filename3=char(48+integer_zeci) 
  filename4=char(48+rest_zeci)

 endif

 filename_tot=''//filename1//''//filename2//''//filename3//''//filename4//''
 return
 end subroutine nume_fisier

How to check if a particular service is running on Ubuntu

For Ubuntu (checked with 12.04)

You can get list of all services and select by color one of them with 'grep':

sudo service --status-all | grep postgres

Or you may use another way if you know correct name of service:

sudo service postgresql status

How do I rotate text in css?

You need to use the CSS3 transform property rotate - see here for which browsers support it and the prefix you need to use.

One example for webkit browsers is -webkit-transform: rotate(-90deg);

Edit: The question was changed substantially so I have added a demo that works in Chrome/Safari (as I only included the -webkit- CSS prefixed rules). The problem you have is that you do not want to rotate the title div, but simply the text inside it. If you remove your rotation, the <div>s are in the correct position and all you need to do is wrap the text in an element and rotate that instead.

There already exists a more customisable widget as part of the jQuery UI - see the accordion demo page. I am sure with some CSS cleverness you should be able to make the accordion vertical and also rotate the title text :-)

Edit 2: I had anticipated the text center problem and have already updated my demo. There is a height/width constraint though, so longer text could still break the layout.

Edit 3: It looks like the horizontal version was part of the original plan but I cannot see any way of configuring it on the demo page. I was incorrect… the new accordion is part of the upcoming jQuery UI 1.9! So you could try the development builds if you want the new functionality.

Hope this helps!

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

HTML Tags in Javascript Alert() method

alert() is a method of the window object that cannot interpret HTML tags

onclick open window and specific size

<a href="/index2.php?option=com_jumi&amp;fileid=3&amp;Itemid=11"
   onclick="window.open(this.href,'targetWindow',
                                   `toolbar=no,
                                    location=no,
                                    status=no,
                                    menubar=no,
                                    scrollbars=yes,
                                    resizable=yes,
                                    width=SomeSize,
                                    height=SomeSize`);
 return false;">Popup link</a>

Where width and height are pixels without units (width=400 not width=400px).

In most browsers it will not work if it is not written without line breaks, once the variables are setup have everything in one line:

<a href="/index2.php?option=com_jumi&amp;fileid=3&amp;Itemid=11" onclick="window.open(this.href,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=SomeSize,height=SomeSize'); return false;">Popup link</a> 

How to format dateTime in django template?

I suspect wpis.entry.lastChangeDate has been somehow transformed into a string in the view, before arriving to the template.

In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper, and then see if the template crashes.

You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.

On an unrelated notice, why don't you use models.DateTimeField(auto_now_add=True) to set the datetime on creation?

correct way of comparing string jquery operator =

NO, when you are using only one "=" you are assigning the variable.

You must use "==" : You must use "===" :

if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
 $("#code").text(data.DATA[0].ID);
}

You could use fonction like .toLowerCase() to avoid case problem if you want

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT i.e 204 No Content as in place of HttpStatus.OK

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

Any value of T will be ignored for 204, but not for 404

  public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
            LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
            final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
            LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$

            if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
                LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
                 return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
            } else {
               LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
                return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
            }

    }

How to change Maven local repository in eclipse

In general, these answer the question: How to change your user settings file? But the question I wanted answered was how to change my local maven repository location. The answer is that you have to edit settings.xml. If the file does not exist, you have to create it. You set or change the location of the file at Window > Preferences > Maven > User Settings. It's the User Settings entry at

Maven User Settings dialog

It's the second file input; the first with information in it.

If it's not clear, [redacted] should be replaced with the local file path to your .m2 folder.

If you click the "open file" link, it opens the settings.xml file for editing in Eclipse.

If you have no settings.xml file yet, the following will set the local repository to the Windows 10 default value for a user named mdfst13:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              https://maven.apache.org/xsd/settings-1.0.0.xsd">

  <localRepository>C:\Users\mdfst13\.m2\repository</localRepository>
</settings>

You should set this to a value appropriate to your system. I haven't tested it, but I suspect that in Linux, the default value would be /home/mdfst13/.m2/repository. And of course, you probably don't want to set it to the default value. If you are reading this, you probably want to set it to some other value. You could just delete it if you wanted the default.

Credit to this comment by @ejaenv for the name of the element in the settings file: <localRepository>. See Maven — Settings Reference for more information.

Credit to @Ajinkya's answer for specifying the location of the User Settings value in Eclipse Photon.

If you already have a settings.xml file, you should merge this into your existing file. I.e. <settings and <localRepository> should only appear once in the file, and you probably want to retain any settings already there. Or to say that another way, edit any existing local repository entry if it exists or just add that line to the file if it doesn't.

I had to restart Eclipse for it to load data into the new repository. Neither "Update Settings" nor "Reindex" was sufficient.

How to prevent vim from creating (and leaving) temporary files?

I'd strongly recommend to keep working with swap files (in case Vim crashes).

You can set the directory where the swap files are stored, so they don't clutter your normal directories:

set swapfile
set dir=~/tmp

See also

:help swap-file

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

Delete last N characters from field in a SQL Server database

UPDATE mytable SET column=LEFT(column, LEN(column)-5)

Removes the last 5 characters from the column (every row in mytable)

Passing two command parameters using a WPF binding

If your values are static, you can use x:Array:

<Button Command="{Binding MyCommand}">10
  <Button.CommandParameter>
    <x:Array Type="system:Object">
       <system:String>Y</system:String>
       <system:Double>10</system:Double>
    </x:Array>
  </Button.CommandParameter>
</Button>

generating variable names on fly in python

I got your problem , and here is my answer:

prices = [5, 12, 45]
list=['1','2','3']

for i in range(1,3):
  vars()["prices"+list[0]]=prices[0]
print ("prices[i]=" +prices[i])

so while printing:

price1 = 5 
price2 = 12
price3 = 45

Swift presentViewController

Swift 3 and Swift 4

let vc = self.storyboard?.instantiateViewController(withIdentifier: "idMyViewControllerName") as! MyViewControllerName
self.present(vc, animated: true, completion: nil)

React ignores 'for' attribute of the label element

For React you must use it's per-define keywords to define html attributes.

class -> className

is used and

for -> htmlFor

is used, as react is case sensitive make sure you must follow small and capital as required.

How to convert an int to a hex string?

With format(), as per format-examples, we can do:

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Create a new "Empty Project" , Add your Cpp file to the new project, delete the line that includes stdafx.

Done.

The project no longer needs the stdafx. It is added automatically when you create projects with installed templates. enter image description here

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

To solve the issue try to repair the .net framework 4 and then run the command

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup....

manifest.json

{
  "name": "Get pages source",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Get pages source from a popup",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

getPagesSource.js

// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);

function DOMtoString(document_root) {
    var html = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            html += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            html += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            html += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            html += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
            break;
        }
        node = node.nextSibling;
    }
    return html;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

Same question : how-to-update-the-gui-from-another-thread-in-c

Two Ways:

  1. Return value in e.result and use it to set yout textbox value in backgroundWorker_RunWorkerCompleted event

  2. Declare some variable to hold these kind of values in a separate class (which will work as data holder) . Create static instance of this class adn you can access it over any thread.

Example:

public  class data_holder_for_controls
{
    //it will hold value for your label
    public  string status = string.Empty;
}

class Demo
{
    public static  data_holder_for_controls d1 = new data_holder_for_controls();
    static void Main(string[] args)
    {
        ThreadStart ts = new ThreadStart(perform_logic);
        Thread t1 = new Thread(ts);
        t1.Start();
        t1.Join();
        //your_label.Text=d1.status; --- can access it from any thread 
    }

    public static void perform_logic()
    {
        //put some code here in this function
        for (int i = 0; i < 10; i++)
        {
            //statements here
        }
        //set result in status variable
        d1.status = "Task done";
    }
}

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The answer by Leos Literak is correct but now outdated, using one of the troublesome old date-time classes, java.sql.Timestamp.

tl;dr

it is really a DATETIME in the DB

Nope, it is not. No such data type as DATETIME in Oracle database.

I was looking for a getDateTime method.

Use java.time classes in JDBC 4.2 and later rather than troublesome legacy classes seen in your Question. In particular, rather than java.sql.TIMESTAMP, use Instant class for a moment such as the SQL-standard type TIMESTAMP WITH TIME ZONE.

Contrived code snippet:

if( 
    JDBCType.valueOf( 
        myResultSetMetaData.getColumnType( … )
    )
    .equals( JDBCType.TIMESTAMP_WITH_TIMEZONE ) 
) {
    Instant instant = myResultSet.getObject( … , Instant.class ) ;
}

Oddly enough, the JDBC 4.2 specification does not require support for the two most commonly used java.time classes, Instant and ZonedDateTime. So if your JDBC does not support the code seen above, use OffsetDateTime instead.

OffsetDateTime offsetDateTime = myResultSet.getObject( … , OffsetDateTime.class ) ;

Details

I would like to get the DATETIME column from an Oracle DB Table with JDBC.

According to this doc, there is no column data type DATETIME in the Oracle database. That terminology seems to be Oracle’s word to refer to all their date-time types as a group.

I do not see the point of your code that detects the type and branches on which data-type. Generally, I think you should be crafting your code explicitly in the context of your particular table and particular business problem. Perhaps this would be useful in some kind of generic framework. If you insist, read on to learn about various types, and to learn about the extremely useful new java.time classes built into Java 8 and later that supplant the classes used in your Question.

Smart objects, not dumb strings

valueToInsert = aDate.toString();

You appear to trying to exchange date-time values with your database as text, as String objects. Don’t.

To exchange date-time values with your database, use date-time objects. Now in Java 8 and later, that means java.time objects, as discussed below.

Various type systems

You may be confusing three sets of date-time related data types:

  • Standard SQL types
  • Proprietary types
  • JDBC types

SQL standard types

The SQL standard defines five types:

  • DATE
  • TIME WITHOUT TIME ZONE
  • TIME WITH TIME ZONE
  • TIMESTAMP WITHOUT TIME ZONE
  • TIMESTAMP WITH TIME ZONE

Date-only

  • DATE
    Date only, no time, no time zone.

Time-Of-Day-only

  • TIME or TIME WITHOUT TIME ZONE
    Time only, no date. Silently ignores any time zone specified as part of input.
  • TIME WITH TIME ZONE (or TIMETZ)
    Time only, no date. Applies time zone and Daylight Saving Time rules if sufficient data is included with input. Of questionable usefulness given the other data types, as discussed in Postgres doc.

Date And Time-Of-Day

  • TIMESTAMP or TIMESTAMP WITHOUT TIME ZONE
    Date and time, but ignores time zone. Any time zone information passed to the database is ignores with no adjustment to UTC. So this does not represent a specific moment on the timeline, but rather a range of possible moments over about 26-27 hours. Use this if the time zone or offset are (a) unknown or (b) irrelevant such as "All our factories around the world close at noon for lunch". If you have any doubts, not likely the right type.
  • TIMESTAMP WITH TIME ZONE (or TIMESTAMPTZ)
    Date and time with respect for time zone. Note that this name is something of a misnomer depending on the implementation. Some systems may store the given time zone info. In other systems such as Postgres the time zone information is not stored, instead the time zone information passed to the database is used to adjust the date-time to UTC.

Proprietary

Many database offer their own date-time related types. The proprietary types vary widely. Some are old, legacy types that should be avoided. Some are believed by the vendor to offer certain benefits; you decide whether to stick with the standard types only or not. Beware: Some proprietary types have a name conflicting with a standard type; I’m looking at you Oracle DATE.

JDBC

The Java platform's handles the internal details of date-time differently than does the SQL standard or specific databases. The job of a JDBC driver is to mediate between these differences, to act as a bridge, translating the types and their actual implemented data values as needed. The java.sql.* package is that bridge.

JDBC legacy classes

Prior to Java 8, the JDBC spec defined 3 types for date-time work. The first two are hacks as before Version 8, Java lacked any classes to represent a date-only or time-only value.

  • java.sql.Date
    Simulates a date-only, pretends to have no time, no time zone. Can be confusing as this class is a wrapper around java.util.Date which tracks both date and time. Internally, the time portion is set to zero (midnight UTC).
  • java.sql.Time
    Time only, pretends to have no date, and no time zone. Can also be confusing as this class too is a thin wrapper around java.util.Date which tracks both date and time. Internally, the date is set to zero (January 1, 1970).
  • java.sql.TimeStamp
    Date and time, but no time zone. This too is a thin wrapper around java.util.Date.

So that answers your question regarding no "getDateTime" method in the ResultSet interface. That interface offers getter methods for the three bridging data types defined in JDBC:

Note that the first lack any concept of time zone or offset-from-UTC. The last one, java.sql.Timestamp is always in UTC despite what its toString method tells you.

JDBC modern classes

You should avoid those poorly-designed JDBC classes listed above. They are supplanted by the java.time types.

  • Instead of java.sql.Date, use LocalDate. Suits SQL-standard DATE type.
  • Instead of java.sql.Time, use LocalTime. Suits SQL-standard TIME WITHOUT TIME ZONE type.
  • Instead of java.sql.Timestamp, use Instant. Suits SQL-standard TIMESTAMP WITH TIME ZONE type.

As of JDBC 4.2 and later, you can directly exchange java.time objects with your database. Use setObject/getObject methods.

Insert/update.

myPreparedStatement.setObject( … , instant ) ;

Retrieval.

Instant instant = myResultSet.getObject( … , Instant.class ) ;

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Adjusting time zone

If you want to see the moment of an Instant as viewed through the wall-clock time used by the people of a particular region (a time zone) rather than as UTC, adjust by applying a ZoneId to get a ZonedDateTime object.

ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;

The resulting ZonedDateTime object is the same moment, the same simultaneous point on the timeline. A new day dawns earlier to the east, so the date and time-of-day will differ. For example, a few minutes after midnight in New Zealand is still “yesterday” in UTC.

You can apply yet another time zone to either the Instant or ZonedDateTime to see the same simultaneous moment through yet another wall-clock time used by people in some other region.

ZoneId zMontréal = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtMontréal = zdtAuckland.withZoneSameInstant( zMontréal ) ;  // Or, for the same effect: instant.atZone( zMontréal ) 

So now we have three objects (instant, zdtAuckland, zMontréal) all representing the same moment, same point on the timeline.

Detecting type

To get back to the code in Question about detecting the data-type of the databases: (a) not my field of expertise, (b) I would avoid this as mentioned up top, and (c) if you insist on this, beware that as of Java 8 and later, the java.sql.Types class is outmoded. That class is now replaced by a proper Java Enum of JDBCType that implements the new interface SQLType. See this Answer to a related Question.

This change is listed in JDBC Maintenance Release 4.2, sections 3 & 4. To quote:

Addition of the java.sql.JDBCType Enum

An Enum used to identify generic SQL Types, called JDBC Types. The intent is to use JDBCType in place of the constants defined in Types.java.

The enum has the same values as the old class, but now provides type-safety.

A note about syntax: In modern Java, you can use a switch on an Enum object. So no need to use cascading if-then statements as seen in your Question. The one catch is that the enum object’s name must be used unqualified when switching for some obscure technical reason, so you must do your switch on TIMESTAMP_WITH_TIMEZONE rather than the qualified JDBCType.TIMESTAMP_WITH_TIMEZONE. Use a static import statement.

So, all that is to say that I guess (I’ve not tried yet) you can do something like the following code example.

final int columnType = myResultSetMetaData.getColumnType( … ) ;
final JDBCType jdbcType = JDBCType.valueOf( columnType ) ;

switch( jdbcType ) {  

    case DATE :  // FYI: Qualified type name `JDBCType.DATE` not allowed in a switch, because of an obscure technical issue. Use a `static import` statement.
        …
        break ;

    case TIMESTAMP_WITH_TIMEZONE :
        …
        break ;

    default :
        … 
        break ;

}

enter image description here


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes. This section left intact as history.

Joda-Time

Prior to Java 8 (java.time.* package), the date-time classes bundled with java (java.util.Date & Calendar, java.text.SimpleDateFormat) are notoriously troublesome, confusing, and flawed.

A better practice is to take what your JDBC driver gives you and from that create Joda-Time objects, or in Java 8, java.time.* package. Eventually, you should see new JDBC drivers that automatically use the new java.time.* classes. Until then some methods have been added to classes such as java.sql.Timestamp to interject with java.time such as toInstant and fromInstant.

String

As for the latter part of the question, rendering a String… A formatter object should be used to generate a string value.

The old-fashioned way is with java.text.SimpleDateFormat. Not recommended.

Joda-Time provide various built-in formatters, and you may also define your own. But for writing logs or reports as you mentioned, the best choice may be ISO 8601 format. That format happens to be the default used by Joda-Time and java.time.

Example Code

//java.sql.Timestamp timestamp = resultSet.getTimestamp(i);
// Or, fake it 
// long m = DateTime.now().getMillis();
// java.sql.Timestamp timestamp = new java.sql.Timestamp( m );

//DateTime dateTimeUtc = new DateTime( timestamp.getTime(), DateTimeZone.UTC );
DateTime dateTimeUtc = new DateTime( DateTimeZone.UTC ); // Defaults to now, this moment.

// Convert as needed for presentation to user in local time zone.
DateTimeZone timeZone = DateTimeZone.forID("Europe/Paris");
DateTime dateTimeZoned = dateTimeUtc.toDateTime( timeZone );

Dump to console…

System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeZoned: " + dateTimeZoned );

When run…

dateTimeUtc: 2014-01-16T22:48:46.840Z
dateTimeZoned: 2014-01-16T23:48:46.840+01:00

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

In your cshtml,

<tr ng-repeat="value in Results">                
 <td>{{value.FileReceivedOn | mydate | date : 'dd-MM-yyyy'}} </td>
</tr>

In Your JS File, maybe app.js,

Outside of app.controller, add the below filter.

Here the "mydate" is the function which you are calling for parsing the date. Here the "app" is the variable which contains the angular.module

app.filter("mydate", function () {
    var re = /\/Date\(([0-9]*)\)\//;
    return function (x) {
        var m = x.match(re);
        if (m) return new Date(parseInt(m[1]));
        else return null;
    };
});

How to change scroll bar position with CSS?

Try this out. Hope this helps

<div id="single" dir="rtl">
    <div class="common">Single</div>
</div>

<div id="both" dir="ltr">
    <div class="common">Both</div>
</div>



#single, #both{
    width: 100px;
    height: 100px;
    overflow: auto;
    margin: 0 auto;
    border: 1px solid gray;
}


.common{
    height: 150px;
    width: 150px;
}

Create a string and append text to it

Another way to do this is to add the new characters to the string as follows:

Dim str As String

str = ""

To append text to your string this way:

str = str & "and this is more text"

Get Return Value from Stored procedure in asp.net

Procedure never returns a value.You have to use a output parameter in store procedure.

ALTER PROC TESTLOGIN
@UserName   varchar(50),
@password   varchar(50)
@retvalue int output
 as
 Begin
    declare @return     int 
    set @return  = (Select COUNT(*) 
    FROM    CPUser  
    WHERE   UserName = @UserName AND Password = @password)

   set @retvalue=@return
  End

Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.

Eclipse executable launcher error: Unable to locate companion shared library

I got similar error sometime back. I had copied the eclipse setup from another laptop to mine. The issue with my setup was that path of the "--launcher.library" in the eclipse.ini file. The path in --launcher.library was that of the old machine and hence I was getting the error

I changed the path of "--launcher.library" in eclipse.ini to the path of eclipse on my laptop and the issue got resolved. I hope this is helpful to someone is getting this error.

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

You are calling GridView.RenderControl(htmlTextWriter), hence the page raises an exception that a Server-Control was rendered outside of a Form.

You could avoid this execption by overriding VerifyRenderingInServerForm

public override void VerifyRenderingInServerForm(Control control)
{
  /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
     server control at run time. */
}

See here and here.

How to calculate the width of a text string of a specific font and font-size?

Update Sept 2019

This answer is a much cleaner way to do it using new syntax.

Original Answer

Based on Glenn Howes' excellent answer, I created an extension to calculate the width of a string. If you're doing something like setting the width of a UISegmentedControl, this can set the width based on the segment's title string.

extension String {

    func widthOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.width
    }

    func heightOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.height
    }

    func sizeOfString(usingFont font: UIFont) -> CGSize {
        let fontAttributes = [NSAttributedString.Key.font: font]
        return self.size(withAttributes: fontAttributes)
    }
}

usage:

    // Set width of segmentedControl
    let starString = "??"
    let starWidth = starString.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) + 16
    segmentedController.setWidth(starWidth, forSegmentAt: 3)

Angular.js: set element height on page load

Combining matty-j suggestion with the snippet of the question, I ended up with this code focusing on resizing the grid after the data was loaded.

The HTML:

<div ng-grid="gridOptions" class="gridStyle"></div>

The directive:

angular.module('myApp.directives', [])
    .directive('resize', function ($window) {
        return function (scope, element) {

            var w = angular.element($window);
            scope.getWindowDimensions = function () {
                return { 'h': w.height(), 'w': w.width() };
            };
            scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {

                // resize Grid to optimize height
                $('.gridStyle').height(newValue.h - 250);
            }, true);

            w.bind('resize', function () {
                scope.$apply();
            });
        }
    });

The controller:

angular.module('myApp').controller('Admin/SurveyCtrl', function ($scope, $routeParams, $location, $window, $timeout, Survey) {

    // Retrieve data from the server
    $scope.surveys = Survey.query(function(data) {

        // Trigger resize event informing elements to resize according to the height of the window.
        $timeout(function () {
            angular.element($window).resize();
        }, 0)
    });

    // Configure ng-grid.
    $scope.gridOptions = {
        data: 'surveys',
        ...
    };
}

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

How to convert a string to lower or upper case in Ruby

... and the uppercase is:

"Awesome String".upcase
=> "AWESOME STRING"

Missing .map resource?

I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!

Tower of Hanoi: Recursive Algorithm

I highly recommend this video which illustrates the recursion for this problem in a very understandable way.

The key is to understand the repeating pattern in the solution. The problem can be divided into three main sub-problems. Assuming you have n disks that they are placed at rod A. The target rod is C, and you have B as an intermediate.

Main problem; move n disks from rod A to rod C by using rod B.

  1. Move n-1 disks from rod A to rod B by using rod C.
  2. Move the last disk from rod A to rod C.
  3. Move n-1 disks from rod B to rod C by using rod A.

Sub-problems 1 and 3 are actually solved within the same problem division you see above. Lets take sub problem 1.

Sub-problem 1; move n-1 disks from rod A to rod B by using rod C.

  1. Move n-2 disks from rod A to rod C by using rod B.
  2. Move the last disk from rod A to rod B.
  3. Move n-2 disks from rod C to rod B by using rod A.

We solve the sub-problem in the same way we solve the main-problem. Our base case will be when the number of disks are equal to 1 then we move it from one rod to target one, that's it.

Writing down these steps will help tremendously.

How do you log all events fired by an element in jQuery?

STEP 1: Check the events for an HTML element on the developer console:

enter image description here

STEP 2: Listen to the events we want to capture:

$(document).on('ch-ui-container-closed ch-ui-container-opened', function(evt){
 console.log(evt);
});

Good Luck...

Pandas sum by groupby, but exclude certain columns

You can select the columns of a groupby:

In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
                       Y1961  Y1962  Y1963
Country     Item_Code
Afghanistan 15            10     20     30
            25            10     20     30
Angola      15            30     40     50
            25            30     40     50

Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.

Run reg command in cmd (bat file)?

If memory serves correct, the reg add command will NOT create the entire directory path if it does not exist. Meaning that if any of the parent registry keys do not exist then they must be created manually one by one. It is really annoying, I know! Example:

@echo off
reg add "HKCU\Software\Policies"
reg add "HKCU\Software\Policies\Microsoft"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer\Control Panel"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer\Control Panel" /v HomePage /t REG_DWORD /d 1 /f
pause

Why Anaconda does not recognize conda command?

When you install anaconda on windows now, it doesn't automatically add Python or Conda to your path so you have to add it yourself.

If you don’t know where your conda and/or python is, you type the following commands into your anaconda prompt

enter image description here

Next, you can add Python and Conda to your path by using the setx command in your command prompt. enter image description here

Next close that command prompt and open a new one. Congrats you can now use conda and python

Source: https://medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444

Get element type with jQuery

As Distdev alluded to, you still need to differentiate the input type. That is to say,

$(this).prev().prop('tagName');

will tell you input, but that doesn't differentiate between checkbox/text/radio. If it's an input, you can then use

$('#elementId').attr('type');

to tell you checkbox/text/radio, so you know what kind of control it is.

Coloring Buttons in Android with Material Design and AppCompat

If you only want "Flat" material button, you can customize their background using selectableItemBackground attribute as explained here.

Failed to resolve version for org.apache.maven.archetypes

Go to Windows-> Preference-> Maven -> User settings

Select settings.xml of Maven

Restart Eclipse

How to start an application using android ADB tools?

It's possible to run application specifying package name only using monkey tool by follow this pattern:

adb shell monkey -p your.app.package.name -c android.intent.category.LAUNCHER 1

Command is used to run app using monkey tool which generates random input for application. The last part of command is integer which specify the number of generated random input for app. In this case the number is 1, which in fact is used to launch the app (icon click).

Convert date from String to Date format in Dataframes

Since your main aim was to convert the type of a column in a DataFrame from String to Timestamp, I think this approach would be better.

import org.apache.spark.sql.functions.{to_date, to_timestamp}
val modifiedDF = DF.withColumn("Date", to_date($"Date", "MM/dd/yyyy"))

You could also use to_timestamp (I think this is available from Spark 2.x) if you require fine grained timestamp.

Table is marked as crashed and should be repaired

This means your MySQL table is corrupted and you need to repair it. Use

myisamchk -r /DB_NAME/wp_posts

from the command line. While you running the repair you should shut down your website temporarily so that no new connections are attempted to your database while its being repaired.

Hide Button After Click (With Existing Form on Page)

Here is another solution using Jquery I find it a little easier and neater than inline JS sometimes.

    <html>
    <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script>

        /* if you prefer to functionize and use onclick= rather then the .on bind
        function hide_show(){
            $(this).hide();
            $("#hidden-div").show();
        }
        */

        $(function(){
            $("#chkbtn").on('click',function() {
                $(this).hide();
                $("#hidden-div").show();
            }); 
        });
    </script>
    <style>
    .hidden-div {
        display:none
    }
    </style>
    </head>
    <body>
    <div class="reform">
        <form id="reform" action="action.php" method="post" enctype="multipart/form-data">
        <input type="hidden" name="type" value="" />
            <fieldset>
                content here...
            </fieldset>

                <div class="hidden-div" id="hidden-div">

            <fieldset>
                more content here that is hidden until the button below is clicked...
            </fieldset>
        </form>
                </div>
                <span style="display:block; padding-left:640px; margin-top:10px;"><button id="chkbtn">Check Availability</button></span>
    </div>
    </body>
    </html>

How to get the HTML for a DOM element in javascript

If you want a lighter footprint, but a longer script, get the elements innerHTML and only create and clone the empty parent-

function getHTML(who,lines){
    if(!who || !who.tagName) return '';

    var txt, ax, str, el= document.createElement('div');
    el.appendChild(who.cloneNode(false));
    txt= el.innerHTML;
    ax= txt.indexOf('>')+1;
    str= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);

    el= null;
    return lines? str.replace(/> *</g,'>\n<'): str;
    //easier to read if elements are separated
}

How to disable a input in angular2

What you are looking for is disabled="true". Here is an example:

<textarea class="customPayload" disabled="true" *ngIf="!showSpinner"></textarea>

MySQL vs MySQLi when using PHP

What is better is PDO; it's a less crufty interface and also provides the same features as MySQLi.

Using prepared statements is good because it eliminates SQL injection possibilities; using server-side prepared statements is bad because it increases the number of round-trips.

Java ArrayList replace at specific index

Use the set() method: see doc

arraylist.set(index,newvalue);

how to overlap two div in css?

check this fiddle , and if you want to move the overlapped div you set its position to absolute then change it's top and left values

How to have EditText with border in Android Lollipop

You can do it using xml.

Create an xml layout and name it like my_edit_text_border.xml

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ffffff"/>
            <corners android:radius="5dp" />
            <stroke
                android:width="2dp"
                android:color="#949494"
                />
        </shape>
    </item>
</selector>

Add background to your Edittext

<EditText
 android:id="@+id/editText1"
 ..
 android:background="@layout/my_edit_text_border">

Does HTML5 <video> playback support the .avi format?

There are three formats with a reasonable level of support: H.264 (MPEG-4 AVC), OGG Theora (VP3) and WebM (VP8). See the wiki linked by Sam for which browsers support which; you will typically need at least one of those plus Flash fallback.

Whilst most browsers won't touch AVI, there are some browser builds that expose all the multimedia capabilities of the underlying OS to <video>. These browser will indeed be able to play AVI, as long as they have matching codecs installed (AVI can contain about a million different video and audio formats). In particular Safari on OS X with QuickTime, or Konqi with GStreamer.

Personally I think this is an absolutely disastrous idea, as it exposes a very large codec codebase to the net, a codebase that was mostly not written to be resistant to network attacks. One of the worst drawbacks of media player plugins was the huge number of security holes they made available to every web page exploit. Let's not make this mistake again.