Programs & Examples On #Django settings

A Django settings file is a Python module with module-level variables that contains all the configuration of your Django installation such as, Databases, Installed apps and Media and Static location to name a few.

sqlite3.OperationalError: unable to open database file

For any one who has a problem with airflow linked to this issue.

In my case, I've initialized airflow in /root/airflow and run its scheduler as root. I used the run_as_user parameter to impersonate the web user while running task instances. However airflow was always failing to trigger my DAG with the following errors in logs:

sqlite3.OperationalError: unable to open database file
...
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file

I also found once I triggered a DAG manually, a new airflow resource directory was automatically created under /home/web. I'm not clear about this behavior, but I make it work by removing the entire airflow resources from /root, reinitializing airflow database under /home/web and running the scheduler as web under:

[root@host ~]# rm -rf airflow
[web@host ~]$ airflow initdb
[web@host ~]$ airflow scheduler -D

If you want to try this approach, I may need to backup your data before doing anything.

Django - after login, redirect user to his custom page --> mysite.com/username

You can authenticate and log the user in as stated here: https://docs.djangoproject.com/en/dev/topics/auth/default/#how-to-log-a-user-in

This will give you access to the User object from which you can get the username and then do a HttpResponseRedirect to the custom URL.

Can I access constants in settings.py from templates in Django?

If someone finds this question like I did, then I'll post my solution which works on Django 2.0:

This tag assigns some settings.py variable value to template's variable:

Usage: {% get_settings_value template_var "SETTINGS_VAR" %}

app/templatetags/my_custom_tags.py:

from django import template
from django.conf import settings

register = template.Library()

class AssignNode(template.Node):
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def render(self, context):
        context[self.name] = getattr(settings, self.value.resolve(context, True), "")
        return ''

@register.tag('get_settings_value')
def do_assign(parser, token):
    bits = token.split_contents()
    if len(bits) != 3:
        raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
    value = parser.compile_filter(bits[2])
    return AssignNode(bits[1], value)

Your template:

{% load my_custom_tags %}

# Set local template variable:
{% get_settings_value settings_debug "DEBUG" %}

# Output settings_debug variable:
{{ settings_debug }}

# Use variable in if statement:
{% if settings_debug %}
... do something ...
{% else %}
... do other stuff ...
{% endif %}

See Django's documentation how to create custom template tags here: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

From The Definitive Guide to Django: Web Development Done Right:

If you’ve used Python before, you may be wondering why we’re running python manage.py shell instead of just python. Both commands will start the interactive interpreter, but the manage.py shell command has one key difference: before starting the interpreter, it tells Django which settings file to use.

Use Case: Many parts of Django, including the template system, rely on your settings, and you won’t be able to use them unless the framework knows which settings to use.

If you’re curious, here’s how it works behind the scenes. Django looks for an environment variable called DJANGO_SETTINGS_MODULE, which should be set to the import path of your settings.py. For example, DJANGO_SETTINGS_MODULE might be set to 'mysite.settings', assuming mysite is on your Python path.

When you run python manage.py shell, the command takes care of setting DJANGO_SETTINGS_MODULE for you.**

How to set up a PostgreSQL database in Django

You need to install psycopg2 Python library.

Installation


Download http://initd.org/psycopg/, then install it under Python PATH

After downloading, easily extract the tarball and:

$ python setup.py install

Or if you wish, install it by either easy_install or pip.

(I prefer to use pip over easy_install for no reason.)

  • $ easy_install psycopg2
  • $ pip install psycopg2

Configuration


in settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db_name',                      
        'USER': 'db_user',
        'PASSWORD': 'db_user_password',
        'HOST': '',
        'PORT': 'db_port_number',
    }
}

- Other installation instructions can be found at download page and install page.

How can I remove a commit on GitHub?

You need to know your commit hash from the commit you want to revert to. You can get it from a GitHub URL like: https://github.com/your-organization/your-project/commits/master

Let's say the hash from the commit (where you want to go back to) is "99fb454" (long version "99fb45413eb9ca4b3063e07b40402b136a8cf264"), then all you have to do is:

git reset --hard 99fb45413eb9ca4b3063e07b40402b136a8cf264
git push --force

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

How to download a file using a Java REST service and a data stream

Refer this:

@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {

// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();

// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");

// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}

Details at: https://twilblog.github.io/java/spring/rest/file/stream/2015/08/14/return-a-file-stream-from-spring-rest.html

Generate an integer sequence in MySQL

If you happen to be using the MariaDB fork of MySQL, the SEQUENCE engine allows direct generation of number sequences. It does this by using virtual (fake) one column tables.

For example, to generate the sequence of integers from 1 to 1000, do this

     SELECT seq FROM seq_1_to_1000;

For 0 to 11, do this.

     SELECT seq FROM seq_0_to_11;

For a week's worth of consecutive DATE values starting today, do this.

SELECT FROM_DAYS(seq + TO_DAYS(CURDATE)) dateseq FROM seq_0_to_6

For a decade's worth of consecutive DATE values starting with '2010-01-01' do this.

SELECT FROM_DAYS(seq + TO_DAYS('2010-01-01')) dateseq
  FROM seq_0_to_3800
 WHERE FROM_DAYS(seq + TO_DAYS('2010-01-01')) < '2010-01-01' + INTERVAL 10 YEAR

If you don't happen to be using MariaDB, please consider it.

The entity name must immediately follow the '&' in the entity reference

Just in case someone from Blogger arrives, I had this problem when using Beautify extension in VSCode. Don´t use it, don´t beautify it.

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

How do I get the dialer to open with phone number displayed?

As @ashishduh mentioned above, using android:autoLink="phone is also a good solution. But this option comes with one drawback, it doesn't work with all phone number lengths. For instance, a phone number of 11 numbers won't work with this option. The solution is to prefix your phone numbers with the country code.

Example:

08034448845 won't work

but +2348034448845 will

What is the strict aliasing rule?

Note

This is excerpted from my "What is the Strict Aliasing Rule and Why do we care?" write-up.

What is strict aliasing?

In C and C++ aliasing has to do with what expression types we are allowed to access stored values through. In both C and C++ the standard specifies which expression types are allowed to alias which types. The compiler and optimizer are allowed to assume we follow the aliasing rules strictly, hence the term strict aliasing rule. If we attempt to access a value using a type not allowed it is classified as undefined behavior(UB). Once we have undefined behavior all bets are off, the results of our program are no longer reliable.

Unfortunately with strict aliasing violations, we will often obtain the results we expect, leaving the possibility the a future version of a compiler with a new optimization will break code we thought was valid. This is undesirable and it is a worthwhile goal to understand the strict aliasing rules and how to avoid violating them.

To understand more about why we care, we will discuss issues that come up when violating strict aliasing rules, type punning since common techniques used in type punning often violate strict aliasing rules and how to type pun correctly.

Preliminary examples

Let's look at some examples, then we can talk about exactly what the standard(s) say, examine some further examples and then see how to avoid strict aliasing and catch violations we missed. Here is an example that should not be surprising (live example):

int x = 10;
int *ip = &x;

std::cout << *ip << "\n";
*ip = 12;
std::cout << x << "\n";

We have a int* pointing to memory occupied by an int and this is a valid aliasing. The optimizer must assume that assignments through ip could update the value occupied by x.

The next example shows aliasing that leads to undefined behavior (live example):

int foo( float *f, int *i ) { 
    *i = 1;               
    *f = 0.f;            

   return *i;
}

int main() {
    int x = 0;

    std::cout << x << "\n";   // Expect 0
    x = foo(reinterpret_cast<float*>(&x), &x);
    std::cout << x << "\n";   // Expect 0?
}

In the function foo we take an int* and a float*, in this example we call foo and set both parameters to point to the same memory location which in this example contains an int. Note, the reinterpret_cast is telling the compiler to treat the the expression as if it had the type specificed by its template parameter. In this case we are telling it to treat the expression &x as if it had type float*. We may naively expect the result of the second cout to be 0 but with optimization enabled using -O2 both gcc and clang produce the following result:

0
1

Which may not be expected but is perfectly valid since we have invoked undefined behavior. A float can not validly alias an int object. Therefore the optimizer can assume the constant 1 stored when dereferencing i will be the return value since a store through f could not validly affect an int object. Plugging the code in Compiler Explorer shows this is exactly what is happening(live example):

foo(float*, int*): # @foo(float*, int*)
mov dword ptr [rsi], 1  
mov dword ptr [rdi], 0
mov eax, 1                       
ret

The optimizer using Type-Based Alias Analysis (TBAA) assumes 1 will be returned and directly moves the constant value into register eax which carries the return value. TBAA uses the languages rules about what types are allowed to alias to optimize loads and stores. In this case TBAA knows that a float can not alias and int and optimizes away the load of i.

Now, to the Rule-Book

What exactly does the standard say we are allowed and not allowed to do? The standard language is not straightforward, so for each item I will try to provide code examples that demonstrates the meaning.

What does the C11 standard say?

The C11 standard says the following in section 6.5 Expressions paragraph 7:

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:88) — a type compatible with the effective type of the object,

int x = 1;
int *p = &x;   
printf("%d\n", *p); // *p gives us an lvalue expression of type int which is compatible with int

— a qualified version of a type compatible with the effective type of the object,

int x = 1;
const int *p = &x;
printf("%d\n", *p); // *p gives us an lvalue expression of type const int which is compatible with int

— a type that is the signed or unsigned type corresponding to the effective type of the object,

int x = 1;
unsigned int *p = (unsigned int*)&x;
printf("%u\n", *p ); // *p gives us an lvalue expression of type unsigned int which corresponds to 
                     // the effective type of the object

gcc/clang has an extension and also that allows assigning unsigned int* to int* even though they are not compatible types.

— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,

int x = 1;
const unsigned int *p = (const unsigned int*)&x;
printf("%u\n", *p ); // *p gives us an lvalue expression of type const unsigned int which is a unsigned type 
                     // that corresponds with to a qualified verison of the effective type of the object

— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or

struct foo {
  int x;
};

void foobar( struct foo *fp, int *ip );  // struct foo is an aggregate that includes int among its members so it can
                                         // can alias with *ip

foo f;
foobar( &f, &f.x );

— a character type.

int x = 65;
char *p = (char *)&x;
printf("%c\n", *p );  // *p gives us an lvalue expression of type char which is a character type.
                      // The results are not portable due to endianness issues.

What the C++17 Draft Standard say

The C++17 draft standard in section [basic.lval] paragraph 11 says:

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:63 (11.1) — the dynamic type of the object,

void *p = malloc( sizeof(int) ); // We have allocated storage but not started the lifetime of an object
int *ip = new (p) int{0};        // Placement new changes the dynamic type of the object to int
std::cout << *ip << "\n";        // *ip gives us a glvalue expression of type int which matches the dynamic type 
                                  // of the allocated object

(11.2) — a cv-qualified version of the dynamic type of the object,

int x = 1;
const int *cip = &x;
std::cout << *cip << "\n";  // *cip gives us a glvalue expression of type const int which is a cv-qualified 
                            // version of the dynamic type of x

(11.3) — a type similar (as defined in 7.5) to the dynamic type of the object,

(11.4) — a type that is the signed or unsigned type corresponding to the dynamic type of the object,

// Both si and ui are signed or unsigned types corresponding to each others dynamic types
// We can see from this godbolt(https://godbolt.org/g/KowGXB) the optimizer assumes aliasing.
signed int foo( signed int &si, unsigned int &ui ) {
  si = 1;
  ui = 2;

  return si;
}

(11.5) — a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,

signed int foo( const signed int &si1, int &si2); // Hard to show this one assumes aliasing

(11.6) — an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union),

struct foo {
 int x;
};

// Compiler Explorer example(https://godbolt.org/g/z2wJTC) shows aliasing assumption
int foobar( foo &fp, int &ip ) {
 fp.x = 1;
 ip = 2;

 return fp.x;
}

foo f; 
foobar( f, f.x ); 

(11.7) — a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,

struct foo { int x ; };

struct bar : public foo {};

int foobar( foo &f, bar &b ) {
  f.x = 1;
  b.x = 2;

  return f.x;
}

(11.8) — a char, unsigned char, or std::byte type.

int foo( std::byte &b, uint32_t &ui ) {
  b = static_cast<std::byte>('a');
  ui = 0xFFFFFFFF;                   

  return std::to_integer<int>( b );  // b gives us a glvalue expression of type std::byte which can alias
                                     // an object of type uint32_t
}

Worth noting signed char is not included in the list above, this is a notable difference from C which says a character type.

What is Type Punning

We have gotten to this point and we may be wondering, why would we want to alias for? The answer typically is to type pun, often the methods used violate strict aliasing rules.

Sometimes we want to circumvent the type system and interpret an object as a different type. This is called type punning, to reinterpret a segment of memory as another type. Type punning is useful for tasks that want access to the underlying representation of an object to view, transport or manipulate. Typical areas we find type punning being used are compilers, serialization, networking code, etc…

Traditionally this has been accomplished by taking the address of the object, casting it to a pointer of the type we want to reinterpret it as and then accessing the value, or in other words by aliasing. For example:

int x =  1 ;

// In C
float *fp = (float*)&x ;  // Not a valid aliasing

// In C++
float *fp = reinterpret_cast<float*>(&x) ;  // Not a valid aliasing

printf( "%f\n", *fp ) ;

As we have seen earlier this is not a valid aliasing, so we are invoking undefined behavior. But traditionally compilers did not take advantage of strict aliasing rules and this type of code usually just worked, developers have unfortunately gotten used to doing things this way. A common alternate method for type punning is through unions, which is valid in C but undefined behavior in C++ (see live example):

union u1
{
  int n;
  float f;
} ;

union u1 u;
u.f = 1.0f;

printf( "%d\n”, u.n );  // UB in C++ n is not the active member

This is not valid in C++ and some consider the purpose of unions to be solely for implementing variant types and feel using unions for type punning is an abuse.

How do we Type Pun correctly?

The standard method for type punning in both C and C++ is memcpy. This may seem a little heavy handed but the optimizer should recognize the use of memcpy for type punning and optimize it away and generate a register to register move. For example if we know int64_t is the same size as double:

static_assert( sizeof( double ) == sizeof( int64_t ) );  // C++17 does not require a message

we can use memcpy:

void func1( double d ) {
  std::int64_t n;
  std::memcpy(&n, &d, sizeof d); 
  //...

At a sufficient optimization level any decent modern compiler generates identical code to the previously mentioned reinterpret_cast method or union method for type punning. Examining the generated code we see it uses just register mov (live Compiler Explorer Example).

C++20 and bit_cast

In C++20 we may gain bit_cast (implementation available in link from proposal) which gives a simple and safe way to type-pun as well as being usable in a constexpr context.

The following is an example of how to use bit_cast to type pun a unsigned int to float, (see it live):

std::cout << bit_cast<float>(0x447a0000) << "\n" ; //assuming sizeof(float) == sizeof(unsigned int)

In the case where To and From types don't have the same size, it requires us to use an intermediate struct15. We will use a struct containing a sizeof( unsigned int ) character array (assumes 4 byte unsigned int) to be the From type and unsigned int as the To type.:

struct uint_chars {
 unsigned char arr[sizeof( unsigned int )] = {} ;  // Assume sizeof( unsigned int ) == 4
};

// Assume len is a multiple of 4 
int bar( unsigned char *p, size_t len ) {
 int result = 0;

 for( size_t index = 0; index < len; index += sizeof(unsigned int) ) {
   uint_chars f;
   std::memcpy( f.arr, &p[index], sizeof(unsigned int));
   unsigned int result = bit_cast<unsigned int>(f);

   result += foo( result );
 }

 return result ;
}

It is unfortunate that we need this intermediate type but that is the current constraint of bit_cast.

Catching Strict Aliasing Violations

We don't have a lot of good tools for catching strict aliasing in C++, the tools we have will catch some cases of strict aliasing violations and some cases of misaligned loads and stores.

gcc using the flag -fstrict-aliasing and -Wstrict-aliasing can catch some cases although not without false positives/negatives. For example the following cases will generate a warning in gcc (see it live):

int a = 1;
short j;
float f = 1.f; // Originally not initialized but tis-kernel caught 
               // it was being accessed w/ an indeterminate value below

printf("%i\n", j = *(reinterpret_cast<short*>(&a)));
printf("%i\n", j = *(reinterpret_cast<int*>(&f)));

although it will not catch this additional case (see it live):

int *p;

p=&a;
printf("%i\n", j = *(reinterpret_cast<short*>(p)));

Although clang allows these flags it apparently does not actually implement the warnings.

Another tool we have available to us is ASan which can catch misaligned loads and stores. Although these are not directly strict aliasing violations they are a common result of strict aliasing violations. For example the following cases will generate runtime errors when built with clang using -fsanitize=address

int *x = new int[2];               // 8 bytes: [0,7].
int *u = (int*)((char*)x + 6);     // regardless of alignment of x this will not be an aligned address
*u = 1;                            // Access to range [6-9]
printf( "%d\n", *u );              // Access to range [6-9]

The last tool I will recommend is C++ specific and not strictly a tool but a coding practice, don't allow C-style casts. Both gcc and clang will produce a diagnostic for C-style casts using -Wold-style-cast. This will force any undefined type puns to use reinterpret_cast, in general reinterpret_cast should be a flag for closer code review. It is also easier to search your code base for reinterpret_cast to perform an audit.

For C we have all the tools already covered and we also have tis-interpreter, a static analyzer that exhaustively analyzes a program for a large subset of the C language. Given a C verions of the earlier example where using -fstrict-aliasing misses one case (see it live)

int a = 1;
short j;
float f = 1.0 ;

printf("%i\n", j = *((short*)&a));
printf("%i\n", j = *((int*)&f));

int *p; 

p=&a;
printf("%i\n", j = *((short*)p));

tis-interpeter is able to catch all three, the following example invokes tis-kernal as tis-interpreter (output is edited for brevity):

./bin/tis-kernel -sa example1.c 
...
example1.c:9:[sa] warning: The pointer (short *)(& a) has type short *. It violates strict aliasing
              rules by accessing a cell with effective type int.
...

example1.c:10:[sa] warning: The pointer (int *)(& f) has type int *. It violates strict aliasing rules by
              accessing a cell with effective type float.
              Callstack: main
...

example1.c:15:[sa] warning: The pointer (short *)p has type short *. It violates strict aliasing rules by
              accessing a cell with effective type int.

Finally there is TySan which is currently in development. This sanitizer adds type checking information in a shadow memory segment and checks accesses to see if they violate aliasing rules. The tool potentially should be able to catch all aliasing violations but may have a large run-time overhead.

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

If the script actually does what it needs to do and it's just Visual Studio bugging you about the error you could just add:

exit 0

to the end of you script.

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

How could I use requests in asyncio?

Requests does not currently support asyncio and there are no plans to provide such support. It's likely that you could implement a custom "Transport Adapter" (as discussed here) that knows how to use asyncio.

If I find myself with some time it's something I might actually look into, but I can't promise anything.

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

There is nothing wrong in concatenating two strings with +. Indeed it's easier to read than ''.join([a, b]).

You are right though that concatenating more than 2 strings with + is an O(n^2) operation (compared to O(n) for join) and thus becomes inefficient. However this has not to do with using a loop. Even a + b + c + ... is O(n^2), the reason being that each concatenation produces a new string.

CPython2.4 and above try to mitigate that, but it's still advisable to use join when concatenating more than 2 strings.

git returns http error 407 from proxy after CONNECT

This config works in my setup:

[http]
    proxy = <your proxy>
[https] proxy = <your proxy>
[http]
    sslVerify = false
[https]
    sslVerify = false   
[credential]
    helper = wincred 

How to check the multiple permission at single request in Android M?

You can ask multiple permissions (from different groups) in a single request. For that, you need to add all the permissions to the string array that you supply as the first parameter to the requestPermissions API like this:

requestPermissions(new String[]{
                                Manifest.permission.READ_CONTACTS,
                                Manifest.permission.ACCESS_FINE_LOCATION},
                        ASK_MULTIPLE_PERMISSION_REQUEST_CODE);

On doing this, you will see the permission popup as a stack of multiple permission popups. Ofcourse you need to handle the acceptance and rejection (including the "Never Ask Again") options of each permissions. The same has been beautifully explained over here.

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

Difference between "or" and || in Ruby?

or is NOT the same as ||. Use only || operator instead of the or operator.

Here are some reasons. The:

  • or operator has a lower precedence than ||.
  • or has a lower precedence than the = assignment operator.
  • and and or have the same precedence, while && has a higher precedence than ||.

Disable a Maven plugin defined in a parent POM

See if the plugin has a 'skip' configuration parameter. Nearly all do. if it does, just add it to a declaration in the child:

<plugin>
   <groupId>group</groupId>
   <artifactId>artifact</artifactId>
   <configuration>
     <skip>true</skip>
   </configuration>
</plugin>

If not, then use:

<plugin>    
<groupId>group</groupId>   
 <artifactId>artifact</artifactId>    
<executions>
     <execution>
       <id>TheNameOfTheRelevantExecution</id>
       <phase>none</phase>
     </execution>    
</executions>  
</plugin>

can not find module "@angular/material"

That's what solved this problem for me.

I used:

npm install --save @angular/material @angular/cdk
npm install --save @angular/animations

but INSIDE THE APPLICATION'S FOLDER.

Source: https://medium.com/@ismapro/first-steps-with-angular-cli-and-angular-material-5a90406e9a4

Is there a W3C valid way to disable autocomplete in a HTML form?

No, but browser auto-complete is often triggered by the field having the same name attribute as fields that were previously filled out. If you could rig up a clever way to have a randomized field name, autocomplete wouldn't be able to pull any previously entered values for the field.

If you were to give an input field a name like "email_<?= randomNumber() ?>", and then have the script that receives this data loop through the POST or GET variables looking for something matching the pattern "email_[some number]", you could pull this off, and this would have (practically) guaranteed success, regardless of browser.

Get file path of image on Android

use this function to get the capture image path

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
            Uri mImageCaptureUri = intent.getData();
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
            knop.setVisibility(Button.VISIBLE);
            System.out.println(mImageCaptureUri);
           //getImgPath(mImageCaptureUri);// it will return the Capture image path
        }  
    }

public String getImgPath(Uri uri) {
        String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID,
                MediaStore.Images.ImageColumns.DATA };
        String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
        Cursor myCursor = this.managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                largeFileProjection, null, null, largeFileSort);
        String largeImagePath = "";
        try {
            myCursor.moveToFirst();
            largeImagePath = myCursor
                    .getString(myCursor
                            .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
        } finally {
            myCursor.close();
        }
        return largeImagePath;
    }

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

jquery $(window).height() is returning the document height

I think your document must be having enough space in the window to display its contents. That means there is no need to scroll down to see any more part of the document. In that case, document height would be equal to the window height.

how to change text box value with jQuery?

$('#cd').click(function() {
  $(this).val('dasf');  // update the value of submit button
  $('#dsf').val('Changed Value') // update the text input value
});

textbox is not a valid selector.

Also, when you hit the submit button it will submit the form as default behavior. So don't forget to stop default form submission.

Better if you do like this:

$('form').on('submit', function() {

  // write all your codes

  return false; // Prevent default form submission
});

Don't forget to user jQuery DOM ready $(function() { .. });

apc vs eaccelerator vs xcache

If you want PHP file caching only, you can use eAccelerator directly. Very easy to install and configure, and give great results.

But too bad, they removed the eaccelerator_put and eaccelerator_put from the latest version 0.9.6.

Are HTTP headers case-sensitive?

officially, headers are case insensitive, however, it is common practice to capitalize the first letter of every word.
but, because it is common practice, certain programs like IE assume the headers are capitalized.
so while the docs say the are case insensitive, bad programmers have basically changed the docs.

int to unsigned int conversion

with a little help of math

#include <math.h>
int main(){
  int a = -1;
  unsigned int b;
  b = abs(a);
}

How can I remount my Android/system as read-write in a bash script using adb?

In addition to all the other answers you received, I want to explain the unknown option -- o error: Your command was

$ adb shell 'su -c  mount -o rw,remount /system'

which calls su through adb. You properly quoted the whole su command in order to pass it as one argument to adb shell. However, su -c <cmd> also needs you to quote the command with arguments it shall pass to the shell's -c option. (YMMV depending on su variants.) Therefore, you might want to try

$ adb shell 'su -c "mount -o rw,remount /system"'

(and potentially add the actual device listed in the output of mount | grep system before the /system arg – see the other answers.)

How do I add space between items in an ASP.NET RadioButtonList

I know this is an old question but I did it like:

<asp:RadioButtonList runat="server" ID="myrbl" RepeatDirection="Horizontal" CssClass="rbl"> 

Use this as your class:

.rbl input[type="radio"]
{
   margin-left: 10px;
   margin-right: 1px;
}

libaio.so.1: cannot open shared object file

Here on a openSuse 12.3 the solution was installing the 32-bit version of libaio in addition. Oracle seems to need this now, although on 12.1 it run without the 32-bit version.

IOException: The process cannot access the file 'file path' because it is being used by another process

As other answers in this thread have pointed out, to resolve this error you need to carefully inspect the code, to understand where the file is getting locked.

In my case, I was sending out the file as an email attachment before performing the move operation.

So the file got locked for couple of seconds until SMTP client finished sending the email.

The solution I adopted was to move the file first, and then send the email. This solved the problem for me.

Another possible solution, as pointed out earlier by Hudson, would've been to dispose the object after use.

public static SendEmail()
{
           MailMessage mMailMessage = new MailMessage();
           //setup other email stuff

            if (File.Exists(attachmentPath))
            {
                Attachment attachment = new Attachment(attachmentPath);
                mMailMessage.Attachments.Add(attachment);
                attachment.Dispose(); //disposing the Attachment object
            }
} 

Default interface methods are only supported starting with Android N

In app-level gradle, you have to write these code:

android {
...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

They come from JavaVersion.java in Android.

An enumeration of Java versions.

Before 9: http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html

After 9: http://openjdk.java.net/jeps/223

@canerkaseler

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

In my case I forgot to add @RequestBody annotation to the method argument:

public TestController(@RequestBody KeeperClient testClient) {
        TestController.testClient = testClient;
    }

How to do parallel programming in Python?

In some cases, it's possible to automatically parallelize loops using Numba, though it only works with a small subset of Python:

from numba import njit, prange

@njit(parallel=True)
def prange_test(A):
    s = 0
    # Without "parallel=True" in the jit-decorator
    # the prange statement is equivalent to range
    for i in prange(A.shape[0]):
        s += A[i]
    return s

Unfortunately, it seems that Numba only works with Numpy arrays, but not with other Python objects. In theory, it might also be possible to compile Python to C++ and then automatically parallelize it using the Intel C++ compiler, though I haven't tried this yet.

Get properties and values from unknown object

void Test(){
    var obj = new{a="aaa", b="bbb"};

    var val_a = obj.GetValObjDy("a"); //="aaa"
    var val_b = obj.GetValObjDy("b"); //="bbb"
}
//create in a static class
static public object GetValObjDy(this object obj, string propertyName)
{            
     return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}

ng-repeat: access key and value for each object in array of objects

Here is another way, without the need for nesting the repeaters.

From the Angularjs docs:

It is possible to get ngRepeat to iterate over the properties of an object using the following syntax:

<div ng-repeat="(key, value) in steps"> {{key}} : {{value}} </div>

Intercept a form submit in JavaScript and prevent normal submission

<form id="my-form">
    <input type="text" name="in" value="some data" />
    <button type="submit">Go</button>
</form>

In JS:

function processForm(e) {
    if (e.preventDefault) e.preventDefault();

    /* do what you want with the form */

    // You must return false to prevent the default form behavior
    return false;
}

var form = document.getElementById('my-form');
if (form.attachEvent) {
    form.attachEvent("submit", processForm);
} else {
    form.addEventListener("submit", processForm);
}

Edit: in my opinion, this approach is better than setting the onSubmit attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.

Edit2: Updated my example to include preventDefault()

JSON.parse vs. eval()

Not all browsers have native JSON support so there will be times where you need to use eval() to the JSON string. Use JSON parser from http://json.org as that handles everything a lot easier for you.

Eval() is an evil but against some browsers its a necessary evil but where you can avoid it, do so!!!!!

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

How do I work with a git repository within another repository?

I had issues with subtrees and submodules that the other answers suggest... mainly because I am using SourceTree and it seems fairly buggy.

Instead, I ended up using SymLinks and that seems to work well so I am posting it here as a possible alternative.

There is a complete guide here: http://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/

But basically you just need to mklink the two paths in an elevated command prompt. Make sure you use the /J hard link prefix. Something along these lines: mklink /J C:\projects\MainProject\plugins C:\projects\SomePlugin

You can also use relative folder paths and put it in a bat to be executed by each person when they first check out your project.

Example: mklink /J .\Assets\TaqtileTools ..\TaqtileHoloTools

Once the folder has been linked you may need to ignore the folder within your main repository that is referencing it. Otherwise you are good to go.

Note I've deleted my duplicate answer from another post as that post was marked as a duplicate question to this one.

Open soft keyboard programmatically

Based on above answers like this it works in KOTLIN as long as you have the context.

fun Context.showKeyboard(editText: EditText) {

    editText.requestFocus()
    editText.setSelection(editText.text.length)

    GlobalScope.launch {
        delay(200L)

        val inputMethodManager: InputMethodManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInputFromWindow(
            editText.applicationWindowToken,
            InputMethodManager.SHOW_IMPLICIT, 0
        )
    }
}

Then you can call it in your fragment for example as follows

requireContext().showKeyboard(binding.myEditText)

sort dict by value python

If you actually want to sort the dictionary instead of just obtaining a sorted list use collections.OrderedDict

>>> from collections import OrderedDict
>>> from operator import itemgetter
>>> data = {1: 'b', 2: 'a'}
>>> d = OrderedDict(sorted(data.items(), key=itemgetter(1)))
>>> d
OrderedDict([(2, 'a'), (1, 'b')])
>>> d.values()
['a', 'b']

How to run jenkins as a different user

The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.

However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub. What if there are multiple jenkins servers that need to access the same gitolite server?

(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)

So in this case you do need to run the Jenkins daemon as a different user.

There are two steps:

Step 1

The main thing is to update the JENKINS_USER environment variable. Here's a patch showing how to change the user to ptran.

BEGIN PATCH
--- etc/default/jenkins.old     2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
 PIDFILE=/var/run/jenkins/jenkins.pid

 # user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran

 # location of the jenkins war file
 JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old      2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins  2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@

 #DAEMON=$JENKINS_SH
 DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG -   -pidfile=$PIDFILE" 
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE" 

 SU=/bin/su
END PATCH

Step 2

Update ownership of jenkins directories:

chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins

Step 3

Restart jenkins

sudo service jenkins restart

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

I Faced Same Problem what i did

  1. php artisan cache:clear
  2. php artisan config:cache

but Same problem found than i run this artisan command

php artisan view:clear

Hope it will helpful.

Programmatically go back to previous ViewController in Swift

I would like to suggest another approach to this problem. Instead of using the navigation controller to pop a view controller, use unwind segues. This solution has a few, but really important, advantages:

  1. The origin controller can go back to any other destination controller (not just the previous one) without knowing anything about the destination.
  2. Push and pop segues are defined in storyboard, so no navigation code in your view controllers.

You can find more details in Unwind Segues Step-by-Step. The how to is better explained in the former link, including how to send data back, but here I will make a brief explanation.

1) Go to the destination (not the origin) view controller and add an unwind segue:

    @IBAction func unwindToContact(_ unwindSegue: UIStoryboardSegue) {
        //let sourceViewController = unwindSegue.source
        // Use data from the view controller which initiated the unwind segue
    }

2) CTRL drag from the view controller itself to the exit icon in the origin view controller:

Unwind from view controller

3) Select the unwind function you just created a few moments ago:

Select unwind function

4) Select the unwind segue and give it a name:

Naming unwind segue

5) Go to any place of the origin view controller and call the unwind segue:

performSegue(withIdentifier: "unwindToContact", sender: self)

I have found this approach payoffs a lot when your navigation starts to get complicated.

I hope this helps someone.

How to differ sessions in browser-tabs?

Another approach that works is to create a unique window id and store this value along with the session id in a database table. The window id I often use is integer(now). This value is created when a window is opened and re-assigned to the same window if the window is refreshed, reloaded or submitted to itself. Window values (inputs) are saved in the local table using the link. When a value is required, it is obtained from the database table based on the window id / session id link. While this approach requires a local database, it is virtually foolproof. The use of a database table was easy for me, but I see no reason why local arrays would not work just as well.

What's the difference between integer class and numeric class in R

To my understanding - we do not declare a variable with a data type so by default R has set any number without L to be a numeric. If you wrote:

> x <- c(4L, 5L, 6L, 6L)
> class(x)
>"integer" #it would be correct

Example of Integer:

> x<- 2L
> print(x)

Example of Numeric (kind of like double/float from other programming languages)

> x<-3.4
> print(x)

FFT in a single C-file

Your best bet is KissFFT - as its name implies it's simple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

This worked for me- -go to the report manager, check site settings-> Security -> New Role Assignment-> add the user

-Also, go to Datasets in report manager -> your report dataset -> Security -> New Role Assignment -> add the user with the required role.

Thanks!

Eliminating NAs from a ggplot

Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.

library(tidyverse) 

MyDate %>%
   filter(!is.na(the_variable)) %>%
     ggplot(aes(x= the_variable, fill=the_variable)) + 
        geom_bar(stat="bin") 

You should be able to remove the annoying NAs on your plot. Hope this works :)

removing bold styling from part of a header

Yes you can add text inside <span> and override css. jsfiddle

html:

<h1>**This text should be bold**, <span>but this text should not</span><h1>

css:

span{
   font-weight: normal;
}

MySQL: Quick breakdown of the types of joins

I have 2 tables like this:

> SELECT * FROM table_a;
+------+------+
| id   | name |
+------+------+
|    1 | row1 |
|    2 | row2 |
+------+------+

> SELECT * FROM table_b;
+------+------+------+
| id   | name | aid  |
+------+------+------+
|    3 | row3 |    1 |
|    4 | row4 |    1 |
|    5 | row5 | NULL |
+------+------+------+

INNER JOIN cares about both tables

INNER JOIN cares about both tables, so you only get a row if both tables have one. If there is more than one matching pair, you get multiple rows.

> SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
+------+------+------+------+------+

It makes no difference to INNER JOIN if you reverse the order, because it cares about both tables:

> SELECT * FROM table_b b INNER JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
+------+------+------+------+------+

You get the same rows, but the columns are in a different order because we mentioned the tables in a different order.

LEFT JOIN only cares about the first table

LEFT JOIN cares about the first table you give it, and doesn't care much about the second, so you always get the rows from the first table, even if there is no corresponding row in the second:

> SELECT * FROM table_a a LEFT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
|    2 | row2 | NULL | NULL | NULL |
+------+------+------+------+------+

Above you can see all rows of table_a even though some of them do not match with anything in table b, but not all rows of table_b - only ones that match something in table_a.

If we reverse the order of the tables, LEFT JOIN behaves differently:

> SELECT * FROM table_b b LEFT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
|    5 | row5 | NULL | NULL | NULL |
+------+------+------+------+------+

Now we get all rows of table_b, but only matching rows of table_a.

RIGHT JOIN only cares about the second table

a RIGHT JOIN b gets you exactly the same rows as b LEFT JOIN a. The only difference is the default order of the columns.

> SELECT * FROM table_a a RIGHT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
| NULL | NULL |    5 | row5 | NULL |
+------+------+------+------+------+

This is the same rows as table_b LEFT JOIN table_a, which we saw in the LEFT JOIN section.

Similarly:

> SELECT * FROM table_b b RIGHT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
| NULL | NULL | NULL |    2 | row2 |
+------+------+------+------+------+

Is the same rows as table_a LEFT JOIN table_b.

No join at all gives you copies of everything

If you write your tables with no JOIN clause at all, just separated by commas, you get every row of the first table written next to every row of the second table, in every possible combination:

> SELECT * FROM table_b b, table_a;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    3 | row3 | 1    |    2 | row2 |
|    4 | row4 | 1    |    1 | row1 |
|    4 | row4 | 1    |    2 | row2 |
|    5 | row5 | NULL |    1 | row1 |
|    5 | row5 | NULL |    2 | row2 |
+------+------+------+------+------+

(This is from my blog post Examples of SQL join types)

HTTP vs HTTPS performance

In addition to everything mentioned so far, please keep in mind that some (all?) web browsers do not store cached content obtained over HTTPS on the local hard-drive for security reasons. This means that from the user's perspective pages with plenty of static content will appear to load slower after the browser is restarted, and from your server's perspective the volume of requests for static content over HTTPS will be higher than would have been over HTTP.

Hex transparency in colors

I realize this is an old question, but I came across it when doing something similar.

Using SASS, you have a very elegant way to convert RGBA to hex ARGB: ie-hex-str. I've used it here in a mixin.

@mixin ie8-rgba ($r, $g, $b, $a){
    $rgba: rgba($r, $g, $b, $a);
    $ie8-rgba: ie-hex-str($rgba);
    .lt-ie9 &{
      background-color: transparent;
      filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#{$ie8-rgba}', endColorstr='#{$ie8-rgba}');
  }
}

.transparent{
    @include ie8-rgba(88,153,131,.8);
    background-color: rgba(88,153,131,.8);
}

outputs:

_x000D_
_x000D_
.transparent {_x000D_
  background-color: rgba(88, 153, 131, 0.8);_x000D_
}_x000D_
.lt-ie9 .transparent {_x000D_
  background-color: transparent;_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#CC589983', endColorstr='#CC589983');_x000D_
  zoom: 1;_x000D_
}
_x000D_
_x000D_
_x000D_

Search in lists of lists by given index

Nothing wrong with using a gen exp, but if the goal is to inline the loop...

>>> import itertools, operator
>>> 'b' in itertools.imap(operator.itemgetter(1), the_list)
True

Should be the fastest as well.

.NET Core vs Mono

This is no more .NET Core vs. Mono. It's unified.

Update as of November 2020 - .NET 5 released that unifies .NET Framework and .NET Core

.NET and Mono will be unified under .NET 6 that would be released in November 2021

  • .NET 6.0 will add net6.0-ios and net6.0-android.
  • The OS-specific names can include OS version numbers, like net6.0-ios14.

Check below articles:

'NOT NULL constraint failed' after adding to models.py

@coldmind answer is correct but lacks details.

The 'NOT NULL constraint failed' occurs when something tries to set None to the 'zipcode' property, while it has not been explicitely allowed.

It usually happens when:

1) your field has Null=False by default, so that the value in the database cannot be None (i.e. undefined) when the object is created and saved in the database (this happens after a objects_set.create() call or setting the .zipcode property and doing a .save() call).

For instance, if somewhere in your code an assignement results in:

model.zipcode = None

this error is raised

2) When creating or updating the database, Django is constrained to find a default value to fill the field, because Null=False by default. It does not find any because you haven't defined any. So this error can not only happen during code execution but also when creating the database?

3) Note that the same error would be returned of you define default=None, or if your default value with an incorrect type, for instance default='00000' instead of 00000 for your field (maybe can there be automatic conversion between char and integers, but I would advise against relying on it. Besides, explicit is better than implicit). Most likely an error would also be raised if the default value violates the max_length property, e.g. 123456

So you'll have to define the field by one of the following:

models.IntegerField(_('zipcode'), max_length=5, Null=True,
   blank=True)

models.IntegerField(_('zipcode'), max_length=5, Null=False,
   blank=True, default=00000)

models.IntegerField(_('zipcode'), max_length=5, blank=True,
   default=00000)

and then make a migration (python3 manage.py makemigration ) and then migrate (python3 manage.py migrate).

For safety you can also delete the last failed migration files in <app_name>/migrations/, there are usually named after this pattern:

<NUMBER>_auto_<DATE>_<HOUR>.py

Finally, if you don't set Null=True, make sure that mode.zipcode = None is never done anywhere.

Angular2 change detection: ngOnChanges not firing for nested object

I have 2 solutions to resolve your problem

  1. Use ngDoCheck to detect object data changed or not
  2. Assign object to a new memory address by object = Object.create(object) from parent component.

Validate that end date is greater than start date with jQuery

First you split the values of two input box by using split function. then concat the same in reverse order. after concat nation parse it to integer. then compare two values in in if statement. eg.1>20-11-2018 2>21-11-2018

after split and concat new values for comparison 20181120 and 20181121 the after that compare the same.

var date1 = $('#datevalue1').val();
var date2 = $('#datevalue2').val();
var d1 = date1.split("-");
var d2 = date2.split("-");

d1 = d1[2].concat(d1[1], d1[0]);
d2 = d2[2].concat(d2[1], d2[0]);

if (parseInt(d1) > parseInt(d2)) {

    $('#fromdatepicker').val('');
} else {

}

Display SQL query results in php

You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.

// Process all rows
while($row = mysql_fetch_array($result)) {
    echo $row['column_name']; // Print a single column data
    echo print_r($row);       // Print the entire row data
}

Change your code to this :

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['fieldname']; 
}

Mocking Logger and LoggerFactory with PowerMock and Mockito

In answer to your first question, it should be as simple as replacing:

   when(LoggerFactory.getLogger(GoodbyeController.class)).thenReturn(loggerMock);

with

   when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);

Regarding your second question (and possibly the puzzling behavior with the first), I think the problem is that logger is static. So,

private static Logger logger = LoggerFactory.getLogger(GoodbyeController.class);

is executed when the class is initialized, not the when the object is instantiated. Sometimes this can be at about the same time, so you'll be OK, but it's hard to guarantee that. So you set up LoggerFactory.getLogger to return your mock, but the logger variable may have already been set with a real Logger object by the time your mocks are set up.

You may be able to set the logger explicitly using something like ReflectionTestUtils (I don't know if that works with static fields) or change it from a static field to an instance field. Either way, you don't need to mock LoggerFactory.getLogger because you'll be directly injecting the mock Logger instance.

Selecting an element in iFrame jQuery

when your document is ready that doesn't mean that your iframe is ready too,
so you should listen to the iframe load event then access your contents:

$(function() {
    $("#my-iframe").bind("load",function(){
        $(this).contents().find("[tokenid=" + token + "]").html();
    });
});

CAST to DECIMAL in MySQL

MySQL casts to Decimal:

Cast bare integer to decimal:

select cast(9 as decimal(4,2));       //prints 9.00

Cast Integers 8/5 to decimal:

select cast(8/5 as decimal(11,4));    //prints 1.6000

Cast string to decimal:

select cast(".885" as decimal(11,3));   //prints 0.885

Cast two int variables into a decimal

mysql> select 5 into @myvar1;
Query OK, 1 row affected (0.00 sec)

mysql> select 8 into @myvar2;
Query OK, 1 row affected (0.00 sec)

mysql> select @myvar1/@myvar2;   //prints 0.6250

Cast decimal back to string:

select cast(1.552 as char(10));   //shows "1.552"

How can I delete a file from a Git repository?

I have obj and bin files that accidentally made it into the repo that I don't want polluting my 'changed files' list

After I noticed they went to the remote, I ignored them by adding this to .gitignore

/*/obj
/*/bin

Problem is they are already in the remote, and when they get changed, they pop up as changed and pollute the changed file list.

To stop seeing them, you need to delete the whole folder from the remote repository.

In a command prompt:

  1. CD to the repo folder (i.e. C:\repos\MyRepo)
  2. I want to delete SSIS\obj. It seems you can only delete at the top level, so you now need to CD into SSIS: (i.e. C:\repos\MyRepo\SSIS)
  3. Now type the magic incantation git rm -r -f obj
    • rm=remove
    • -r = recursively remove
    • -f = means force, cause you really mean it
    • obj is the folder
  4. Now run git commit -m "remove obj folder"

I got an alarming message saying 13 files changed 315222 deletions

Then because I didn't want to have to look up the CMD line, I went into Visual Sstudio and did a Sync to apply it to the remote

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

I found 3 ways to implement this:

C# class:

public class AddressInfo {
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    public string Country { get; set; }
}

Action:

[HttpPost]
public ActionResult Check(AddressInfo addressInfo)
{
    return Json(new { success = true });
}

JavaScript you can do it three ways:

1) Query String:

$.ajax({
    url: '/en/Home/Check',
    data: $('#form').serialize(),
    type: 'POST',
});

Data here is a string.

"Address1=blah&Address2=blah&City=blah&State=blah&ZipCode=blah&Country=blah"

2) Object Array:

$.ajax({
    url: '/en/Home/Check',
    data: $('#form').serializeArray(),
    type: 'POST',
});

Data here is an array of key/value pairs :

=[{name: 'Address1', value: 'blah'}, {name: 'Address2', value: 'blah'}, {name: 'City', value: 'blah'}, {name: 'State', value: 'blah'}, {name: 'ZipCode', value: 'blah'}, {name: 'Country', value: 'blah'}]

3) JSON:

$.ajax({
      url: '/en/Home/Check',
      data: JSON.stringify({ addressInfo:{//missing brackets
          Address1: $('#address1').val(),
          Address2: $('#address2').val(),
          City: $('#City').val(),
          State: $('#State').val(),
          ZipCode: $('#ZipCode').val()}}),
      type: 'POST',
      contentType: 'application/json; charset=utf-8'
});

Data here is a serialized JSON string. Note that the name has to match the parameter name in the server!!

='{"addressInfo":{"Address1":"blah","Address2":"blah","City":"blah","State":"blah", "ZipCode", "blah", "Country", "blah"}}'

How to clear Facebook Sharer cache?

I just posted a simple solution that takes 5 seconds here on a related post here - Facebook debugger: Clear whole site cache

short answer... change your permalinks on a worpdress site in the permalinks settings to a custom one. I just added an underscore.
/_%postname%/
then facebook scrapes them all as new urls, new posts.

mongodb: insert if not exists

As of MongoDB 2.4, you can use $setOnInsert (http://docs.mongodb.org/manual/reference/operator/setOnInsert/)

Set 'insertion_date' using $setOnInsert and 'last_update_date' using $set in your upsert command.

To turn your pseudocode into a working example:

now = datetime.utcnow()
for document in update:
    collection.update_one(
        {"_id": document["_id"]},
        {
            "$setOnInsert": {"insertion_date": now},
            "$set": {"last_update_date": now},
        },
        upsert=True,
    )

How to stop INFO messages displaying on spark console?

Right after starting spark-shell type ;

sc.setLogLevel("ERROR")

In Spark 2.0 (Scala):

spark = SparkSession.builder.getOrCreate()
spark.sparkContext.setLogLevel("ERROR")

API Docs : https://spark.apache.org/docs/2.2.0/api/scala/index.html#org.apache.spark.sql.SparkSession

For Java:

spark = SparkSession.builder.getOrCreate();
spark.sparkContext().setLogLevel("ERROR");

getting the reason why websockets closed with close code 1006

This may be your websocket URL you are using in device are not same(You are hitting different websocket URL from android/iphonedevice )

Column calculated from another column?

MySQL 5.7 supports computed columns. They call it "Generated Columns" and the syntax is a little weird, but it supports the same options I see in other databases.

https://dev.mysql.com/doc/refman/5.7/en/create-table.html#create-table-generated-columns

Java Class that implements Map and keeps insertion order?

Either You can use LinkedHashMap<K, V> or you can implement you own CustomMap which maintains insertion order.

You can use the Following CustomHashMap with the following features:

  • Insertion order is maintained, by using LinkedHashMap internally.
  • Keys with null or empty strings are not allowed.
  • Once key with value is created, we are not overriding its value.

HashMap vs LinkedHashMap vs CustomHashMap

interface CustomMap<K, V> extends Map<K, V> {
    public boolean insertionRule(K key, V value);
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public class CustomHashMap<K, V> implements CustomMap<K, V> {
    private Map<K, V> entryMap;
    // SET: Adds the specified element to this set if it is not already present.
    private Set<K> entrySet;

    public CustomHashMap() {
        super();
        entryMap = new LinkedHashMap<K, V>();
        entrySet = new HashSet();
    }

    @Override
    public boolean insertionRule(K key, V value) {
        // KEY as null and EMPTY String is not allowed.
        if (key == null || (key instanceof String && ((String) key).trim().equals("") ) ) {
            return false;
        }

        // If key already available then, we are not overriding its value.
        if (entrySet.contains(key)) { // Then override its value, but we are not allowing
            return false;
        } else { // Add the entry
            entrySet.add(key);
            entryMap.put(key, value);
            return true;
        }
    }
    public V put(K key, V value) {
        V oldValue = entryMap.get(key);
        insertionRule(key, value);
        return oldValue;
    }
    public void putAll(Map<? extends K, ? extends V> t) {
        for (Iterator i = t.keySet().iterator(); i.hasNext();) {
            K key = (K) i.next();
            insertionRule(key, t.get(key));
        }
    }

    public void clear() {
        entryMap.clear();
        entrySet.clear();
    }
    public boolean containsKey(Object key) {
        return entryMap.containsKey(key);
    }
    public boolean containsValue(Object value) {
        return entryMap.containsValue(value);
    }
    public Set entrySet() {
        return entryMap.entrySet();
    }
    public boolean equals(Object o) {
        return entryMap.equals(o);
    }
    public V get(Object key) {
        return entryMap.get(key);
    }
    public int hashCode() {
        return entryMap.hashCode();
    }
    public boolean isEmpty() {
        return entryMap.isEmpty();
    }
    public Set keySet() {
        return entrySet;
    }
    public V remove(Object key) {
        entrySet.remove(key);
        return entryMap.remove(key);
    }
    public int size() {
        return entryMap.size();
    }
    public Collection values() {
        return entryMap.values();
    }
}

Usage of CustomHashMap:

public static void main(String[] args) {
    System.out.println("== LinkedHashMap ==");
    Map<Object, String> map2 = new LinkedHashMap<Object, String>();
    addData(map2);

    System.out.println("== CustomHashMap ==");
    Map<Object, String> map = new CustomHashMap<Object, String>();
    addData(map);
}
public static void addData(Map<Object, String> map) {
    map.put(null, "1");
    map.put("name", "Yash");
    map.put("1", "1 - Str");
    map.put("1", "2 - Str"); // Overriding value
    map.put("", "1"); // Empty String
    map.put(" ", "1"); // Empty String
    map.put(1, "Int");
    map.put(null, "2"); // Null

    for (Map.Entry<Object, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " = " + entry.getValue());
    }
}

O/P:

== LinkedHashMap == | == CustomHashMap ==
null = 2            | name = Yash
name = Yash         | 1 = 1 - Str
1 = 2 - Str         | 1 = Int
 = 1                |
  = 1               |
1 = Int             |

If you know the KEY's are fixed then you can use EnumMap. Get the values form Properties/XML files

EX:

enum ORACLE {
    IP, URL, USER_NAME, PASSWORD, DB_Name;
}

EnumMap<ORACLE, String> props = new EnumMap<ORACLE, String>(ORACLE.class);
props.put(ORACLE.IP, "127.0.0.1");
props.put(ORACLE.URL, "...");
props.put(ORACLE.USER_NAME, "Scott");
props.put(ORACLE.PASSWORD, "Tiget");
props.put(ORACLE.DB_Name, "MyDB");

How to read a CSV file from a URL with Python?

Using pandas it is very simple to read a csv file directly from a url

import pandas as pd
data = pd.read_csv('https://example.com/passkey=wedsmdjsjmdd')

This will read your data in tabular format, which will be very easy to process

Get google map link with latitude/longitude

Use View mode returns a map with no markers or directions.

The example below uses the optional maptype parameter to display a satellite view of the map.

https://www.google.com/maps/embed/v1/view
  ?key=YOUR_API_KEY
  &center=-33.8569,151.2152
  &zoom=18
  &maptype=satellite

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

About duli's contribution with my own measurements.

The conclusion is that arrays of integers are faster than vectors of integers (5 times in my example). However, arrays and vectors are arround the same speed for more complex / not aligned data.

Disable Enable Trigger SQL server for a table

Below is the simplest way

Try the code

ALTER TRIGGER trigger_name DISABLE

That's it :)

How to serialize an object into a string

If you're storing an object as binary data in the database, then you really should use a BLOB datatype. The database is able to store it more efficiently, and you don't have to worry about encodings and the like. JDBC provides methods for creating and retrieving blobs in terms of streams. Use Java 6 if you can, it made some additions to the JDBC API that make dealing with blobs a whole lot easier.

If you absolutely need to store the data as a String, I would recommend XStream for XML-based storage (much easier than XMLEncoder), but alternative object representations might be just as useful (e.g. JSON). Your approach depends on why you actually need to store the object in this way.

Increment value in mysql update query

Who needs to update string and numbers SET @a = 0; UPDATE obj_disposition SET CODE = CONCAT('CD_', @a:=@a+1);

Docker: adding a file from a parent directory

Adding some code snippets to support the accepted answer.

Directory structure :

setup/
 |__docker/DockerFile
 |__target/scripts/<myscripts.sh>
src/
 |__<my source files>

Docker file entry:

RUN mkdir -p /home/vagrant/dockerws/chatServerInstaller/scripts/
RUN mkdir -p /home/vagrant/dockerws/chatServerInstaller/src/
WORKDIR /home/vagrant/dockerws/chatServerInstaller

#Copy all the required files from host's file system to the container file system.
COPY setup/target/scripts/install_x.sh scripts/
COPY setup/target/scripts/install_y.sh scripts/
COPY src/ src/

Command used to build the docker image

docker build -t test:latest -f setup/docker/Dockerfile .

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

I would try to connect to your Sharepoint site with this tool here. If that works you can be sure that the problem is in your code / configuration. That maybe does not solve your problem immediately but it rules out that there is something wrong with the server. Assuming that it does not work I would investigate the following:

  • Does your user really have enough rights on the site?
  • Is there a proxy that interferes? (Your configuration looks a bit like there is a proxy. Can you bypass it?)

I think there is nothing wrong with using security mode Transport, but I am not so sure about the proxyCredentialType="Ntlm", maybe this should be set to None.

How to resolve symbolic links in a shell script

In case where pwd can't be used (e.g. calling a scripts from a different location), use realpath (with or without dirname):

$(dirname $(realpath $PATH_TO_BE_RESOLVED))

Works both when calling through (multiple) symlink(s) or when directly calling the script - from any location.

CSS3 Transition - Fade out effect

This is the working code for your question.
Enjoy Coding....

<html>
   <head>

      <style>

         .animated {
            background-color: green;
            background-position: left top;
            padding-top:95px;
            margin-bottom:60px;
            -webkit-animation-duration: 10s;animation-duration: 10s;
            -webkit-animation-fill-mode: both;animation-fill-mode: both;
         }

         @-webkit-keyframes fadeOut {
            0% {opacity: 1;}
            100% {opacity: 0;}
         }

         @keyframes fadeOut {
            0% {opacity: 1;}
            100% {opacity: 0;}
         }

         .fadeOut {
            -webkit-animation-name: fadeOut;
            animation-name: fadeOut;
         }
      </style>

   </head>
   <body>

      <div id="animated-example" class="animated fadeOut"></div>

   </body>
</html>

HTML/Javascript: how to access JSON data loaded in a script tag with src set

I agree with Ben. You cannot load/import the simple JSON file.

But if you absolutely want to do that and have flexibility to update json file, you can

my-json.js

   var myJSON = {
      id: "12ws",
      name: "smith"
    }

index.html

<head>
  <script src="my-json.js"></script>
</head>
<body onload="document.getElementById('json-holder').innerHTML = JSON.stringify(myJSON);">
  <div id="json-holder"></div>
</body>

Error when trying to access XAMPP from a network

In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:

# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>

and add

"Allow from all"

after Allow from ::1 127.0.0.0/8 {line}

Restart xampp, and you are done.

In later versions of Xampp

...you can simply remove this part

#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

from the same file and it should work over the local network.

Binding an enum to a WinForms combo box, and then setting it

In Framework 4 you can use the following code:

To bind MultiColumnMode enum to combobox for example:

cbMultiColumnMode.Properties.Items.AddRange(typeof(MultiColumnMode).GetEnumNames());

and to get selected index:

MultiColumnMode multiColMode = (MultiColumnMode)cbMultiColumnMode.SelectedIndex;

note: I use DevExpress combobox in this example, you can do the same in Win Form Combobox

In STL maps, is it better to use map::insert than []?

When you write

map[key] = value;

there's no way to tell if you replaced the value for key, or if you created a new key with value.

map::insert() will only create:

using std::cout; using std::endl;
typedef std::map<int, std::string> MyMap;
MyMap map;
// ...
std::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value));
if ( ! res.second ) {
    cout << "key " <<  key << " already exists "
         << " with value " << (res.first)->second << endl;
} else {
    cout << "created key " << key << " with value " << value << endl;
}

For most of my apps, I usually don't care if I'm creating or replacing, so I use the easier to read map[key] = value.

Remove ALL styling/formatting from hyperlinks

As Chris said before me, just an a should override. For example:

a { color:red; }
a:hover { color:blue; }
.nav a { color:green; }

In this instance the .nav a would ALWAYS be green, the :hover wouldn't apply to it.

If there's some other rule affecting it, you COULD use !important, but you shouldn't. It's a bad habit to fall into.

.nav a { color:green !important; } /*I'm a bad person and shouldn't use !important */

Then it'll always be green, irrelevant of any other rule.

Is there a good jQuery Drag-and-drop file upload plugin?

Shameless Plug:

Filepicker.io handles uploading for you and returns a url. It supports drag/drop, cross browser. Also, people can upload from Dropbox/Facebook/Gmail which is super handy on a mobile device.

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

Test if element is present using Selenium WebDriver?

This works for me:

 if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
    //THEN CLICK ON THE SUBMIT BUTTON
}else{
    //DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
}

Where do I find the bashrc file on Mac?

~/.bashrc is already a path to .bashrc.

If you do echo ~ you'll see that it's a path to your home directory.

Homebrew directory is /usr/local/bin. Homebrew is installed inside it and everything installed by homebrew will be installed there.

For example, if you do brew install python Homebrew will put Python binary in /usr/local/bin.

Finally, to add Homebrew directory to your path you can run echo "export PATH=/usr/local/lib:$PATH" >> ~/.bashrc. It will create .bashrc file if it doesn't exist and then append the needed line to the end.

You can check the result by running tail ~/.bashrc.

JavaScript: location.href to open in new window/tab?

You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.

How to "comment-out" (add comment) in a batch/cmd?

You can use :: or rem for comments.

When commenting, use :: as it's 3 times faster. An example is shown here

Only if comments are in if, use rem, as the colons could make errors, because they are a label.

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

For me something similar happened when I had accidently added

apply plugin: 'kotlin-android'

to my android library module. Removing the line fixes the issue.

Declaring and initializing a string array in VB.NET

Public Function TestError() As String()
     Return {"foo", "bar"}
End Function

Works fine for me and should work for you, but you may need allow using implicit declarations in your project. I believe this is turning off Options strict in the Compile section of the program settings.

Since you are using VS 2008 (VB.NET 9.0) you have to declare create the new instance

New String() {"foo", "Bar"}

How to hide Table Row Overflow?

Need to specify two attributes, table-layout:fixed on table and white-space:nowrap; on the cells. You also need to move the overflow:hidden; to the cells too

table { width:250px;table-layout:fixed; }
table tr { height:1em;  }
td { overflow:hidden;white-space:nowrap;  } 

Here's a Demo . Tested in Firefox 3.5.3 and IE 7

Git ignore local file changes

If you dont want your local changes, then do below command to ignore(delete permanently) the local changes.

  • If its unstaged changes, then do checkout (git checkout <filename> or git checkout -- .)
  • If its staged changes, then first do reset (git reset <filename> or git reset) and then do checkout (git checkout <filename> or git checkout -- .)
  • If it is untracted files/folders (newly created), then do clean (git clean -fd)

If you dont want to loose your local changes, then stash it and do pull or rebase. Later merge your changes from stash.

  • Do git stash, and then get latest changes from repo git pull orign master or git rebase origin/master, and then merge your changes from stash git stash pop stash@{0}

How to close Android application?

none of all above answers working good on my app

here is my working code

on your exit button:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
mainIntent.putExtra("close", true);
startActivity(mainIntent);
finish();

that code is to close any other activity and bring MainActivity on top now on your MainActivity:

if( getIntent().getBooleanExtra("close", false)){
    finish();
}

Dealing with multiple Python versions and PIP?

So apparently there are multiple versions of easy_install and pip. It seems to be a big mess. Anyway, this is what I did to install Django for Python 2.7 on Ubuntu 12.10:

$ sudo easy_install-2.7 pip
Searching for pip
Best match: pip 1.1
Adding pip 1.1 to easy-install.pth file
Installing pip-2.7 script to /usr/local/bin

Using /usr/lib/python2.7/dist-packages
Processing dependencies for pip
Finished processing dependencies for pip

$ sudo pip-2.7 install django
Downloading/unpacking django
  Downloading Django-1.5.1.tar.gz (8.0Mb): 8.0Mb downloaded
  Running setup.py egg_info for package django

    warning: no previously-included files matching '__pycache__' found under directory '*'
    warning: no previously-included files matching '*.py[co]' found under directory '*'
Installing collected packages: django
  Running setup.py install for django
    changing mode of build/scripts-2.7/django-admin.py from 644 to 755

    warning: no previously-included files matching '__pycache__' found under directory '*'
    warning: no previously-included files matching '*.py[co]' found under directory '*'
    changing mode of /usr/local/bin/django-admin.py to 755
Successfully installed django
Cleaning up...

$ python
Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> 

Forcing to download a file using PHP

.htaccess Solution

To brute force all CSV files on your server to download, add in your .htaccess file:

AddType application/octet-stream csv

PHP Solution

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");

How to get all options in a drop-down list by Selenium WebDriver using C#?

WebElement drop_down =driver.findElement(By.id("Category"));
Select se = new Select(drop_down);
for(int i=0 ;i<se.getOptions().size(); i++)
System.out.println(se.getOptions().get(i).getAttribute("value"));

How to manage a redirect request after a jQuery Ajax call

in the servlet you should put response.setStatus(response.SC_MOVED_PERMANENTLY); to send the '301' xmlHttp status you need for a redirection...

and in the $.ajax function you should not use the .toString() function..., just

if (xmlHttp.status == 301) { top.location.href = 'xxxx.jsp'; }

the problem is it is not very flexible, you can't decide where you want to redirect..

redirecting through the servlets should be the best way. but i still can not find the right way to do it.

Linking dll in Visual Studio

You don't add or link directly against a DLL, you link against the LIB produced by the DLL.

A LIB provides symbols and other necessary data to either include a library in your code (static linking) or refer to the DLL (dynamic linking).

To link against a LIB, you need to add it to the project Properties -> Linker -> Input -> Additional Dependencies list. All LIB files here will be used in linking. You can also use a pragma like so:

#pragma comment(lib, "dll.lib")

With static linking, the code is included in your executable and there are no runtime dependencies. Dynamic linking requires a DLL with matching name and symbols be available within the search path (which is not just the path or system directory).

Calculating Page Load Time In JavaScript

Why so complicated? When you can do:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;

If you need more times check out the window.performance object:

console.log(window.performance);

Will show you the timing object:

connectEnd                 Time when server connection is finished.
connectStart               Time just before server connection begins.
domComplete                Time just before document readiness completes.
domContentLoadedEventEnd   Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive             Time just before readiness set to interactive.
domLoading                 Time just before readiness set to loading.
domainLookupEnd            Time after domain name lookup.
domainLookupStart          Time just before domain name lookup.
fetchStart                 Time when the resource starts being fetched.
loadEventEnd               Time when the load event is complete.
loadEventStart             Time just before the load event is fired.
navigationStart            Time after the previous document begins unload.
redirectCount              Number of redirects since the last non-redirect.
redirectEnd                Time after last redirect response ends.
redirectStart              Time of fetch that initiated a redirect.
requestStart               Time just before a server request.
responseEnd                Time after the end of a response or connection.
responseStart              Time just before the start of a response.
timing                     Reference to a performance timing object.
navigation                 Reference to performance navigation object.
performance                Reference to performance object for a window.
type                       Type of the last non-redirect navigation event.
unloadEventEnd             Time after the previous document is unloaded.
unloadEventStart           Time just before the unload event is fired.

Browser Support

More Info

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

Make sure that you aren't clicking on "Run unnamed" from 'run' tab. You must click on "run ". Or just click the green shortcut button.

How to Display blob (.pdf) in an AngularJS app

Most recent answer (for Angular 8+):

this.http.post("your-url",params,{responseType:'arraybuffer' as 'json'}).subscribe(
  (res) => {
    this.showpdf(res);
  }
)};

public Content:SafeResourceUrl;
showpdf(response:ArrayBuffer) {
  var file = new Blob([response], {type: 'application/pdf'});
  var fileURL = URL.createObjectURL(file);
  this.Content = this.sanitizer.bypassSecurityTrustResourceUrl(fileURL);
}

  HTML :

  <embed [src]="Content" style="width:200px;height:200px;" type="application/pdf" />

Print the address or pointer for value in C

I believe this would be most correct.

printf("%p", (void *)emp1);
printf("%p", (void *)*emp1);

printf() is a variadic function and must be passed arguments of the right types. The standard says %p takes void *.

How to create a new object instance from a Type

If this is for something that will be called a lot in an application instance, it's a lot faster to compile and cache dynamic code instead of using the activator or ConstructorInfo.Invoke(). Two easy options for dynamic compilation are compiled Linq Expressions or some simple IL opcodes and DynamicMethod. Either way, the difference is huge when you start getting into tight loops or multiple calls.

How to merge a list of lists with same type of items to a single list of items?

Here's the C# integrated syntax version:

var items =
    from list in listOfList
    from item in list
    select item;

Difference between web reference and service reference?

Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)

They are designed to work with WCF.

If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP

How to change default text color using custom theme?

In your Manifest you need to reference the name of the style that has the text color item inside it. Right now you are just referencing an empty style. So in your theme.xml do only this style:

<style name="Theme" parent="@android:style/TextAppearance">
    <item name="android:textColor">#ffffffff</item>
</style>

And keep you reference to in the Manifest the same (android:theme="@style/Theme")

EDIT:

theme.xml:

<style name="MyTheme" parent="@android:style/TextAppearance">
    <item name="android:textColor">#ffffffff</item>
    <item name="android:textSize">12dp</item>
</style>

Manifest:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/MyTheme">

Notice I combine the text color and size into the same style. Also, I changed the name of the theme to MyTheme and am now referencing that in the Manifest. And I changed to @android:style/TextAppearance for the parent value.

jQuery UI - Draggable is not a function?

Instead of

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>    
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>

Use

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>  
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>

How to get the date from the DatePicker widget in Android?

U can also use te Calendar.GregorianCalendar java class

    GregorianCalendar calendarBeg=new GregorianCalendar(datePicker.getYear(),
        datePicker.getMonth(),datePicker.getDayOfMonth());
    Date begin=calendarBeg.getTime();

ASP.Net 2012 Unobtrusive Validation with jQuery

In "configuration file" instead this lines:

<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />

by this lines:

<compilation debug="true" targetFramework="4.0" />
<httpRuntime targetFramework="4.0" />

This error because in version 4.0 library belong to "asp:RequiredFieldValidator" exist but in version 4.5 library not exist so you need to add library by yourself

Ruby: character to ascii from a string

puts "string".split('').map(&:ord).to_s

importing go files in same folder

I just wanted something really basic to move some files out of the main folder, like user2889485's reply, but his specific answer didnt work for me. I didnt care if they were in the same package or not.

My GOPATH workspace is c:\work\go and under that I have

/src/pg/main.go      (package main)
/src/pg/dbtypes.go   (pakage dbtypes)

in main.go I import "/pg/dbtypes"

Javascript: Call a function after specific time period

sounds like you're looking for setInterval. It's as easy as this:

function FetchData() {
  // do something
}
setInterval(FetchData, 60000);

if you only want to call something once, theres setTimeout.

Python 2.7 getting user input and manipulating as string without quotations

Use raw_input() instead of input():

testVar = raw_input("Ask user for something.")

input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.

How to bind DataTable to Datagrid

In cs file

DataTable employeeData = CreateDataTable();
gridEmployees.DataContext = employeeData.DefaultView;

In xaml file

<DataGrid Name="gridEmployees" ItemsSource="{Binding}">

How to use if, else condition in jsf to display image

For those like I who just followed the code by skuntsel and received a cryptic stack trace, allow me to save you some time.

It seems c:if cannot by itself be followed by c:otherwise.

The correct solution is as follows:

<c:choose>
    <c:when test="#{some.test}">
        <p>some.test is true</p>
    </c:when>
    <c:otherwise>
        <p>some.test is not true</p>
    </c:otherwise>
</c:choose>

You can add additional c:when tests in as necessary.

How do I clear the std::queue efficiently?

A common idiom for clearing standard containers is swapping with an empty version of the container:

void clear( std::queue<int> &q )
{
   std::queue<int> empty;
   std::swap( q, empty );
}

It is also the only way of actually clearing the memory held inside some containers (std::vector)

Java ResultSet how to check if there are any results

ResultSet rs = rs.executeQuery();
if(rs.next())
{
  rs = rs.executeQuery();
  while(rs.next())
  {
    //do code part
  }
}
else
{
  //else if no result set
}

It is better to re execute query because when we call if(rs.next()){....} first row of ResultSet will be executed and after it inside while(rs.next()){....} we'll get result from next line. So I think re-execution of query inside if is the better option.

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

spring.jackson.serialization-inclusion=non_null used to work for us

But when we upgraded spring boot version to 1.4.2.RELEASE or higher, it stopped working.

Now, another property spring.jackson.default-property-inclusion=non_null is doing the magic.

in fact, serialization-inclusion is deprecated. This is what my intellij throws at me.

Deprecated: ObjectMapper.setSerializationInclusion was deprecated in Jackson 2.7

So, start using spring.jackson.default-property-inclusion=non_null instead

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

How to make a transparent HTML button?

Make a div and use your image ( png with transparent background ) as the background of the div, then you can apply any text within that div to hover over the button. Something like this:

<div class="button" onclick="yourbuttonclickfunction();" >
Your Button Label Here
</div>

CSS:

.button {
height:20px;
width:40px;
background: url("yourimage.png");
}

Best practice to call ConfigureAwait for all server-side code

I have some general thoughts about the implementation of Task:

  1. Task is disposable yet we are not supposed to use using.
  2. ConfigureAwait was introduced in 4.5. Task was introduced in 4.0.
  3. .NET Threads always used to flow the context (see C# via CLR book) but in the default implementation of Task.ContinueWith they do not b/c it was realised context switch is expensive and it is turned off by default.
  4. The problem is a library developer should not care whether its clients need context flow or not hence it should not decide whether flow the context or not.
  5. [Added later] The fact that there is no authoritative answer and proper reference and we keep fighting on this means someone has not done their job right.

I have got a few posts on the subject but my take - in addition to Tugberk's nice answer - is that you should turn all APIs asynchronous and ideally flow the context . Since you are doing async, you can simply use continuations instead of waiting so no deadlock will be cause since no wait is done in the library and you keep the flowing so the context is preserved (such as HttpContext).

Problem is when a library exposes a synchronous API but uses another asynchronous API - hence you need to use Wait()/Result in your code.

NoSQL Use Case Scenarios or WHEN to use NoSQL

It really is an "it depends" kinda question. Some general points:

  • NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
  • NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
  • Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
  • It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
  • IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
  • It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
  • NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.

How to have a drop down <select> field in a rails form?

<%= f.select :email_provider, ["gmail","yahoo","msn"]%>

Selecting all text in HTML text input when clicked

You can use this javascript snippet:

<input onClick="this.select();" value="Sample Text" />

But apparently it doesn't work on mobile Safari. In those cases you can use:

<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" />

Is it necessary to use # for creating temp tables in SQL server?

The difference between this two tables ItemBack1 and #ItemBack1 is that the first on is persistent (permanent) where as the other is temporary.

Now if take a look at your question again

Is it necessary to Use # for creating temp table in sql server?

The answer is Yes, because without this preceding # the table will not be a temporary table, it will be independent of all sessions and scopes.

How to make a div have a fixed size?

Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.

max-width:something px;
max-height:something px;

The other option would be to use the devlopr tools and see if you can remove the natural padding.

padding: 0;

3 column layout HTML/CSS

CSS:

     .container div{
 width: 33.33%;
 float: left;
 height: 100px ;} 

Clear floats after the columns

 .container:after {
 content: "";
 display: table;
 clear: both;}

Send FormData with other field in AngularJS

Don't serialize FormData with POSTing to server. Do this:

this.uploadFileToUrl = function(file, title, text, uploadUrl){
    var payload = new FormData();

    payload.append("title", title);
    payload.append('text', text);
    payload.append('file', file);

    return $http({
        url: uploadUrl,
        method: 'POST',
        data: payload,
        //assign content-type as undefined, the browser
        //will assign the correct boundary for us
        headers: { 'Content-Type': undefined},
        //prevents serializing payload.  don't do it.
        transformRequest: angular.identity
    });
}

Then use it:

MyService.uploadFileToUrl(file, title, text, uploadUrl).then(successCallback).catch(errorCallback);

cannot import name patterns

I Resolved it by cloning my project directly into Eclipse from GIT,

Initially I was cloning it at specific location on file system then importing it as existing project into Eclipse.

Query comparing dates in SQL

Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "

Ex:

 select id,numbers_from,created_date,amount_numbers,SMS_text 
 from Test_Table
 where 
 created_date <= #2013-04-12#

Running unittest with typical test directory structure

This BASH script will execute the python unittest test directory from anywhere in the file system, no matter what working directory you are in.

This is useful when staying in the ./src or ./example working directory and you need a quick unit test:

#!/bin/bash

this_program="$0"
dirname="`dirname $this_program`"
readlink="`readlink -e $dirname`"

python -m unittest discover -s "$readlink"/test -v

No need for a test/__init__.py file to burden your package/memory-overhead during production.

System has not been booted with systemd as init system (PID 1). Can't operate

use this command for run every service just write name service for example :

for xrdp :

sudo /etc/init.d/xrdp start

for redis :

sudo /etc/init.d/redis start

(for any other service, check the init.d folder for filenames)

How to serialize object to CSV file?

Worth mentioning that the handlebar library https://github.com/jknack/handlebars.java can trivialize many transformation tasks include toCSV.

XPath using starts-with function

Try this

//ITEM/*[starts-with(text(),'2552')]/following-sibling::*

Python Remove last char from string and return it

Yes, python strings are immutable and any modification will result in creating a new string. This is how it's mostly done.

So, go ahead with it.

Changing color of Twitter bootstrap Nav-Pills

Bootstrap 4.x Solution

.nav-pills .nav-link.active {
    background-color: #ff0000 !important;
}

Setting TIME_WAIT TCP

setting the tcp_reuse is more useful than changing time_wait, as long as you have the parameter (kernels 3.2 and above, unfortunately that disqualifies all versions of RHEL and XenServer).

Dropping the value, particularly for VPN connected users, can result in constant recreation of proxy tunnels on the outbound connection. With the default Netscaler (XenServer) config, which is lower than the default Linux config, Chrome will sometimes have to recreate the proxy tunnel up to a dozen times to retrieve one web page. Applications that don't retry, such as Maven and Eclipse P2, simply fail.

The original motive for the parameter (avoid duplication) was made redundant by a TCP RFC that specifies timestamp inclusion on all TCP requests.

Invisible characters - ASCII

Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.

            '\u2060', // Word Joiner
            '\u2061', // FUNCTION APPLICATION
            '\u2062', // INVISIBLE TIMES
            '\u2063', // INVISIBLE SEPARATOR
            '\u2064', // INVISIBLE PLUS
            '\u2066', // LEFT - TO - RIGHT ISOLATE
            '\u2067', // RIGHT - TO - LEFT ISOLATE
            '\u2068', // FIRST STRONG ISOLATE
            '\u2069', // POP DIRECTIONAL ISOLATE
            '\u206A', // INHIBIT SYMMETRIC SWAPPING
            '\u206B', // ACTIVATE SYMMETRIC SWAPPING
            '\u206C', // INHIBIT ARABIC FORM SHAPING
            '\u206D', // ACTIVATE ARABIC FORM SHAPING
            '\u206E', // NATIONAL DIGIT SHAPES
            '\u206F', // NOMINAL DIGIT SHAPES
            '\u200B', // Zero-Width Space
            '\u200C', // Zero Width Non-Joiner
            '\u200D', // Zero Width Joiner
            '\u200E', // Left-To-Right Mark
            '\u200F', // Right-To-Left Mark
            '\u061C', // Arabic Letter Mark
            '\uFEFF', // Byte Order Mark
            '\u180E', // Mongolian Vowel Separator
            '\u00AD'  // soft-hyphen

c++ parse int from string

Some handy quick functions (if you're not using Boost):

template<typename T>
std::string ToString(const T& v)
{
    std::ostringstream ss;
    ss << v;
    return ss.str();
}

template<typename T>
T FromString(const std::string& str)
{
    std::istringstream ss(str);
    T ret;
    ss >> ret;
    return ret;
}

Example:

int i = FromString<int>(s);
std::string str = ToString(i);

Works for any streamable types (floats etc). You'll need to #include <sstream> and possibly also #include <string>.

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

You could add the following VBA code to your sheet:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1") > 0.5 Then
        MsgBox "Discount too high"
    End If
End Sub

Every time a cell is changed on the sheet, it will check the value of cell A1.

Notes:

  • if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
  • the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.

Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):

  • Pros: his method will work if A1's value is linked to cells located in other sheets.
  • Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.

Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.

nvarchar(max) vs NText

nvarchar(max) is what you want to be using. The biggest advantage is that you can use all the T-SQL string functions on this data type. This is not possible with ntext. I'm not aware of any real disadvantages.

How to get integer values from a string in Python?

if you have multiple sets of numbers then this is another option

>>> import re
>>> print(re.findall('\d+', 'xyz123abc456def789'))
['123', '456', '789']

its no good for floating point number strings though.

Permission denied (publickey,keyboard-interactive)

The server first tries to authenticate you by public key. That doesn't work (I guess you haven't set one up), so it then falls back to 'keyboard-interactive'. It should then ask you for a password, which presumably you're not getting right. Did you see a password prompt?

How can I change the version of npm using nvm?

  1. find the node and npm version you want to use from here https://nodejs.org/en/download/releases/
  2. nvm use 8.11.4
  3. you already got the npm 5.6 with node 8.11.4

Just go with nvm use node_version

Basic Python client socket example

Here is the simplest python socket example.

Server side:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

Client Side:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
  • First run the SocketServer.py, and make sure the server is ready to listen/receive sth
  • Then the client send info to the server;
  • After the server received sth, it terminates

"python" not recognized as a command

This is because the Python exec are not in the search path of your operating system. In windows, start CMD. Type in

setx PATH PythonPath

where PythonPath is usually C:\Python27 or C:\Python33 or C:\Users\<Your User Name>\AppData\Local\Programs\Python\Python37 depending on your Python version. After restarting the CMD, you should get see outcomes when typing

Python --version

Complex nesting of partials and templates

Well, since you can currently only have one ngView directive... I use nested directive controls. This allows you to set up templating and inherit (or isolate) scopes among them. Outside of that I use ng-switch or even just ng-show to choose which controls I'm displaying based on what's coming in from $routeParams.

EDIT Here's some example pseudo-code to give you an idea of what I'm talking about. With a nested sub navigation.

Here's the main app page

<!-- primary nav -->
<a href="#/page/1">Page 1</a>
<a href="#/page/2">Page 2</a>
<a href="#/page/3">Page 3</a>

<!-- display the view -->
<div ng-view>
</div>

Directive for the sub navigation

app.directive('mySubNav', function(){
    return {
        restrict: 'E',
        scope: {
           current: '=current'
        },
        templateUrl: 'mySubNav.html',
        controller: function($scope) {
        }
    };
});

template for the sub navigation

<a href="#/page/1/sub/1">Sub Item 1</a>
<a href="#/page/1/sub/2">Sub Item 2</a>
<a href="#/page/1/sub/3">Sub Item 3</a>

template for a main page (from primary nav)

<my-sub-nav current="sub"></my-sub-nav>

<ng-switch on="sub">
  <div ng-switch-when="1">
      <my-sub-area1></my-sub-area>
  </div>
  <div ng-switch-when="2">
      <my-sub-area2></my-sub-area>
  </div>
  <div ng-switch-when="3">
      <my-sub-area3></my-sub-area>
  </div>
</ng-switch>

Controller for a main page. (from the primary nav)

app.controller('page1Ctrl', function($scope, $routeParams) {
     $scope.sub = $routeParams.sub;
});

Directive for a Sub Area

app.directive('mySubArea1', function(){
    return {
        restrict: 'E',
        templateUrl: 'mySubArea1.html',
        controller: function($scope) {
            //controller for your sub area.
        }
    };
});

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Static variables in JavaScript

In JavaScript, there is no term or keyword static, but we can put such data directly into function object (like in any other object).

function f() {
    f.count = ++f.count || 1 // f.count is undefined at first
    alert("Call No " + f.count)
}

f(); // Call No 1

f(); // Call No 2

Fix CSS hover on iPhone/iPad/iPod

I know that the question is old but still relevant.

The only solution that I've found that works is using @media query like this:

@media (hover) { my-class:hover {
  //properties
 }
}

My reference: https://www.jonathanfielding.com/an-introduction-to-interaction-media-features/

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

This cannot be done for the table; besides, you even cannot change this default value at all.

The answer is a server variable datetime_format, it is unused.

Setting a div's height in HTML with CSS

I can think of 2 options

  1. Use javascript to resize the smaller column on page load.
  2. Fake the equal heights by setting the background-color for the column on the container <div/> instead (<div class="separator"/>) with repeat-y

What is a classpath and how do I set it?

Static member of a class can be called directly without creating object instance. Since the main method is static Java virtual Machine can call it without creating any instance of a class which contains the main method, which is start point of program.

How do I set response headers in Flask?

This was how added my headers in my flask application and it worked perfectly

@app.after_request
def add_header(response):
    response.headers['X-Content-Type-Options'] = 'nosniff'
    return response

How to get history on react-router v4?

You just need to have a module that exports a history object. Then you would import that object throughout your project.

// history.js
import { createBrowserHistory } from 'history'

export default createBrowserHistory({
  /* pass a configuration object here if needed */
})

Then, instead of using one of the built-in routers, you would use the <Router> component.

// index.js
import { Router } from 'react-router-dom'
import history from './history'
import App from './App'

ReactDOM.render((
  <Router history={history}>
    <App />
  </Router>
), holder)
// some-other-file.js
import history from './history'
history.push('/go-here')

Java Desktop application: SWT vs. Swing

One thing to consider: Screenreaders

For some reasons, some Swing components do not work well when using a screenreader (and the Java AccessBridge for Windows). Know that different screenreaders result in different behaviour. And in my experience the SWT-Tree performs a lot better than the Swing-Tree in combination with a screenreader. Thus our application ended up in using both SWT and Swing components.

For distributing and loading the proper SWT-library, you might find this link usefull: http://www.chrisnewland.com/select-correct-swt-jar-for-your-os-and-jvm-at-runtime-191

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

Matplotlib 2 Subplots, 1 Colorbar

You can simplify Joe Kington's code using the axparameter of figure.colorbar() with a list of axes. From the documentation:

ax

None | parent axes object(s) from which space for a new colorbar axes will be stolen. If a list of axes is given they will all be resized to make room for the colorbar axes.

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax in axes.flat:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

fig.colorbar(im, ax=axes.ravel().tolist())

plt.show()

1

Parse JSON file using GSON

Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then use Gson.fromJson() method.
For example:

class Response {
    Map<String, App> descriptor;
    // standard getters & setters...
}

class App {
  String name;
  int age;
  String[] messages;
  // standard getters & setters...
}

Then just use:

Gson gson = new Gson();
Response response = gson.fromJson(yourJson, Response.class);

Where yourJson can be a String, any Reader, a JsonReader or a JsonElement.

Finally, if you want to access any particular field, you just have to do:

String name = response.getDescriptor().get("app3").getName();

You can always parse the JSON manually as suggested in other answers, but personally I think this approach is clearer, more maintainable in long term and it fits better with the whole idea of JSON.

Deploying my application at the root in Tomcat

In my server I am using this and root autodeploy works just fine:

   <Host name="mysite" autoDeploy="true" appBase="webapps" unpackWARs="true" deployOnStartup="true">
        <Alias>www.mysite.com</Alias>
        <Valve className="org.apache.catalina.valves.RemoteIpValve" protocolHeader="X-Forwarded-Proto"/>
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="mysite_access_log." suffix=".txt"
           pattern="%h %l %u %t &quot;%r&quot; %s %b"/>
        <Context path="/mysite" docBase="mysite" reloadable="true"/>
    </Host>

How does Facebook Sharer select Images and other metadata when sharing my URL?

From my experience, the http://www.facebook.com/sharer.php does not use meta tags. It uses the string you pass. See below.

http://www.facebook.com/sharer.php?s=100&p[title]=THIS IS MY TITLE&p[summary]=THIS IS MY SUMMARY&p[url]=http://www.MYURL.com&&p[images][0]=http://www.MYURL.com/img/IMAGEADDRESS

The meta tags work with Facebook's developer like/send buttons, as does the other Open Graph info. So if you use one of Facebook's actual elements like the comments and such, that will all tie into the Open Graph stuff.

UPDATE: There are two ways to use the sharer * note the ?s versus the ?u value in the query string
1 ==> STRING: http://www.facebook.com/sharer.php?s + content from above
~~> Will pull info from the string.
2 ==> URL: http://www.facebook.com/sharer.php?u=url where url equals an actual url
~~> Will scrape the page provided in the url value
~~> You can test test the values here: https://developers.facebook.com/tools/debug

Checkbox value true/false

Use Checked = true

$("#checkbox1").prop('checked', true);

Note: I am not clear whether you want to onclick/onchange event on checkbox. is(":checked", function(){}) is a wrong in the question.

how to fix groovy.lang.MissingMethodException: No signature of method:

This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.

class name - User is accepted but user is not.

How to create a hex dump of file containing only the hex characters without spaces in bash?

It seems to depend on the details of the version of od. On OSX, use this:

od -t x1 -An file |tr -d '\n '

(That's print as type hex bytes, with no address. And whitespace deleted afterwards, of course.)

How to convert a Java object (bean) to key-value pairs (and vice versa)?

Use juffrou-reflect's BeanWrapper. It is very performant.

Here is how you can transform a bean into a map:

public static Map<String, Object> getBeanMap(Object bean) {
    Map<String, Object> beanMap = new HashMap<String, Object>();
    BeanWrapper beanWrapper = new BeanWrapper(BeanWrapperContext.create(bean.getClass()));
    for(String propertyName : beanWrapper.getPropertyNames())
        beanMap.put(propertyName, beanWrapper.getValue(propertyName));
    return beanMap;
}

I developed Juffrou myself. It's open source, so you are free to use it and modify. And if you have any questions regarding it, I'll be more than happy to respond.

Cheers

Carlos

How connect Postgres to localhost server using pgAdmin on Ubuntu?

First you should change the password using terminal. (username is postgres)

postgres=# \password postgres

Then you will be prompted to enter the password and confirm it.

Now you will be able to connect using pgadmin with the new password.

HTML embedded PDF iframe

Iframe

<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>

Object

<object data="your_url_to_pdf" type="application/pdf">
  <embed src="your_url_to_pdf" type="application/pdf" />
</object>

What's the easiest way to call a function every 5 seconds in jQuery?

you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)

<script>
  var time = 3670;
window.setInterval(function(){

  // Time calculations for days, hours, minutes and seconds
    var h = Math.floor(time / 3600);
    var m = Math.floor(time % 3600 / 60);
    var s = Math.floor(time % 3600 % 60);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  h + "h "
  + m + "m " + s + "s ";

  // If the count down is finished, write some text 
  if (time < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

  time--;
}, 1000);


</script>

How can I add additional PHP versions to MAMP

The file /Applications/MAMP/bin/mamp/mamp.conf.json holds the MAMP configuration, look for the section:

{
  "name": "PHP",
  "version": "5.6.28, 7.0.20"
}

which lists the the php versions which will be displayed in the GUI, obviously you need to have downloaded the PHP version from the MAMP site first and placed it in /Applications/MAMP/bin/php for this to work.

What is the right way to check for a null string in Objective-C?

if ([linkedStr isEqual:(id)[NSNull null]])
                {
                    _linkedinLbl.text=@"No";
                }else{
                    _linkedinLbl.text=@"Yes";
                }

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

How to implement a FSM - Finite State Machine in Java

You can implement Finite State Machine in two different ways.

Option 1:

Finite State machine with a pre-defined workflow : Recommended if you know all states in advance and state machine is almost fixed without any changes in future

  1. Identify all possible states in your application

  2. Identify all the events in your application

  3. Identify all the conditions in your application, which may lead state transition

  4. Occurrence of an event may cause transitions of state

  5. Build a finite state machine by deciding a workflow of states & transitions.

    e.g If an event 1 occurs at State 1, the state will be updated and machine state may still be in state 1.

    If an event 2 occurs at State 1, on some condition evaluation, the system will move from State 1 to State 2

This design is based on State and Context patterns.

Have a look at Finite State Machine prototype classes.

Option 2:

Behavioural trees: Recommended if there are frequent changes to state machine workflow. You can dynamically add new behaviour without breaking the tree.

enter image description here

The base Task class provides a interface for all these tasks, the leaf tasks are the ones just mentioned, and the parent tasks are the interior nodes that decide which task to execute next.

The Tasks have only the logic they need to actually do what is required of them, all the decision logic of whether a task has started or not, if it needs to update, if it has finished with success, etc. is grouped in the TaskController class, and added by composition.

The decorators are tasks that “decorate” another class by wrapping over it and giving it additional logic.

Finally, the Blackboard class is a class owned by the parent AI that every task has a reference to. It works as a knowledge database for all the leaf tasks

Have a look at this article by Jaime Barrachina Verdia for more details

HTML5 Canvas and Anti-aliasing

Anti-aliasing cannot be turned on or off, and is controlled by the browser.

Can I turn off antialiasing on an HTML <canvas> element?

How do I get a list of files in a directory in C++?

You can use the following code for getting all files in a directory.A simple modification in the Andreas Bonini answer to remove the occurance of "." and ".."

CString dirpath="d:\\mydir"
DWORD errVal = ERROR_SUCCESS;
HANDLE dir;
WIN32_FIND_DATA file_data;
CString  file_name,full_file_name;
if ((dir = FindFirstFile((dirname+ "/*"), &file_data)) == INVALID_HANDLE_VALUE)
{
    errVal=ERROR_INVALID_ACCEL_HANDLE;
    return errVal;
}

while (FindNextFile(dir, &file_data)) {
    file_name = file_data.cFileName;
    full_file_name = dirname+ file_name;
    if (strcmp(file_data.cFileName, ".") != 0 && strcmp(file_data.cFileName, "..") != 0)
    {
        m_List.AddTail(full_file_name);
    }
}

Plot logarithmic axes with matplotlib in python

if you want to change the base of logarithm, just add:

plt.yscale('log',base=2) 

Before Matplotlib 3.3, you would have to use basex/basey as the bases of log

Use PHP to create, edit and delete crontab jobs?

Check a cronjob

function cronjob_exists($command){

    $cronjob_exists=false;

    exec('crontab -l', $crontab);


    if(isset($crontab)&&is_array($crontab)){

        $crontab = array_flip($crontab);

        if(isset($crontab[$command])){

            $cronjob_exists=true;

        }

    }
    return $cronjob_exists;
}

Append a cronjob

function append_cronjob($command){

    if(is_string($command)&&!empty($command)&&cronjob_exists($command)===FALSE){

        //add job to crontab
        exec('echo -e "`crontab -l`\n'.$command.'" | crontab -', $output);


    }

    return $output;
}

Remove a crontab

exec('crontab -r', $crontab);

Example

exec('crontab -r', $crontab);

append_cronjob('* * * * * curl -s http://localhost/cron/test1.php');

append_cronjob('* * * * * curl -s http://localhost/cron/test2.php');

append_cronjob('* * * * * curl -s http://localhost/cron/test3.php');

what is the most efficient way of counting occurrences in pandas?

When you want to count the frequency of categorical data in a column in pandas dataFrame use: df['Column_Name'].value_counts()

-Source.

Picking a random element from a set

A somewhat related Did You Know:

There are useful methods in java.util.Collections for shuffling whole collections: Collections.shuffle(List<?>) and Collections.shuffle(List<?> list, Random rnd).

LEFT JOIN in LINQ to entities?

May be I come later to answer but right now I'm facing with this... if helps there are one more solution (the way i solved it).

    var query2 = (
    from users in Repo.T_Benutzer
    join mappings in Repo.T_Benutzer_Benutzergruppen on mappings.BEBG_BE equals users.BE_ID into tmpMapp
    join groups in Repo.T_Benutzergruppen on groups.ID equals mappings.BEBG_BG into tmpGroups
    from mappings in tmpMapp.DefaultIfEmpty()
    from groups in tmpGroups.DefaultIfEmpty()
    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);

By the way, I tried using the Stefan Steiger code which also helps but it was slower as hell.

Get a list of URLs from a site

I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.

Upgrade version of Pandas

According to an article on Medium, this will work:

install --upgrade pandas==1.0.0rc0

How to create a directory and give permission in single command

You could write a simple shell script, for example:

#!/bin/bash
mkdir "$1"
chmod 777 "$1"

Once saved, and the executable flag enabled, you could run it instead of mkdir and chmod:

./scriptname path/foldername

However, alex's answer is much better because it spawns one process instead of three. I didn't know about the -m option.

How to get the day of week and the month of the year?

Use the standard javascript Date class. No need for arrays. No need for extra libraries.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

_x000D_
_x000D_
var options = {  weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };_x000D_
var prnDt = 'Printed on ' + new Date().toLocaleTimeString('en-us', options);_x000D_
_x000D_
console.log(prnDt);
_x000D_
_x000D_
_x000D_

append new row to old csv file python

Based in the answer of @G M and paying attention to the @John La Rooy's warning, I was able to append a new row opening the file in 'a'mode.

Even in windows, in order to avoid the newline problem, you must declare it as newline=''.

Now you can open the file in 'a'mode (without the b).

import csv

with open(r'names.csv', 'a', newline='') as csvfile:
    fieldnames = ['This','aNew']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writerow({'This':'is', 'aNew':'Row'})

I didn't try with the regular writer (without the Dict), but I think that it'll be ok too.

Speed up rsync with Simultaneous/Concurrent File Transfers?

I've developed a python package called: parallel_sync

https://pythonhosted.org/parallel_sync/pages/examples.html

Here is a sample code how to use it:

from parallel_sync import rsync
creds = {'user': 'myusername', 'key':'~/.ssh/id_rsa', 'host':'192.168.16.31'}
rsync.upload('/tmp/local_dir', '/tmp/remote_dir', creds=creds)

parallelism by default is 10; you can increase it:

from parallel_sync import rsync
creds = {'user': 'myusername', 'key':'~/.ssh/id_rsa', 'host':'192.168.16.31'}
rsync.upload('/tmp/local_dir', '/tmp/remote_dir', creds=creds, parallelism=20)

however note that ssh typically has the MaxSessions by default set to 10 so to increase it beyond 10, you'll have to modify your ssh settings.

Multi value Dictionary

If the values are related, why not encapsulate them in a class and just use the plain old Dictionary?

Counting words in string

Here's a function that counts number of words in an HTML code:

$(this).val()
    .replace(/((&nbsp;)|(<[^>]*>))+/g, '') // remove html spaces and tags
    .replace(/\s+/g, ' ') // merge multiple spaces into one
    .trim() // trim ending and beginning spaces (yes, this is needed)
    .match(/\s/g) // find all spaces by regex
    .length // get amount of matches

presentViewController and displaying navigation bar

Swift 3

        let vc0 : ViewController1 = ViewController1()
        let vc2: NavigationController1 = NavigationController1(rootViewController: vc0)
        self.present(vc2, animated: true, completion: nil)

Multi-statement Table Valued Function vs Inline Table Valued Function

Internally, SQL Server treats an inline table valued function much like it would a view and treats a multi-statement table valued function similar to how it would a stored procedure.

When an inline table-valued function is used as part of an outer query, the query processor expands the UDF definition and generates an execution plan that accesses the underlying objects, using the indexes on these objects.

For a multi-statement table valued function, an execution plan is created for the function itself and stored in the execution plan cache (once the function has been executed the first time). If multi-statement table valued functions are used as part of larger queries then the optimiser does not know what the function returns, and so makes some standard assumptions - in effect it assumes that the function will return a single row, and that the returns of the function will be accessed by using a table scan against a table with a single row.

Where multi-statement table valued functions can perform poorly is when they return a large number of rows and are joined against in outer queries. The performance issues are primarily down to the fact that the optimiser will produce a plan assuming that a single row is returned, which will not necessarily be the most appropriate plan.

As a general rule of thumb we have found that where possible inline table valued functions should be used in preference to multi-statement ones (when the UDF will be used as part of an outer query) due to these potential performance issues.

How do I join two SQLite tables in my Android application?

In addition to @pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN like this

SELECT * FROM expense INNER JOIN refuel
ON exp_id = expense_id
WHERE refuel_id = 1

via raw query like this -

String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
        + " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
        + " WHERE " + RefuelTable.ID + " = " +  id;
Cursor c = db.rawQuery(
        rawQuery,
        null
);

because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -

SELECT *
FROM expense, refuel
WHERE exp_id = expense_id AND refuel_id = 1

and hence be able to take advanatage of the SQLiteDatabase.query() helper method

Cursor c = db.query(
        RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
        Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
        RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " +  id,
        null,
        null,
        null,
        null
);

For a detailed blog post check this http://blog.championswimmer.in/2015/12/doing-a-table-join-in-android-without-using-rawquery