Programs & Examples On #Storekit

Store Kit is an iOS framework that allows an application to request payment from a user for additional functionality or content.

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

I use the following method in my project

-(NSArray*)networkErrorCodes
{
    static NSArray *codesArray;
    if (![codesArray count]){
        @synchronized(self){
            const int codes[] = {
                //kCFURLErrorUnknown,     //-998
                //kCFURLErrorCancelled,   //-999
                //kCFURLErrorBadURL,      //-1000
                //kCFURLErrorTimedOut,    //-1001
                //kCFURLErrorUnsupportedURL, //-1002
                //kCFURLErrorCannotFindHost, //-1003
                kCFURLErrorCannotConnectToHost,     //-1004
                kCFURLErrorNetworkConnectionLost,   //-1005
                kCFURLErrorDNSLookupFailed,         //-1006
                //kCFURLErrorHTTPTooManyRedirects,    //-1007
                kCFURLErrorResourceUnavailable,     //-1008
                kCFURLErrorNotConnectedToInternet,  //-1009
                //kCFURLErrorRedirectToNonExistentLocation,   //-1010
                kCFURLErrorBadServerResponse,               //-1011
                //kCFURLErrorUserCancelledAuthentication,     //-1012
                //kCFURLErrorUserAuthenticationRequired,      //-1013
                //kCFURLErrorZeroByteResource,        //-1014
                //kCFURLErrorCannotDecodeRawData,     //-1015
                //kCFURLErrorCannotDecodeContentData, //-1016
                //kCFURLErrorCannotParseResponse,     //-1017
                kCFURLErrorInternationalRoamingOff, //-1018
                kCFURLErrorCallIsActive,                //-1019
                //kCFURLErrorDataNotAllowed,              //-1020
                //kCFURLErrorRequestBodyStreamExhausted,  //-1021
                kCFURLErrorFileDoesNotExist,            //-1100
                //kCFURLErrorFileIsDirectory,             //-1101
                kCFURLErrorNoPermissionsToReadFile,     //-1102
                //kCFURLErrorDataLengthExceedsMaximum,     //-1103
            };
            int size = sizeof(codes)/sizeof(int);
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (int i=0;i<size;++i){
                [array addObject:[NSNumber numberWithInt:codes[i]]];
            }
            codesArray = [array copy];
        }
    }
    return codesArray;
}

Then I just check the error code and show alert if it is in the list

if ([[self networkErrorCodes] containsObject:[NSNumber
numberWithInt:[error code]]]){ 
// Fire Alert View Here
}

But as you can see I commented out codes that I think does not fit to my definition of NO INTERNET. E.g the code of -1012 (Authentication fail.) You may edit the list as you like.

In my project I use it at username/password entering from user. And in my view (physical) network connection errors could be the only reason to show alert view in your network based app. In any other case (e.g. incorrect username/password pair) I prefer to do some custom user friendly animation, OR just repeat the failed attempt again without any attention of the user. Especially if the user didn't explicitly initiated a network call.

Regards to martinezdelariva for a link to documentation.

What is a Subclass

A sub class is a small file of a program that extends from some other class. For example you make a class about cars in general and have basic information that holds true for all cars with your constructors and stuff then you have a class that extends from that on a more specific car or line of cars that would have new variables/methods. I see you already have plenty of examples of code from above by the time I get to post this but I hope this description helps.

DateTime.ToString() format that can be used in a filename or extension?

Personally I like it this way:

DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss")

Because it distinguishes between the date and the time.

Python BeautifulSoup extract text between element

Use .children instead:

from bs4 import NavigableString, Comment
print ''.join(unicode(child) for child in hit.children 
    if isinstance(child, NavigableString) and not isinstance(child, Comment))

Yes, this is a bit of a dance.

Output:

>>> for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
...     print ''.join(unicode(child) for child in hit.children 
...         if isinstance(child, NavigableString) and not isinstance(child, Comment))
... 




      THIS IS MY TEXT

How to import an excel file in to a MySQL database

Fastest and simpliest way is to save XLS as ODS (open document spreasheet) and import it from PhpMyAdmin enter image description here

How can I assign an ID to a view programmatically?

Android id overview

An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.)

Assign id via XML

  • Add an attribute of android:id="@+id/somename" to your view.
  • When your application is built, the android:id will be assigned a unique int for use in code.
  • Reference your android:id's int value in code using "R.id.somename" (effectively a constant.)
  • this int can change from build to build so never copy an id from gen/package.name/R.java, just use "R.id.somename".
  • (Also, an id assigned to a Preference in XML is not used when the Preference generates its View.)

Assign id via code (programmatically)

  • Manually set ids using someView.setId(int);
  • The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)
  • For example, if creating and numbering several views representing items, you could use their item number.

Uniqueness of ids

  • XML-assigned ids will be unique.
  • Code-assigned ids do not have to be unique
  • Code-assigned ids can (theoretically) conflict with XML-assigned ids.
  • These conflicting ids won't matter if queried correctly (keep reading).

When (and why) conflicting ids don't matter

  • findViewById(int) will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View it finds with a matching id.
  • As long as there are no code-assigned ids assigned before an XML-defined id in the hierarchy, findViewById(R.id.somename) will always return the XML-defined View so id'd.

Dynamically Creating Views and Assigning IDs

  • In layout XML, define an empty ViewGroup with id.
  • Such as a LinearLayout with android:id="@+id/placeholder".
  • Use code to populate the placeholder ViewGroup with Views.
  • If you need or want, assign any ids that are convenient to each view.
  • Query these child views using placeholder.findViewById(convenientInt);

  • API 17 introduced View.generateViewId() which allows you to generate a unique ID.

If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext() and be sure to set each reference to null in onDestroy. Apparently leaking the Activity (hanging onto it after is is destroyed) is wasteful.. :)

Reserve an XML android:id for use in code

API 17 introduced View.generateViewId() which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="reservedNamedId" type="id"/>
</resources>

Then once the ViewGroup or View has been created, you can attach the custom id

myViewGroup.setId(R.id.reservedNamedId);

Conflicting id example

For clarity by way of obfuscating example, lets examine what happens when there is an id conflict behind the scenes.

layout/mylayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/placeholder"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
</LinearLayout>

To simulate a conflict, lets say our latest build assigned R.id.placeholder(@+id/placeholder) an int value of 12..

Next, MyActivity.java defines some adds views programmatically (via code):

int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
    TextView tv = new TextView(this.getApplicationContext());
    // One new TextView will also be assigned an id==12:
    tv.setId(i);
    placeholder.addView(tv);
}

So placeholder and one of our new TextViews both have an id of 12! But this isn't really a problem if we query placeholder's child views:

// Will return a generated TextView:
 placeholder.findViewById(12);

// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12: 
Activity.this.findViewById(12);

*Not so bad

Internal and external fragmentation

Presumably from this site:

Internal Fragmentation Internal fragmentation occurs when the memory allocator leaves extra space empty inside of a block of memory that has been allocated for a client. This usually happens because the processor’s design stipulates that memory must be cut into blocks of certain sizes -- for example, blocks may be required to be evenly be divided by four, eight or 16 bytes. When this occurs, a client that needs 57 bytes of memory, for example, may be allocated a block that contains 60 bytes, or even 64. The extra bytes that the client doesn’t need go to waste, and over time these tiny chunks of unused memory can build up and create large quantities of memory that can’t be put to use by the allocator. Because all of these useless bytes are inside larger memory blocks, the fragmentation is considered internal.

External Fragmentation External fragmentation happens when the memory allocator leaves sections of unused memory blocks between portions of allocated memory. For example, if several memory blocks are allocated in a continuous line but one of the middle blocks in the line is freed (perhaps because the process that was using that block of memory stopped running), the free block is fragmented. The block is still available for use by the allocator later if there’s a need for memory that fits in that block, but the block is now unusable for larger memory needs. It cannot be lumped back in with the total free memory available to the system, as total memory must be contiguous for it to be useable for larger tasks. In this way, entire sections of free memory can end up isolated from the whole that are often too small for significant use, which creates an overall reduction of free memory that over time can lead to a lack of available memory for key tasks.

Difference between .on('click') vs .click()

As far as ilearned from internet and some friends .on() is used when you dynamically add elements. But when i used it in a simple login page where click event should send AJAX to node.js and at return append new elements it started to call multi-AJAX calls. When i changed it to click() everything went right. Actually i did not faced with this problem before.

Reversing a string in C

You can actually do something like this:

#include <string.h>

void reverse(char *);

int main(void){
 char name[7] = "walter";
 reverse(name);
 printf("%s", name);
}

void reverse(char *s) {
  size_t len = strlen(s);
  char *a = s;
  char *b = &s[(int)len - 1];
  char tmp;
  for (; a < b; ++a, --b) {
    tmp = *a;
    *a = *b;
    *b = tmp;
  }
}

Get key by value in dictionary

Sometimes int() may be needed:

titleDic = {'??????':1, '??????':2}

def categoryTitleForNumber(self, num):
    search_title = ''
    for title, titleNum in self.titleDic.items():
        if int(titleNum) == int(num):
            search_title = title
    return search_title

Styling a input type=number

UPDATE 17/03/2017

Original solution won't work anymore. The spinners are part of shadow dom. For now just to hide in chrome use:

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button {_x000D_
  -webkit-appearance: none;_x000D_
}
_x000D_
<input type="number" />
_x000D_
_x000D_
_x000D_

or to always show:

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<input type="number" />
_x000D_
_x000D_
_x000D_

You can try the following but keep in mind that works only for Chrome:

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button { _x000D_
    -webkit-appearance: none;_x000D_
    cursor:pointer;_x000D_
    display:block;_x000D_
    width:8px;_x000D_
    color: #333;_x000D_
    text-align:center;_x000D_
    position:relative;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:before,_x000D_
input[type=number]::-webkit-inner-spin-button:after {_x000D_
    content: "^";_x000D_
    position:absolute;_x000D_
    right: 0;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:before {_x000D_
    top:0px;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:after {_x000D_
    bottom:0px;_x000D_
    -webkit-transform: rotate(180deg);_x000D_
}
_x000D_
<input type="number" />
_x000D_
_x000D_
_x000D_

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

This cannot be emphasized enough:

Keys only make sense in the context of the surrounding array.

"For example, if you extract a ListItem component, you should keep the key on the <ListItem /> elements in the array rather than on the <li> element in the ListItem itself." -- https://reactjs.org/docs/lists-and-keys.html#extracting-components-with-keys

Using logging in multiple modules

Several of these answers suggest that at the top of a module you you do

import logging
logger = logging.getLogger(__name__)

It is my understanding that this is considered very bad practice. The reason is that the file config will disable all existing loggers by default. E.g.

#my_module
import logging

logger = logging.getLogger(__name__)

def foo():
    logger.info('Hi, foo')

class Bar(object):
    def bar(self):
        logger.info('Hi, bar')

And in your main module :

#main
import logging

# load my module - this now configures the logger
import my_module

# This will now disable the logger in my module by default, [see the docs][1] 
logging.config.fileConfig('logging.ini')

my_module.foo()
bar = my_module.Bar()
bar.bar()

Now the log specified in logging.ini will be empty, as the existing logger was disabled by fileconfig call.

While is is certainly possible to get around this (disable_existing_Loggers=False), realistically many clients of your library will not know about this behavior, and will not receive your logs. Make it easy for your clients by always calling logging.getLogger locally. Hat Tip : I learned about this behavior from Victor Lin's Website.

So good practice is instead to always call logging.getLogger locally. E.g.

#my_module
import logging

logger = logging.getLogger(__name__)

def foo():
    logging.getLogger(__name__).info('Hi, foo')

class Bar(object):
    def bar(self):
        logging.getLogger(__name__).info('Hi, bar')    

Also, if you use fileconfig in your main, set disable_existing_loggers=False, just in case your library designers use module level logger instances.

What is time_t ultimately a typedef to?

The answer is definitely implementation-specific. To find out definitively for your platform/compiler, just add this output somewhere in your code:

printf ("sizeof time_t is: %d\n", sizeof(time_t));

If the answer is 4 (32 bits) and your data is meant to go beyond 2038, then you have 25 years to migrate your code.

Your data will be fine if you store your data as a string, even if it's something simple like:

FILE *stream = [stream file pointer that you've opened correctly];
fprintf (stream, "%d\n", (int)time_t);

Then just read it back the same way (fread, fscanf, etc. into an int), and you have your epoch offset time. A similar workaround exists in .Net. I pass 64-bit epoch numbers between Win and Linux systems with no problem (over a communications channel). That brings up byte-ordering issues, but that's another subject.

To answer paxdiablo's query, I'd say that it printed "19100" because the program was written this way (and I admit I did this myself in the '80's):

time_t now;
struct tm local_date_time;
now = time(NULL);
// convert, then copy internal object to our object
memcpy (&local_date_time, localtime(&now), sizeof(local_date_time));
printf ("Year is: 19%02d\n", local_date_time.tm_year);

The printf statement prints the fixed string "Year is: 19" followed by a zero-padded string with the "years since 1900" (definition of tm->tm_year). In 2000, that value is 100, obviously. "%02d" pads with two zeros but does not truncate if longer than two digits.

The correct way is (change to last line only):

printf ("Year is: %d\n", local_date_time.tm_year + 1900);

New question: What's the rationale for that thinking?

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit.

I was getting this Error due to incorrect syntax using in the terminal. I was using java - version. But its actually is java -version. there is no space between - and version. you can also cross check by using java -help.

i hope this will help.

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

Bootstrap 3: How do you align column content to bottom of row

When working with bootsrap usually face three main problems:

  1. How to place the content of the column to the bottom?
  2. How to create a multi-row gallery of columns of equal height in one .row?
  3. How to center columns horizontally if their total width is less than 12 and the remaining width is odd?

To solve first two problems download this small plugin https://github.com/codekipple/conformity

The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns

Common code

<style>
    [class*=col-] {position: relative}
    .row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
    .row-centered {text-align:center}   
    .row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top} 
</style>

<script src="assets/conformity/conformity.js"></script>
<script>
    $(document).ready(function () {
        $('.row-conformity > [class*=col-]').conformity();
        $(window).on('resize', function() {
            $('.row-conformity > [class*=col-]').conformity();
        });
    });
</script>

1. Aligning content of the column to the bottom

<div class="row row-conformity">
    <div class="col-sm-3">
        I<br>create<br>highest<br>column
    </div>
    <div class="col-sm-3">
        <div class="to-bottom">
            I am on the bottom
        </div>
    </div>
</div>

2. Gallery of columns of equal height

<div class="row row-conformity">
    <div class="col-sm-4">We all have equal height</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
</div>

3. Horizontal alignment of columns to the center (less than 12 col units)

<div class="row row-centered">
    <div class="col-sm-3">...</div>
    <div class="col-sm-4">...</div>
</div>

All classes can work together

<div class="row row-conformity row-centered">
    ...
</div>

What is the main difference between PATCH and PUT request?

Here are the difference between POST, PUT and PATCH methods of a HTTP protocol.

POST

A HTTP.POST method always creates a new resource on the server. Its a non-idempotent request i.e. if user hits same requests 2 times it would create another new resource if there is no constraint.

http post method is like a INSERT query in SQL which always creates a new record in database.

Example: Use POST method to save new user, order etc where backend server decides the resource id for new resource.

PUT

In HTTP.PUT method the resource is first identified from the URL and if it exists then it is updated otherwise a new resource is created. When the target resource exists it overwrites that resource with a complete new body. That is HTTP.PUT method is used to CREATE or UPDATE a resource.

http put method is like a MERGE query in SQL which inserts or updates a record depending upon whether the given record exists.

PUT request is idempotent i.e. hitting the same requests twice would update the existing recording (No new record created). In PUT method the resource id is decided by the client and provided in the request url.

Example: Use PUT method to update existing user or order.

PATCH

A HTTP.PATCH method is used for partial modifications to a resource i.e. delta updates.

http patch method is like a UPDATE query in SQL which sets or updates selected columns only and not the whole row.

Example: You could use PATCH method to update order status.

PATCH /api/users/40450236/order/10234557

Request Body: {status: 'Delivered'}

How to print (using cout) a number in binary form?

Is there a standard way in C++ to show the binary representation in memory of a number [...]?

No. There's no std::bin, like std::hex or std::dec, but it's not hard to output a number binary yourself:

You output the left-most bit by masking all the others, left-shift, and repeat that for all the bits you have.

(The number of bits in a type is sizeof(T) * CHAR_BIT.)

django change default runserver port

This is an old post but for those who are interested:

If you want to change the default port number so when you run the "runserver" command you start with your preferred port do this:

  1. Find your python installation. (you can have multiple pythons installed and you can have your virtual environment version as well so make sure you find the right one)
  2. Inside the python folder locate the site-packages folder. Inside that you will find your django installation
  3. Open the django folder-> core -> management -> commands
  4. Inside the commands folder open up the runserver.py script with a text editor
  5. Find the DEFAULT_PORT field. it is equal to 8000 by default. Change it to whatever you like DEFAULT_PORT = "8080"
  6. Restart your server: python manage.py runserver and see that it uses your set port number

It works with python 2.7 but it should work with newer versions of python as well. Good luck

Creating a DateTime in a specific Time Zone in c#

Jon's answer talks about TimeZone, but I'd suggest using TimeZoneInfo instead.

Personally I like keeping things in UTC where possible (at least for the past; storing UTC for the future has potential issues), so I'd suggest a structure like this:

public struct DateTimeWithZone
{
    private readonly DateTime utcDateTime;
    private readonly TimeZoneInfo timeZone;

    public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
    {
        var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
        utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone); 
        this.timeZone = timeZone;
    }

    public DateTime UniversalTime { get { return utcDateTime; } }

    public TimeZoneInfo TimeZone { get { return timeZone; } }

    public DateTime LocalTime
    { 
        get 
        { 
            return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); 
        }
    }        
}

You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.

Python 3 - Encode/Decode vs Bytes/Str

To add to Lennart Regebro's answer There is even the third way that can be used:

encoded3 = str.encode(original, 'utf-8')
print(encoded3)

Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.


A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.

Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.

In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".

The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.

How do I merge dictionaries together in Python?

You can use the .update() method if you don't need the original d2 any more:

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

E.g.:

>>> d1 = {'a': 1, 'b': 2} 
>>> d2 = {'b': 1, 'c': 3}
>>> d2.update(d1)
>>> d2
{'a': 1, 'c': 3, 'b': 2}

Update:

Of course you can copy the dictionary first in order to create a new merged one. This might or might not be necessary. In case you have compound objects (objects that contain other objects, like lists or class instances) in your dictionary, copy.deepcopy should also be considered.

How to create multidimensional array

Create uninitialized multidimensional array:

function MultiArray(a) {
  if (a.length < 1) throw "Invalid array dimension";
  if (a.length == 1) return Array(a[0]);
  return [...Array(a[0])].map(() => MultiArray(a.slice(1)));
}

Create initialized multidimensional array:

function MultiArrayInit(a, init) {
  if (a.length < 1) throw "Invalid array dimension";
  if (a.length == 1) return Array(a[0]).fill(init);
  return [...Array(a[0])].map(() => MultiArrayInit(a.slice(1), init));
}

Usage:

MultiArray([3,4,5]);  // -> Creates an array of [3][4][5] of empty cells

MultiArrayInit([3,4,5], 1);  // -> Creates an array of [3][4][5] of 1s

Ineligible Devices section appeared in Xcode 6.x.x

My answer, perhaps listed already but i did not notice, was simple: I deleted the app in question from the target itself, then fired up Xcode and the target was then available. And yes, i tried most of the other suggestions, and was resorting to activating the target from the Product menu, but that was getting tedious.

How to change visibility of layout programmatically

You can change layout visibility just in the same way as for regular view. Use setVisibility(View.GONE) etc. All layouts are just Views, they have View as their parent.

How can I access getSupportFragmentManager() in a fragment?

do this in your fragment

getActivity().getSupportFragmentManager()

Escaping single quotes in JavaScript string for JavaScript evaluation

I agree that this var formattedString = string.replace(/'/g, "\\'"); works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.

The solution that worked for me is that you need to put three \ and escape the double quotes. "var string = \"l'avancement\"; var formattedString = string.replace(/'/g, \"\\\'\");"

I answer that question since I had trouble finding that three \ was the work around.

Text Editor For Linux (Besides Vi)?

I just thought I would recommend Ninja IDE, open source and all.. I use it for all my Python development now days when I got a GUI to work with and looks the same when I am on my Windows and Linux machines.

Ninja IDE

How to get POSTed JSON in Flask?

Assuming you've posted valid JSON with the application/json content type, request.json will have the parsed JSON data.

from flask import Flask, request, jsonify

app = Flask(__name__)


@app.route('/echo', methods=['POST'])
def hello():
   return jsonify(request.json)

ImportError: No module named tensorflow

For me, if I did

python3 -m pip install tensorflow

then I got the error the OP reports when using a 3rd party library calling tensorflow.

However, when I substituted either tensorflow-cpu or tensorflow-gpu (depending upon which one is appropriate for you) then the code was suddenly able to find tensorflow.

DateTime.MinValue and SqlDateTime overflow

From MSDN:

Date and time data from January 1, 1753, to December 31, 9999, with an accuracy of one three-hundredth second, or 3.33 milliseconds. Values are rounded to increments of .000, .003, or .007 milliseconds. Stored as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system's reference date. Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight. Seconds have a valid range of 0–59.

SQL uses a different system than C# for DateTime values.

You can use your MinValue as a sentinel value - and if it is MinValue - pass null into your object (and store the date as nullable in the DB).

if(date == dateTime.Minvalue)
    objinfo.BirthDate = null;

Val and Var in Kotlin

Both, val and var can be used for declaring variables (local and class properties).

Local variables:

  1. val declares read-only variables that can only be assigned once, but cannot be reassigned.

Example:

val readonlyString = “hello”
readonlyString = “c u” // Not allowed for `val`
  1. var declares reassignable variables as you know them from Java (the keyword will be introduced in Java 10, “local variable type inference”).

Example:

var reasignableString = “hello”
reasignableString = “c u” // OK

It is always preferable to use val. Try to avoid var as often as possible!

Class properties:

Both keywords are also used in order to define properties inside classes. As an example, have a look at the following data class:

data class Person (val name: String, var age: Int)

The Person contains two fields, one of which is readonly (name). The age, on the other hand, may be reassigned after class instantiation, via the provided setter. Note that name won’t have a corresponding setter method.

SQL grouping by all the columns

Here is my suggestion:

DECLARE @FIELDS VARCHAR(MAX), @NUM INT

--DROP TABLE #FIELD_LIST

SET @NUM = 1
SET @FIELDS = ''

SELECT 
'SEQ' = IDENTITY(int,1,1) ,
COLUMN_NAME
INTO #FIELD_LIST
FROM Req.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'new340B'

WHILE @NUM <= (SELECT COUNT(*) FROM #FIELD_LIST)
BEGIN
SET @FIELDS = @FIELDS + ',' + (SELECT COLUMN_NAME FROM #FIELD_LIST WHERE SEQ = @NUM)
SET @NUM = @NUM + 1
END

SET @FIELDS = RIGHT(@FIELDS,LEN(@FIELDS)-1)

EXEC('SELECT ' + @FIELDS + ', COUNT(*) AS QTY FROM [Req].[dbo].[new340B] GROUP BY ' + @FIELDS + ' HAVING COUNT(*) > 1  ') 

Java: Reading a file into an array

Here is some example code to help you get started:

package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}

And an example unit test:

package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Hope this helps.

Java URLConnection Timeout

Are you on Windows? The underlying socket implementation on Windows seems not to support the SO_TIMEOUT option very well. See also this answer: setSoTimeout on a client socket doesn't affect the socket

deleting rows in numpy array

The simplest way to delete rows and columns from arrays is the numpy.delete method.

Suppose I have the following array x:

x = array([[1,2,3],
        [4,5,6],
        [7,8,9]])

To delete the first row, do this:

x = numpy.delete(x, (0), axis=0)

To delete the third column, do this:

x = numpy.delete(x,(2), axis=1)

So you could find the indices of the rows which have a 0 in them, put them in a list or a tuple and pass this as the second argument of the function.

how to convert integer to string?

If you really want to use String:

NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];

But I would recommend using NSNumber:

NSNumber *number = [[NSNumber alloc] initWithInt:123];

Then just add it to the array.

[array addObject:number];

Don't forget to release it after that, since you created it above.

[number release];

JQuery show and hide div on mouse click (animate)

That .toggle() method was removed from jQuery in version 1.9. You can do this instead:

$(document).ready(function() {
    $('#showmenu').click(function() {
            $('.menu').slideToggle("fast");
    });
});

Demo: http://jsfiddle.net/APA2S/1/

...but as with the code in your question that would slide up or down. To slide left or right you can do the following:

$(document).ready(function() {
    $('#showmenu').click(function() {
         $('.menu').toggle("slide");
    });
});

Demo: http://jsfiddle.net/APA2S/2/

Noting that this requires jQuery-UI's slide effect, but you added that tag to your question so I assume that is OK.

Binding ComboBox SelectedItem using MVVM

I had a similar problem where the SelectedItem-binding did not update when I selected something in the combobox. My problem was that I had to set UpdateSourceTrigger=PropertyChanged for the binding.

<ComboBox ItemsSource="{Binding SalesPeriods}" 
          SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

Try this:

Xvfb :21 -screen 0 1024x768x24 +extension RANDR &
Xvfb --help

+extension name        Enable extension
-extension name        Disable extension

How to suspend/resume a process in Windows?

PsSuspend command line utility from SysInternals suite. It suspends / resumes a process by its id.

Editing specific line in text file in Python

I have been practising working on files this evening and realised that I can build on Jochen's answer to provide greater functionality for repeated/multiple use. Unfortunately my answer does not address issue of dealing with large files but does make life easier in smaller files.

with open('filetochange.txt', 'r+') as foo:
    data = foo.readlines()                  #reads file as list
    pos = int(input("Which position in list to edit? "))-1  #list position to edit
    data.insert(pos, "more foo"+"\n")           #inserts before item to edit
    x = data[pos+1]
    data.remove(x)                      #removes item to edit
    foo.seek(0)                     #seeks beginning of file
    for i in data:
        i.strip()                   #strips "\n" from list items
        foo.write(str(i))

bootstrap responsive table content wrapping

just simply use as below and it will word wrap any long text within a table . No need to anything else

<td style="word-wrap: break-word;min-width: 160px;max-width: 160px;">long long comments</td>

How to output to the console and file?

I came up with this [untested]

import sys

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() # If you want the output to be visible immediately
    def flush(self) :
        for f in self.files:
            f.flush()

f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test"  # This will go to stdout and the file out.txt

#use the original
sys.stdout = original
print "This won't appear on file"  # Only on stdout
f.close()

print>>xyz in python will expect a write() function in xyz. You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without >>xyz.

Floating point comparison functions for C#

Further to Andrew Wang's answer: if the BitConverter method is too slow but you cannot use unsafe code in your project, this struct is ~6x quicker than BitConverter:

[StructLayout(LayoutKind.Explicit)]
public struct FloatToIntSafeBitConverter
{
    public static int Convert(float value)
    {
        return new FloatToIntSafeBitConverter(value).IntValue;
    }

    public FloatToIntSafeBitConverter(float floatValue): this()
    {
        FloatValue = floatValue;
    }

    [FieldOffset(0)]
    public readonly int IntValue;

    [FieldOffset(0)]
    public readonly float FloatValue;
}

(Incidentally, I tried using the accepted solution but it (well my conversion at least) failed some of the unit tests also mentioned in the answer. e.g. assertTrue(nearlyEqual(Float.MIN_VALUE, -Float.MIN_VALUE)); )

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

What is the best way to create and populate a numbers table?

This is a repackaging of the accepted answer - but in a way that lets you compare them all to each other for yourself - the top 3 algorithms are compared (and comments explain why other methods are excluded) and you can run against your own setup to see how they each perform with the size of sequence that you desire.

SET NOCOUNT ON;

--
-- Set the count of numbers that you want in your sequence ...
--
DECLARE @NumberOfNumbers int = 10000000;
--
--  Some notes on choosing a useful length for your sequence ...
--      For a sequence of  100 numbers -- winner depends on preference of min/max/avg runtime ... (I prefer PhilKelley algo here - edit the algo so RowSet2 is max RowSet CTE)
--      For a sequence of   1k numbers -- winner depends on preference of min/max/avg runtime ... (Sadly PhilKelley algo is generally lowest ranked in this bucket, but could be tweaked to perform better)
--      For a sequence of  10k numbers -- a clear winner emerges for this bucket
--      For a sequence of 100k numbers -- do not test any looping methods at this size or above ...
--                                        the previous winner fails, a different method is need to guarantee the full sequence desired
--      For a sequence of  1MM numbers -- the statistics aren't changing much between the algorithms - choose one based on your own goals or tweaks
--      For a sequence of 10MM numbers -- only one of the methods yields the desired sequence, and the numbers are much closer than for smaller sequences

DECLARE @TestIteration int = 0;
DECLARE @MaxIterations int = 10;
DECLARE @MethodName varchar(128);

-- SQL SERVER 2017 Syntax/Support needed
DROP TABLE IF EXISTS #TimingTest
CREATE TABLE #TimingTest (MethodName varchar(128), TestIteration int, StartDate DateTime2, EndDate DateTime2, ElapsedTime decimal(38,0), ItemCount decimal(38,0), MaxNumber decimal(38,0), MinNumber decimal(38,0))

--
--  Conduct the test ...
--
WHILE @TestIteration < @MaxIterations
BEGIN
    -- Be sure that the test moves forward
    SET @TestIteration += 1;

/*  -- This method has been removed, as it is BY FAR, the slowest method
    -- This test shows that, looping should be avoided, likely at all costs, if one places a value / premium on speed of execution ...

    --
    -- METHOD - Fast looping
    --

    -- Prep for the test
    DROP TABLE IF EXISTS [Numbers].[Test];
    CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);

    -- Method information
    SET @MethodName = 'FastLoop';

    -- Record the start of the test
    INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
    SELECT @MethodName, @TestIteration, GETDATE()

    -- Run the algorithm
    DECLARE @i INT = 1;
    WHILE @i <= @NumberOfNumbers
    BEGIN
        INSERT INTO [Numbers].[Test](Number) VALUES (@i);
        SELECT @i = @i + 1;
    END;

    ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)

    -- Record the end of the test
    UPDATE tt
        SET 
            EndDate = GETDATE()
    FROM #TimingTest tt
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    -- And the stats about the numbers in the sequence
    UPDATE tt
        SET 
            ItemCount = results.ItemCount,
            MaxNumber = results.MaxNumber,
            MinNumber = results.MinNumber
    FROM #TimingTest tt
    CROSS JOIN (
        SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
    ) results
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration
*/

/*  -- This method requires GO statements, which would break the script, also - this answer does not appear to be the fastest *AND* seems to perform "magic"
    --
    -- METHOD - "Semi-Looping"
    --

    -- Prep for the test
    DROP TABLE IF EXISTS [Numbers].[Test];
    CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);

    -- Method information
    SET @MethodName = 'SemiLoop';

    -- Record the start of the test
    INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
    SELECT @MethodName, @TestIteration, GETDATE()

    -- Run the algorithm 
    INSERT [Numbers].[Test] values (1);
--    GO --required

    INSERT [Numbers].[Test] SELECT Number + (SELECT COUNT(*) FROM [Numbers].[Test]) FROM [Numbers].[Test]
--    GO 14 --will create 16384 total rows

    ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)

    -- Record the end of the test
    UPDATE tt
        SET 
            EndDate = GETDATE()
    FROM #TimingTest tt
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    -- And the stats about the numbers in the sequence
    UPDATE tt
        SET 
            ItemCount = results.ItemCount,
            MaxNumber = results.MaxNumber,
            MinNumber = results.MinNumber
    FROM #TimingTest tt
    CROSS JOIN (
        SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
    ) results
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration
*/
    --
    -- METHOD - Philip Kelley's algo 
    --          (needs tweaking to match the desired length of sequence in order to optimize its performance, relies more on the coder to properly tweak the algorithm)
    --

    -- Prep for the test
    DROP TABLE IF EXISTS [Numbers].[Test];
    CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);

    -- Method information
    SET @MethodName = 'PhilKelley';

    -- Record the start of the test
    INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
    SELECT @MethodName, @TestIteration, GETDATE()

    -- Run the algorithm
    ; WITH
    RowSet0 as (select 1 as Item union all select 1),              --          2 rows   -- We only have to name the column in the first select, the second/union select inherits the column name
    RowSet1 as (select 1 as Item from RowSet0 as A, RowSet0 as B), --          4 rows
    RowSet2 as (select 1 as Item from RowSet1 as A, RowSet1 as B), --         16 rows
    RowSet3 as (select 1 as Item from RowSet2 as A, RowSet2 as B), --        256 rows
    RowSet4 as (select 1 as Item from RowSet3 as A, RowSet3 as B), --      65536 rows (65k)
    RowSet5 as (select 1 as Item from RowSet4 as A, RowSet4 as B), -- 4294967296 rows (4BB)
    -- Add more RowSetX to get higher and higher numbers of rows    
    -- Each successive RowSetX results in squaring the previously available number of rows
    Tally   as (select row_number() over (order by Item) as Number from RowSet5) -- This is what gives us the sequence of integers, always select from the terminal CTE expression
    -- Note: testing of this specific use case has shown that making Tally as a sub-query instead of a terminal CTE expression is slower (always) - be sure to follow this pattern closely for max performance
    INSERT INTO [Numbers].[Test] (Number)
    SELECT o.Number
    FROM Tally o
    WHERE o.Number <= @NumberOfNumbers

    ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)

    -- Record the end of the test
    UPDATE tt
        SET 
            EndDate = GETDATE()
    FROM #TimingTest tt
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    -- And the stats about the numbers in the sequence
    UPDATE tt
        SET 
            ItemCount = results.ItemCount,
            MaxNumber = results.MaxNumber,
            MinNumber = results.MinNumber
    FROM #TimingTest tt
    CROSS JOIN (
        SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
    ) results
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    --
    -- METHOD - Mladen Prajdic answer
    --

    -- Prep for the test
    DROP TABLE IF EXISTS [Numbers].[Test];
    CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);

    -- Method information
    SET @MethodName = 'MladenPrajdic';

    -- Record the start of the test
    INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
    SELECT @MethodName, @TestIteration, GETDATE()

    -- Run the algorithm
    INSERT INTO [Numbers].[Test](Number)
    SELECT TOP (@NumberOfNumbers) row_number() over(order by t1.number) as N
    FROM master..spt_values t1 
    CROSS JOIN master..spt_values t2

    ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)

    -- Record the end of the test
    UPDATE tt
        SET 
            EndDate = GETDATE()
    FROM #TimingTest tt
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    -- And the stats about the numbers in the sequence
    UPDATE tt
        SET 
            ItemCount = results.ItemCount,
            MaxNumber = results.MaxNumber,
            MinNumber = results.MinNumber
    FROM #TimingTest tt
    CROSS JOIN (
        SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
    ) results
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    --
    -- METHOD - Single INSERT
    -- 

    -- Prep for the test
    DROP TABLE IF EXISTS [Numbers].[Test];
    -- The Table creation is part of this algorithm ...

    -- Method information
    SET @MethodName = 'SingleInsert';

    -- Record the start of the test
    INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
    SELECT @MethodName, @TestIteration, GETDATE()

    -- Run the algorithm
    SELECT TOP (@NumberOfNumbers) IDENTITY(int,1,1) AS Number
    INTO [Numbers].[Test]
    FROM sys.objects s1       -- use sys.columns if you don't get enough rows returned to generate all the numbers you need
    CROSS JOIN sys.objects s2 -- use sys.columns if you don't get enough rows returned to generate all the numbers you need

    ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)

    -- Record the end of the test
    UPDATE tt
        SET 
            EndDate = GETDATE()
    FROM #TimingTest tt
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    -- And the stats about the numbers in the sequence
    UPDATE tt
        SET 
            ItemCount = results.ItemCount,
            MaxNumber = results.MaxNumber,
            MinNumber = results.MinNumber
    FROM #TimingTest tt
    CROSS JOIN (
        SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
    ) results
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration
END

-- Calculate the timespan for each of the runs
UPDATE tt
    SET
        ElapsedTime = DATEDIFF(MICROSECOND, StartDate, EndDate)
FROM #TimingTest tt

--
-- Report the results ...
--
SELECT 
    MethodName, AVG(ElapsedTime) / AVG(ItemCount) as TimePerRecord, CAST(AVG(ItemCount) as bigint) as SequenceLength,
    MAX(ElapsedTime) as MaxTime, MIN(ElapsedTime) as MinTime,
    MAX(MaxNumber) as MaxNumber, MIN(MinNumber) as MinNumber
FROM #TimingTest tt
GROUP by tt.MethodName
ORDER BY TimePerRecord ASC, MaxTime ASC, MinTime ASC

Django set field value after a form is initialized

If you've already initialized the form, you can use the initial property of the field. For example,

form = CustomForm()
form.fields["Email"].initial = GetEmailString()

docker unauthorized: authentication required - upon push with successful login

You'll need to log in to Docker.

Step 1: log in to docker hub

Based on @KaraPirinc's comment, in Docker version 17 in order to log in:

docker login -u username --password-stdin

Then enter your password when asked.

Step 2: create a repository in the docker hub.

Let's say "mysqlserver:sql".

docker push <user username>/mysqlserver:sql

CSS fixed width in a span

Using HTML 5.0, it is possible to fix width of text block using <span> or <div>.

enter image description here

For <span>, what is important is to add following CCS line

display: inline-block;

For your empty <span> what is important is to add &nbsp; space.

My code is following

_x000D_
_x000D_
body_x000D_
 {_x000D_
 font-family: Arial;_x000D_
 font-size:20px;_x000D_
 }_x000D_
_x000D_
div_x000D_
 {_x000D_
 width:200px;_x000D_
 font-size:80px;_x000D_
 background-color: lime;_x000D_
 }_x000D_
div span_x000D_
 {_x000D_
 display:block;_x000D_
 width:200px;_x000D_
 background-color: lime;_x000D_
 }_x000D_
_x000D_
ul li span_x000D_
 {_x000D_
 display: inline-block;_x000D_
 width: 80px;_x000D_
 background-color: yellow;_x000D_
 }_x000D_
span.tab_x000D_
 {_x000D_
 display: inline-block;_x000D_
 width: 80px;_x000D_
 background-color: yellow;_x000D_
 }
_x000D_
&lt;DIV&gt;_x000D_
_x000D_
<div class='test'>ABCDEF</div>_x000D_
_x000D_
&lt;SPAN&gt;_x000D_
_x000D_
<div>_x000D_
    <span class='test'>ABCDEF</span>_x000D_
</div_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
  <li><span class='tab'>&nbsp;</span> The lazy dog.</li>_x000D_
  <li><span class='tab'>AND</span> The lazy cat.</li>_x000D_
  <li><span class='tab'>OR</span> The active goldfish.</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

PS: I have defined tab class because ul li span CSS selector is not working on my PC !

How to set the JSTL variable value in javascript?

one more approach to use.

first, define the following somewhere on the page:

<div id="valueHolderId">${someValue}</div>

then in JS, just do something similar to

var someValue = $('#valueHolderId').html();

it works great for the cases when all scripts are inside .js files and obviously there is no jstl available

Running .sh scripts in Git Bash

If you wish to execute a script file from the git bash prompt on Windows, just precede the script file with sh

sh my_awesome_script.sh

Take a screenshot via a Python script on Linux

It's an old question. I would like to answer it using new tools.

Works with python 3 (should work with python 2, but I haven't test it) and PyQt5.

Minimal working example. Copy it to the python shell and get the result.

from PyQt5.QtWidgets import QApplication
app = QApplication([])
screen = app.primaryScreen()
screenshot = screen.grabWindow(QApplication.desktop().winId())
screenshot.save('/tmp/screenshot.png')

Pandas DataFrame: replace all values in a column, based on condition

We can update the First Season column in df with the following syntax:

df['First Season'] = expression_for_new_values

To map the values in First Season we can use pandas‘ .map() method with the below syntax:

data_frame(['column']).map({'initial_value_1':'updated_value_1','initial_value_2':'updated_value_2'})

CSS: create white glow around image

Use simple CSS3 (not supported in IE<9)

img
{
    box-shadow: 0px 0px 5px #fff;
}

This will put a white glow around every image in your document, use more specific selectors to choose which images you'd like the glow around. You can change the color of course :)

If you're worried about the users that don't have the latest versions of their browsers, use this:

img
{
-moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
box-shadow: 0px 0px 5px #fff;
}

For IE you can use a glow filter (not sure which browsers support it)

img
{
    filter:progid:DXImageTransform.Microsoft.Glow(Color=white,Strength=5);
}

Play with the settings to see what suits you :)

How do I add a newline using printf?

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget

How to change line width in IntelliJ (from 120 character)

IntelliJ IDEA 2018

File > Settings... > Editor > Code Style > Hard wrap at

Code Style > Hard wrap at

IntelliJ IDEA 2016 & 2017

File > Settings... > Editor > Code Style > Right margin (columns):

File > Settings

Editor > Code Style > Right margin

Spring Boot - inject map from application.yml

You can make it even simplier, if you want to avoid extra structures.

service:
  mappings:
    key1: value1
    key2: value2
@Configuration
@EnableConfigurationProperties
public class ServiceConfigurationProperties {

  @Bean
  @ConfigurationProperties(prefix = "service.mappings")
  public Map<String, String> serviceMappings() {
    return new HashMap<>();
  }

}

And then use it as usual, for example with a constructor:

public class Foo {

  private final Map<String, String> serviceMappings;

  public Foo(Map<String, String> serviceMappings) {
    this.serviceMappings = serviceMappings;
  }

}

How to set an button align-right with Bootstrap?

<div class="container">
    <div class="btn-block pull-right">
        <a href="#" class="btn btn-primary pull-right">Search</a>
        <a href="#" class="btn btn-primary pull-right">Apple</a>
        <a href="#" class="btn btn-primary pull-right">Sony</a>
    </div>
</div>

Android: disabling highlight on listView click

RoflcoptrException's answer should do the trick,but for some reason it did not work for me, So I am posting the solution which worked for me, hope it helps someone

<ListView 
android:listSelector="@android:color/transparent" 
android:cacheColorHint="@android:color/transparent"
/>

Upgrading Node.js to latest version

1 Minute Solution Without using sudo:

The current stable "LTS" version of node is 14.15.5 (2021-01-17) see: nodejs.org for latest.

Step 1 - Get NVM (Node Version Manger)

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash

If you're curious about the installation command read the source code
... its been reviewed by several node.js security experts

Step 2 - Install the version of node.js you need

Once you've got NVM you can install a specific version of Node.js using the nvm command:

nvm install v14.15.5

Note: you may need to close & re-open your terminal window for nvm command to be available.

You should expect to see something like this in your terminal:

Now using node v14.15.4

Step 3 - Enjoy the rest of your day!

Yes, it's that easy and didn't require sudo!
Now please Upvote this (so others can avoid sudo-installing things!)
and have a lovely day writing node.js code!

Microsoft Windows User? Use: https://github.com/coreybutler/nvm-windows

 tl;dr

Review of the node mailing list indicates that using NVM (Node Version Manager) is the preferred way to manage your nodejs versioning/upgrading. see: github.com/nvm-sh/nvm

NVM is considered "better" than N because the verbose commands mean is much easier to keep track of what you are doing in your Terminal/SSH Log. Its also faster, saves kittens by not requiring sudo and is used by the team at NPM the node.js security experts!

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

Add the following dependency in your pom.xml file and if you are using IntelliJ then add the same jars to WEB-INF->lib folder.... path is Project Structure -> Atrifacts -> Select jar from Available Elements pane and double click. It will add to respective folder

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>3.0.1.RELEASE</version>
</dependency>

Check if decimal value is null

Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).

Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue

How can I post an array of string to ASP.NET MVC Controller without a form?

Don't post the data as an array. To bind to a list, the key/value pairs should be submitted with the same value for each key.

You should not need a form to do this. You just need a list of key/value pairs, which you can include in the call to $.post.

How to make the checkbox unchecked by default always

This is browser specific behavior and is a way for making filling up forms more convenient to users (like reloading the page when an error has been encountered and not losing what they just typed). So there is no sure way to disable this across browsers short of setting the default values on page load using javascript.

Firefox though seems to disable this feature when you specify the header:

Cache-Control: no-store

See this question.

How to concatenate two strings in C++?

strcat(destination,source) can be used to concatenate two strings in c++.

To have a deep understanding you can lookup in the following link-

http://www.cplusplus.com/reference/cstring/strcat/

How to access Anaconda command prompt in Windows 10 (64-bit)

To create Anaconda Prompt using Command Prompt, just create a shortcut file of Command Prompt and modify the shortcut target to:

%windir%\System32\cmd.exe "/K" <Anaconda Location>\anaconda3\Scripts\activate.bat

Example:

%windir%\system32\cmd.exe "/K" C:\Users\user_1\AppData\Local\Continuum\anaconda3\Scripts\activate.bat

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

If you're in a Browser-Only environment, use SridharR's solution.

If you're in a Node/CommonJS + Browser environment (e.g. electron, node-webkit, etc..); the reason for this error is that jQuery's export logic first checks for module, not window:

if (typeof module === "object" && typeof module.exports === "object") {
    // CommonJS/Node
} else {
    // window
}

Note that it exports itself via module.exports in this case; so jQuery and $ are not assigned to window.

So to resolve this, instead of <script src="path/to/jquery.js"></script>;

Simply assign it yourself by a require statement:

<script>
    window.jQuery = window.$ = require('jquery');
</script>

NOTE: If your electron app does not need nodeIntegration, set it to false so you won't need this workaround.

Remove Blank option from Select Option with AngularJS

Finally it worked for me.

<select ng-init="mybasketModel = basket[0]" ng-model="mybasketModel">
        <option ng-repeat="item in basket" ng-selected="$first">{{item}}</option>
</select>


How to resolve 'unrecognized selector sent to instance'?

A lot of people have given some very technical answers for this and similar questions, but I think it's simpler than that. Sometimes if you're not paying attention a selector that you don't intend to use can be attached to something in the interface. You might be getting this error because the selector's there but you haven't written any code for it.

The easiest way to double-check that this is not the case is to control-click the item so you can see all of the selectors that are associated with it. If there's anything in there that you don't want to be, get rid of it! Hope this helps...

MySQL Cannot Add Foreign Key Constraint

I got the same error. The cause in my case was:

  1. I created a backup of a database via phpmyadmin by copying the whole database.
  2. I created a new db with the same name the old db had und selected it.
  3. I started an SQL script to create updated tables and data.
  4. I got the error. Also when I disabled foreign_key_checks. Altough the database was completely empty.

The cause was: Since i used phpmyadmin to create some foreign keys in the renamed database - the foreign keys where created with a database name prefix but the database name prefix was not updated. So there were still references in the backup-db pointing to the newly created db.

DLL Load Library - Error Code 126

Windows dll error 126 can have many root causes. The most useful methods I have found to debug this are:

  1. Use dependency walker to look for any obvious problems (which you have already done)
  2. Use the sysinternals utility Process Monitor http://technet.microsoft.com/en-us/sysinternals/bb896645 from Microsoft to trace all file access while your dll is trying to load. With this utility, you will see everything that that dll is trying to pull in and usually the problem can be determined from there.

Why is conversion from string constant to 'char*' valid in C but invalid in C++

It's valid in C for historical reasons. C traditionally specified that the type of a string literal was char * rather than const char *, although it qualified it by saying that you're not actually allowed to modify it.

When you use a cast, you're essentially telling the compiler that you know better than the default type matching rules, and it makes the assignment OK.

CSS: How to position two elements on top of each other, without specifying a height?

Great answer, "mu is too short". I was seeking the exact same thing, and after reading your post I found a solution that fitted my problem.

I was having two elements of the exact same size and wanted to stack them. As each have same size, what I could do was to make

position: absolute;
top: 0px;
left: 0px;

on only the last element. This way the first element is inserted correctly, "pushing" the parents height, and the second element is placed on top.

Hopes this helps other people trying to stacking 2+ elements with same (unknown) height.

How to use JavaScript variables in jQuery selectors?

var name = this.name;
$("input[name=" + name + "]").hide();

OR you can do something like this.

var id = this.id;
$('#' + id).hide();

OR you can give some effect also.

$("#" + this.id).slideUp();

If you want to remove the entire element permanently form the page.

$("#" + this.id).remove();

You can also use it in this also.

$("#" + this.id).slideUp('slow', function (){
    $("#" + this.id).remove();
});

Does Python have a ternary conditional operator?

Unfortunately, the

(falseValue, trueValue)[test]

solution doesn't have short-circuit behaviour; thus both falseValue and trueValue are evaluated regardless of the condition. This could be suboptimal or even buggy (i.e. both trueValue and falseValue could be methods and have side-effects).

One solution to this would be

(lambda: falseValue, lambda: trueValue)[test]()

(execution delayed until the winner is known ;)), but it introduces inconsistency between callable and non-callable objects. In addition, it doesn't solve the case when using properties.

And so the story goes - choosing between 3 mentioned solutions is a trade-off between having the short-circuit feature, using at least ?ython 2.5 (IMHO not a problem anymore) and not being prone to "trueValue-evaluates-to-false" errors.

How to find the highest value of a column in a data frame in R?

Similar to colMeans, colSums, etc, you could write a column maximum function, colMax, and a column sort function, colSort.

colMax <- function(data) sapply(data, max, na.rm = TRUE)
colSort <- function(data, ...) sapply(data, sort, ...)

I use ... in the second function in hopes of sparking your intrigue.

Get your data:

dat <- read.table(h=T, text = "Ozone Solar.R Wind Temp Month Day
1     41     190  7.4   67     5   1
2     36     118  8.0   72     5   2
3     12     149 12.6   74     5   3
4     18     313 11.5   62     5   4
5     NA      NA 14.3   56     5   5
6     28      NA 14.9   66     5   6
7     23     299  8.6   65     5   7
8     19      99 13.8   59     5   8
9      8      19 20.1   61     5   9")

Use colMax function on sample data:

colMax(dat)
#  Ozone Solar.R    Wind    Temp   Month     Day 
#   41.0   313.0    20.1    74.0     5.0     9.0

To do the sorting on a single column,

sort(dat$Solar.R, decreasing = TRUE)
# [1] 313 299 190 149 118  99  19

and over all columns use our colSort function,

colSort(dat, decreasing = TRUE) ## compare with '...' above

How do I dynamically change the content in an iframe using jquery?

If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src attribute.

 $("#myiframe").attr("src", "newwebpage.html");

CSS background opacity with rgba not working in IE 8

the transparent png image will not work in IE 6-, alternatives are:

with CSS:

.transparent {

    /* works for IE 5+. */
    filter:alpha(opacity=30); 

    /* works for IE 8. */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";

    /* works for old school versions of the Mozilla browsers like Netscape Navigator. */
    -moz-opacity:0.3; 

    /* This is for old versions of Safari (1.x) with KHTML rendering engine */
    -khtml-opacity: 0.3; 

    /* This is the "most important" one because it's the current standard in CSS. This will work in most versions of Firefox, Safari, and Opera. */  
    opacity: 0.3; 
}

or just do it with jQuery:

// a crossbrowser solution
$(document).ready(function(){ 
    $(".transparent").css('opacity','.3');
});

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

^[a-zA-Z] means any a-z or A-Z at the start of a line

[^a-zA-Z] means any character that IS NOT a-z OR A-Z

How to use youtube-dl from a python program?

For simple code, may be i think

import os
os.system('youtube-dl [OPTIONS] URL [URL...]')

Above is just running command line inside python.

Other is mentioned in the documentation Using youtube-dl on python Here is the way

from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

This \ means "the root directory of the current drive". In your example it means the "test" folder in the current drive's root directory. So, this can be equal to "c:\test".

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

How to use 'find' to search for files created on a specific date?

You could do this:

find ./ -type f -ls |grep '10 Sep'

Example:

[root@pbx etc]# find /var/ -type f -ls | grep "Dec 24"
791235    4 -rw-r--r--   1 root     root           29 Dec 24 03:24 /var/lib/prelink/full
798227  288 -rw-r--r--   1 root     root       292323 Dec 24 23:53 /var/log/sa/sar24
797244  320 -rw-r--r--   1 root     root       321300 Dec 24 23:50 /var/log/sa/sa24

Django - Did you forget to register or load this tag?

You need to change:

{% endblock content %}

to

{% endblock %}

Can you force a React component to rerender without calling setState?

forceUpdate(); method will work but it is advisable to use setState();

Editing an item in a list<T>

  1. You can use the FindIndex() method to find the index of item.
  2. Create a new list item.
  3. Override indexed item with the new item.

List<Class1> list = new List<Class1>();

int index = list.FindIndex(item => item.Number == textBox6.Text);

Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";

list[index] = newItem;

Loading local JSON file

What worked for me is the following:

Input:

http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json

Javascript Code:

<html>
<head>

<style>
pre {}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>

<script>
function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function gethtmlcontents(){
    path = window.location.search.substr(1)
    var rawFile = new XMLHttpRequest();
    var my_file = rawFile.open("GET", path, true)  // Synchronous File Read
    //alert('Starting to read text')
    rawFile.onreadystatechange = function ()
    {
        //alert("I am here");
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                //alert(allText)
                var json_format = JSON.stringify(JSON.parse(allText), null, 8)
                //output(json_format)
                output(syntaxHighlight(json_format));
            }
        }
    }
    rawFile.send(null);
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

gethtmlcontents();
</script>
</head>
<body>
</body>
</html>

how do I get a new line, after using float:left?

Another approach that's a little more semantic is to have a UL defined as your total 6 image width, each LI defined as float left and width defined - so that when LI #7 hits, it runs into the boundry of the UL, and is pushed down to the new row. You'll still have an open float that you'll want to clear after the /UL - but that can be done on the next element of the page, or as a clear div. Here's sort of the idea, you may have to mess with actual values, but this should give you the idea. The code is a little cleaner.

 <style type="text/css"> 
ul#imageSet { width: 600px; margin: 0; padding:0; }
ul#imageSet li { float: left; width: 100px;  height: 188px; margin: 0; padding:0; position: relative; list-style-type: none; }
.cornerimage { position: absolute; bottom: 0; right: 0; } 
h3.nextelement { clear: both; }
</style>


<ul id="imageSet">
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
     <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
</ul>


<h3 class="nextelement">Next Element in Doc</h3>

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

Improve INSERT-per-second performance of SQLite

Try using SQLITE_STATIC instead of SQLITE_TRANSIENT for those inserts.

SQLITE_TRANSIENT will cause SQLite to copy the string data before returning.

SQLITE_STATIC tells it that the memory address you gave it will be valid until the query has been performed (which in this loop is always the case). This will save you several allocate, copy and deallocate operations per loop. Possibly a large improvement.

Copying data from one SQLite database to another

Objective-C code for copy Table from a Database to another Database

-(void) createCopyDatabase{

          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
          NSString *documentsDir = [paths objectAtIndex:0];

          NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;

          NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
          NSFileManager *fileManager = [NSFileManager defaultManager];
          char *error;

         if ([fileManager fileExistsAtPath:newdbPath]) {
             [fileManager removeItemAtPath:newdbPath error:nil];
         }
         sqlite3 *database;
         //open database
        if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
            NSLog(@"Error to open database");
        }

        NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",maindbPath];

       sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
       if (error) {
           NSLog(@"Error to Attach = %s",error);
       }

       //Query for copy Table
       NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM aDB.Info";
       sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
        if (error) {
            NSLog(@"Error to copy database = %s",error);
        }

        //Query for copy Table with Where Clause

        sqlString = @"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'";
        sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
        if (error) {
            NSLog(@"Error to copy database = %s",error);
        }
 }

SQL Server after update trigger

Here is my example after a test

CREATE TRIGGER [dbo].UpdateTasadoresName 
ON [dbo].Tasadores  
FOR  UPDATE
AS 
      UPDATE Tasadores 
      SET NombreCompleto = RTRIM( Tasadores.Nombre + ' ' + isnull(Tasadores.ApellidoPaterno,'') + ' ' + isnull(Tasadores.ApellidoMaterno,'')    )  
      FROM Tasadores 
    INNER JOIN INSERTED i ON Tasadores.id = i.id

The inserted special table will have the information from the updated record.

why I can't get value of label with jquery and javascript?

You need text() or html() for label not val() The function should not be called for label instead it is used to get values of input like text or checkbox etc.

Change

value = $("#telefon").val(); 

To

value = $("#telefon").text(); 

How to maintain state after a page refresh in React.js?

We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.

When the user selects an option, we can push the value of that onto the current route with:

history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});

pathname can be the current path. In your case params would look something like:

{
  selectedOption: 5
}

Then at the top level of the React tree, React Router will update the props of that component with a prop of location.search which is the encoded value we set earlier, so there will be something in componentWillReceiveProps like:

params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});

Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.

React Router: https://github.com/reactjs/react-router

History: https://github.com/ReactTraining/history

The query string library: https://github.com/ljharb/qs

jQuery attr() change img src

  1. Function imageMorph will create a new img element therefore the id is removed. Changed to

    $("#wrapper > img")

  2. You should use live() function for click event if you want you rocket lanch again.

Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/

How to square all the values in a vector in R?

Try this (faster and simpler):

newData <- data^2

Can I simultaneously declare and assign a variable in VBA?

There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the : continuation character if you want it on one line for readability;

Dim clientToTest As String:  clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)

Hint (summary of other answers/comments): Works with objects too (Excel 2010):

Dim ws  As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"

CSS - Syntax to select a class within an id

This will also work and you don't need the extra class:

#navigation li li {}

If you have a third level of LI's you may have to reset/override some of the styles they will inherit from the above selector. You can target the third level like so:

#navigation li li li {}

How to convert a NumPy array to PIL image applying matplotlib colormap

Quite a busy one-liner, but here it is:

  1. First ensure your NumPy array, myarray, is normalised with the max value at 1.0.
  2. Apply the colormap directly to myarray.
  3. Rescale to the 0-255 range.
  4. Convert to integers, using np.uint8().
  5. Use Image.fromarray().

And you're done:

from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

with plt.savefig():

Enter image description here

with im.save():

Enter image description here

Does height and width not apply to span?

Inspired from @Hamed, I added the following and it worked for me:

display: inline-block; overflow: hidden; 

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

From your output:

no listening sockets available, shutting down

what basically means, that any port in which one apache is going to be listening is already being used by another application.

netstat -punta | grep LISTEN

Will give you a list of all the ports being used and the information needed to recognize which process is so you can kill stop or do whatever you want to do with it.

After doing a nmap of your ip I can see that

80/tcp    open     http

so I guess you sorted it out.

Adding whitespace in Java

Use the StringUtils class, it also includes null check

StringUtils.leftPad(String str, int size)
StringUtils.rightPad(String str, int size)

What is the maximum possible length of a .NET string?

The max length of a string on my machine is 1,073,741,791.

You see, Strings aren't limited by integer as is commonly believed.

Memory restrictions aside, Strings cannot have more than 230 (1,073,741,824) characters, since a 2GB limit is imposed by the Microsoft CLR (Common Language Runtime). 33 more than my computer allowed.

Now, here's something you're welcome to try yourself.

Create a new C# console app in Visual Studio and then copy/paste the main method here:

static void Main(string[] args)
{
    Console.WriteLine("String test, by Nicholas John Joseph Taylor");

    Console.WriteLine("\nTheoretically, C# should support a string of int.MaxValue, but we run out of memory before then.");

    Console.WriteLine("\nThis is a quickish test to narrow down results to find the max supported length of a string.");

    Console.WriteLine("\nThe test starts ...now:\n");

    int Length = 0;

    string s = "";

    int Increment = 1000000000; // We know that s string with the length of 1000000000 causes an out of memory exception.

    LoopPoint:

    // Make a string appendage the length of the value of Increment

    StringBuilder StringAppendage = new StringBuilder();

    for (int CharacterPosition = 0; CharacterPosition < Increment; CharacterPosition++)
    {
        StringAppendage.Append("0");

    }

    // Repeatedly append string appendage until an out of memory exception is thrown.

    try
    {
        if (Increment > 0)
            while (Length < int.MaxValue)
            {
                Length += Increment;

                s += StringAppendage.ToString(); // Append string appendage the length of the value of Increment

                Console.WriteLine("s.Length = " + s.Length + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"));

            }

    }
    catch (OutOfMemoryException ex) // Note: Any other exception will crash the program.
    {
        Console.WriteLine("\n" + ex.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");

        Length -= Increment;

        Increment /= 10;

        Console.WriteLine("After decimation, the value of Increment is " + Increment + ".");

    }
    catch (Exception ex2)
    {
        Console.WriteLine("\n" + ex2.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");

        Console.WriteLine("Press a key to continue...");

        Console.ReadKey();

    }

    if (Increment > 0)
    {
        goto LoopPoint;

    }

    Console.WriteLine("Test complete.");

    Console.WriteLine("\nThe max length of a string is " + s.Length + ".");

    Console.WriteLine("\nPress any key to continue.");

    Console.ReadKey();

}

My results were as follows:

String test, by Nicholas John Joseph Taylor

Theoretically, C# should support a string of int.MaxValue, but we run out of memory before then.

This is a quickish test to narrow down results to find the max supported length of a string.

The test starts ...now:

s.Length = 1000000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000000.

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000000. s.Length = 1010000000 at 08/05/2019 12:06 s.Length = 1020000000 at 08/05/2019 12:06 s.Length = 1030000000 at 08/05/2019 12:06 s.Length = 1040000000 at 08/05/2019 12:06 s.Length = 1050000000 at 08/05/2019 12:06 s.Length = 1060000000 at 08/05/2019 12:06 s.Length = 1070000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000000. s.Length = 1071000000 at 08/05/2019 12:06 s.Length = 1072000000 at 08/05/2019 12:06 s.Length = 1073000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000. s.Length = 1073100000 at 08/05/2019 12:06 s.Length = 1073200000 at 08/05/2019 12:06 s.Length = 1073300000 at 08/05/2019 12:06 s.Length = 1073400000 at 08/05/2019 12:06 s.Length = 1073500000 at 08/05/2019 12:06 s.Length = 1073600000 at 08/05/2019 12:06 s.Length = 1073700000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000. s.Length = 1073710000 at 08/05/2019 12:06 s.Length = 1073720000 at 08/05/2019 12:06 s.Length = 1073730000 at 08/05/2019 12:06 s.Length = 1073740000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000. s.Length = 1073741000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100. s.Length = 1073741100 at 08/05/2019 12:06 s.Length = 1073741200 at 08/05/2019 12:06 s.Length = 1073741300 at 08/05/2019 12:07 s.Length = 1073741400 at 08/05/2019 12:07 s.Length = 1073741500 at 08/05/2019 12:07 s.Length = 1073741600 at 08/05/2019 12:07 s.Length = 1073741700 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 10. s.Length = 1073741710 at 08/05/2019 12:07 s.Length = 1073741720 at 08/05/2019 12:07 s.Length = 1073741730 at 08/05/2019 12:07 s.Length = 1073741740 at 08/05/2019 12:07 s.Length = 1073741750 at 08/05/2019 12:07 s.Length = 1073741760 at 08/05/2019 12:07 s.Length = 1073741770 at 08/05/2019 12:07 s.Length = 1073741780 at 08/05/2019 12:07 s.Length = 1073741790 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 1. s.Length = 1073741791 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 0. Test complete.

The max length of a string is 1073741791.

Press any key to continue.

The max length of a string on my machine is 1073741791.

I'd appreciate it very much if people could post their results as a comment below.

It will be interesting to learn if people get the same or different results.

Target Unreachable, identifier resolved to null in JSF 2.2

I solved this problem.

My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.

Thanks @PM77-1


javascript regular expression to not match a word

function doesNotContainAbcOrDef(x) {
    return (x.match('abc') || x.match('def')) === null;
}

What is a .pid file and what does it contain?

Pidfile contains pid of a process. It is a convention allowing long running processes to be more self-aware. Server process can inspect it to stop itself, or have heuristic that its other instance is already running. Pidfiles can also be used to conventiently kill risk manually, e.g. pkill -F <some.pid>

How to convert a color integer to a hex String in Android?

I believe i have found the answer, This code converts the integer to a hex string an removes the alpha.

Integer intColor = -16895234;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);

Note only use this code if you are sure that removing the alpha would not affect anything.

Angular2 disable button

May be below code can help:

<button [attr.disabled]="!isValid ? true : null">Submit</button>

iPhone X / 8 / 8 Plus CSS media queries

If your page is missing meta[@name="viewport"] element within its DOM, then the following could be used to detect a mobile device:

@media only screen and (width: 980px), (hover: none) { … }

If you want to avoid false-positives with desktops that just magically have their viewport set to 980px like all the mobile browsers do, then a device-width test could also be added into the mix:

@media only screen and (max-device-width: 800px) and (width: 980px), (hover: none) { … }

Per the list at https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries, the new hover property would appear to be the final new way to detect that you've got yourself a mobile device that doesn't really do proper hover; it's only been introduced in 2018 with Firefox 64 (2018), although it's been supported since 2016 with Android Chrome 50 (2016), or even since 2014 with Chrome 38 (2014):

Link to the issue number on GitHub within a commit message

github adds a reference to the commit if it contains #issuenbr (discovered this by chance).

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

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

I like the DataTable approach proposed by MusiGenesis above. The nice thing about it is that you can sort by any valid SQL 'order by' string that uses column names, e.g. "x, y desc, z" for 'order by x, y desc, z'. (FWIW, I could not get it to work using column ordinals, e.g. "3,2,1 " for 'order by 3,2,1') I used only integers, but clearly you could add mixed type data into the DataTable and sort it any which way.

In the example below, I first loaded some unsorted integer data into a tblToBeSorted in Sandbox (not shown). With the table and its data already existing, I load it (unsorted) into a 2D integer array, then to a DataTable. The array of DataRows is the sorted version of DataTable. The example is a little odd in that I load my array from the DB and could have sorted it then, but I just wanted to get an unsorted array into C# to use with the DataTable object.

static void Main(string[] args)
{
    SqlConnection cnnX = new SqlConnection("Data Source=r90jroughgarden\\;Initial Catalog=Sandbox;Integrated Security=True");
    SqlCommand cmdX = new SqlCommand("select * from tblToBeSorted", cnnX);
    cmdX.CommandType = CommandType.Text;
    SqlDataReader rdrX = null;
    if (cnnX.State == ConnectionState.Closed) cnnX.Open();

    int[,] aintSortingArray = new int[100, 4];     //i, elementid, planid, timeid

    try
    {
        //Load unsorted table data from DB to array
        rdrX = cmdX.ExecuteReader();
        if (!rdrX.HasRows) return;

        int i = -1;
        while (rdrX.Read() && i < 100)
        {
            i++;
            aintSortingArray[i, 0] = rdrX.GetInt32(0);
            aintSortingArray[i, 1] = rdrX.GetInt32(1);
            aintSortingArray[i, 2] = rdrX.GetInt32(2);
            aintSortingArray[i, 3] = rdrX.GetInt32(3);
        }
        rdrX.Close();

        DataTable dtblX = new DataTable();
        dtblX.Columns.Add("ChangeID");
        dtblX.Columns.Add("ElementID");
        dtblX.Columns.Add("PlanID");
        dtblX.Columns.Add("TimeID");
        for (int j = 0; j < i; j++)
        {
            DataRow drowX = dtblX.NewRow();
            for (int k = 0; k < 4; k++)
            {
                drowX[k] = aintSortingArray[j, k];
            }
            dtblX.Rows.Add(drowX);
        }

        DataRow[] adrowX = dtblX.Select("", "ElementID, PlanID, TimeID");
        adrowX = dtblX.Select("", "ElementID desc, PlanID asc, TimeID desc");

    }
    catch (Exception ex)
    {
        string strErrMsg = ex.Message;
    }
    finally
    {
        if (cnnX.State == ConnectionState.Open) cnnX.Close();
    }
}

In java how to get substring from a string till a character c?

look at String.indexOf and String.substring.

Make sure you check for -1 for indexOf.

How can I add an item to a ListBox in C# and WinForms?

DisplayMember and ValueMember are mostly only useful if you're databinding to objects that have those properties defined. You would then need to add an instance of that object.

e.g.:

public class MyObject
{
     public string clan { get; set; }
     public int sifOsoba { get; set; }
     public MyObject(string aClan, int aSif0soba)
     {
        this.clan = aClan;
        this.sif0soba = aSif0soba;
     }

     public override string ToString() { return this.clan; }
 }

 ....

 list.Items.Add(new MyObject("hello", 5));

If you're binding it manually then you can use the example provided by goggles

How to get element by class name?

You need to use the document.getElementsByClassName('class_name');

and dont forget that the returned value is an array of elements so if you want the first one use:

document.getElementsByClassName('class_name')[0]

UPDATE

Now you can use:

document.querySelector(".class_name") to get the first element with the class_name CSS class (null will be returned if non of the elements on the page has this class name)

or document.querySelectorAll(".class_name") to get a NodeList of elements with the class_name css class (empty NodeList will be returned if non of. the elements on the the page has this class name).

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

How can I get a Unicode character's code?

There is an open source library MgntUtils that has a Utility class StringUnicodeEncoderDecoder. That class provides static methods that convert any String into Unicode sequence vise-versa. Very simple and useful. To convert String you just do:

String codes = StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence(myString);

For example a String "Hello World" will be converted into

"\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064"

It works with any language. Here is the link to the article that explains all te ditails about the library: MgntUtils. Look for the subtitle "String Unicode converter". The library could be obtained as a Maven artifact or taken from Github (including source code and Javadoc)

AttributeError: 'tuple' object has no attribute

I am working in python flask: I had the same problem... There was a "," after I declared my my form variables; I am working with wtforms. That is what caused all the confusion

How to check certificate name and alias in keystore files?

You can run the following command to list the content of your keystore file (and alias name):

keytool -v -list -keystore .keystore

If you are looking for a specific alias, you can also specify it in the command:

keytool -list -keystore .keystore -alias foo

If the alias is not found, it will display an exception:

keytool error: java.lang.Exception: Alias does not exist

How to make a custom LinkedIn share button

Official LinkedIn API for sharing:

https://developer.linkedin.com/docs/share-on-linkedin

Read Terms of Use!

Example link using "Customized URL" method: http://www.linkedin.com/shareArticle?mini=true&url=https://stackoverflow.com/questions/10713542/how-to-make-custom-linkedin-share-button/10737122&title=How%20to%20make%20custom%20linkedin%20share%20button&summary=some%20summary%20if%20you%20want&source=stackoverflow.com

You just need to open it in popup using JavaScript or load it to iframe. Simple and works - that's what I was looking for!

EDIT: Video attached to a post:

I checked that you can't really embed any video to LinkedIn post, the only option is to add the link to the page with video itself.

You can achieve it by putting YT link into url param:

https://www.linkedin.com/shareArticle?mini=true&url=https://www.youtube.com/watch?v=SBi92AOSW2E

If you specify summary and title then LinkedIn will stop pulling it from the video, e.g.:

https://www.linkedin.com/shareArticle?mini=true&summary=youtube&title=f1&url=https://www.youtube.com/watch?v=SBi92AOSW2E

It does work exactly the same with Vimeo, and probably will work for any website. Hope it will help.

EDIT 2: Pulling images to the post:

When you open above links you will see that LinkedIn loads some images along with the passed URL (and optionally title and summary).

LinkedIn does it automatically, and you can read about it here: https://developer.linkedin.com/docs/share-on-linkedin#opengraph

It's interesting though as it says:

If Open Graph tags are present, LinkedIn's crawler will not have to rely on it's own analysis to determine what content will be shared, which improves the likelihood that the information that is shared is exactly what you intended.

It tells me that even if Open Graph information is not attached, LinkedIn can pull this data based on its own analysis. And in case of YouTube it seems to be the case, as I couldn't find any Open Graph tags added to YouTube pages.

How to check if an email address exists without sending an email?

There are two methods you can sometimes use to determine if a recipient actually exists:

  1. You can connect to the server, and issue a VRFY command. Very few servers support this command, but it is intended for exactly this. If the server responds with a 2.0.0 DSN, the user exists.

    VRFY user
    
  2. You can issue a RCPT, and see if the mail is rejected.

    MAIL FROM:<>
    RCPT TO:<user@domain>
    

If the user doesn't exist, you'll get a 5.1.1 DSN. However, just because the email is not rejected, does not mean the user exists. Some server will silently discard requests like this to prevent enumeration of their users. Other servers cannot verify the user and have to accept the message regardless.

There is also an antispam technique called greylisting, which will cause the server to reject the address initially, expecting a real SMTP server would attempt a re-delivery some time later. This will mess up attempts to validate the address.

Honestly, if you're attempting to validate an address the best approach is to use a simple regex to block obviously invalid addresses, and then send an actual email with a link back to your system that will validate the email was received. This also ensures that they user entered their actual email, not a slight typo that happens to belong to somebody else.

Java program to find the largest & smallest number in n numbers without using arrays

Try the code mentioned below

public static void main(String[] args) {
    int smallest=0; int large=0; int num;
    System.out.println("enter the number");
    Scanner input=new Scanner(System.in);
    int n=input.nextInt();
    num=input.nextInt();
    smallest = num;
    for(int i=0;i<n-1;i++)
        {
            num=input.nextInt();
            if(num<smallest)
            {
                smallest=num;
            }
        }
        System.out.println("the smallest is:"+smallest);
}

How do you get the file size in C#?

FileInfo.Length will do the trick (per MSDN it "[g]ets the size, in bytes, of the current file.") There is a nice page on MSDN on common I/O tasks.

What is the .idea folder?

As of year 2020, JetBrains suggests to commit the .idea folder.
The JetBrains IDEs (webstorm, intellij, android studio, pycharm, clion, etc.) automatically add that folder to your git repository (if there's one).
Inside the folder .idea, has been already created a .gitignore, updated by the IDE itself to avoid to commit user related settings that may contains privacy/password data.

It is safe (and usually useful) to commit the .idea folder.

How does "cat << EOF" work in bash?

Worth noting that here docs work in bash loops too. This example shows how-to get the column list of table:

export postgres_db_name='my_db'
export table_name='my_table_name'

# start copy 
while read -r c; do test -z "$c" || echo $table_name.$c , ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
SELECT column_name
FROM information_schema.columns
WHERE 1=1
AND table_schema = 'public'
AND table_name   =:'table_name'  ;
EOF
)
# stop copy , now paste straight into the bash shell ...

output: 
my_table_name.guid ,
my_table_name.id ,
my_table_name.level ,
my_table_name.seq ,

or even without the new line

while read -r c; do test -z "$c" || echo $table_name.$c , | perl -ne 
's/\n//gm;print' ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
 SELECT column_name
 FROM information_schema.columns
 WHERE 1=1
 AND table_schema = 'public'
 AND table_name   =:'table_name'  ;
 EOF
 )

 # output: daily_issues.guid ,daily_issues.id ,daily_issues.level ,daily_issues.seq ,daily_issues.prio ,daily_issues.weight ,daily_issues.status ,daily_issues.category ,daily_issues.name ,daily_issues.description ,daily_issues.type ,daily_issues.owner

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

this expression is to get only numbers

    If Regex.IsMatch(mystring, "^[A-Za-z ].*|\s") Then
        MessageBox.Show("please fill the box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
       
    ElseIf (mystring = "") Then
        MessageBox.Show("please fill the box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
      
    End If

How do I add the contents of an iterable to a set?

You can add elements of a list to a set like this:

>>> foo = set(range(0, 4))
>>> foo
set([0, 1, 2, 3])
>>> foo.update(range(2, 6))
>>> foo
set([0, 1, 2, 3, 4, 5])

Validating a Textbox field for only numeric input.

Here is another simple solution

try
{
    int temp=Convert.ToInt32(txtEvDistance.Text);
}
catch(Exception h)
{
    MessageBox.Show("Please provide number only");
}

mysql_config not found when installing mysqldb python interface

On python 3.5.2

sudo apt-get install libmysqlclient-dev python-dev

Counting lines, words, and characters within a text file using Python

file__IO = input('\nEnter file name here to analize with path:: ')
with open(file__IO, 'r') as f:
    data = f.read()
    line = data.splitlines()
    words = data.split()
    spaces = data.split(" ")
    charc = (len(data) - len(spaces))

    print('\n Line number ::', len(line), '\n Words number ::', len(words), '\n Spaces ::', len(spaces), '\n Charecters ::', (len(data)-len(spaces)))

I tried this code & it works as expected.

How to resize image automatically on browser width resize but keep same height?

I've used Perfect Full Page Background Image to accomplish this on a previous site.

You can use background-size: cover; if you only need to support modern browsers.

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

To send mail using Gmail SMTP, need to change your account setting. Login into your gmail accout then follow the link below to change your gmail account setting to send mail using your apps and program. https://www.google.com/settings/security/lesssecureapps

Note: This setting is not available for accounts with 2-Step Verification enabled. Such accounts require an application-specific password for less secure apps access.

Good way of getting the user's location in Android

I scoured the internet for an updated (past year) answer using the latest location pulling methods suggested by google (to use FusedLocationProviderClient). I finally landed on this:

https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates

I created a new project and copied in most of this code. Boom. It works. And I think without any deprecated lines.

Also, the simulator doesn't seem to get a GPS location, that I know of. It did get as far as reporting this in the log: "All location settings are satisfied."

And finally, in case you wanted to know (I did), you DO NOT need a google maps api key from the google developer console, if all you want is the GPS location.

Also useful is their tutorial. But I wanted a full one page tutorial/code example, and that. Their tutorial stacks but is confusing when you're new to this because you don't know what pieces you need from earlier pages.

https://developer.android.com/training/location/index.html

And finally, remember things like this:

I not only had to modify the mainActivity.Java. I also had to modify Strings.xml, androidmanifest.xml, AND the correct build.gradle. And also your activity_Main.xml (but that part was easy for me).

I needed to add dependencies like this one: implementation 'com.google.android.gms:play-services-location:11.8.0', and update the settings of my android studio SDK to include google play services. (file settings appearance system settings android SDK SDK Tools check google play services).

update: the android simulator did seem to get a location and location change events (when I changed the value in the settings of the sim). But my best and first results were on an actual device. So it's probably easiest to test on actual devices.

Android EditText for password with android:hint

Hint is displayed correctly with

android:inputType="textPassword"

and

android:gravity="center"

if you set also

android:ellipsize="start"

Get Mouse Position

If you're using Swing as your UI layer, you can use a Mouse-Motion Listener for this.

Spring Boot Adding Http Request Interceptors

Since all responses to this make use of the now long-deprecated abstract WebMvcConfigurer Adapter instead of the WebMvcInterface (as already noted by @sebdooe), here is a working minimal example for a SpringBoot (2.1.4) application with an Interceptor:

Minimal.java:

@SpringBootApplication
public class Minimal
{
    public static void main(String[] args)
    {
        SpringApplication.run(Minimal.class, args);
    }
}

MinimalController.java:

@RestController
@RequestMapping("/")
public class Controller
{
    @GetMapping("/")
    @ResponseBody
    public ResponseEntity<String> getMinimal()
    {
        System.out.println("MINIMAL: GETMINIMAL()");

        return new ResponseEntity<String>("returnstring", HttpStatus.OK);
    }
}

Config.java:

@Configuration
public class Config implements WebMvcConfigurer
{
    //@Autowired
    //MinimalInterceptor minimalInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        registry.addInterceptor(new MinimalInterceptor());
    }
}

MinimalInterceptor.java:

public class MinimalInterceptor extends HandlerInterceptorAdapter
{
    @Override
    public boolean preHandle(HttpServletRequest requestServlet, HttpServletResponse responseServlet, Object handler) throws Exception
    {
        System.out.println("MINIMAL: INTERCEPTOR PREHANDLE CALLED");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
    {
        System.out.println("MINIMAL: INTERCEPTOR POSTHANDLE CALLED");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception
    {
        System.out.println("MINIMAL: INTERCEPTOR AFTERCOMPLETION CALLED");
    }
}

works as advertised

The output will give you something like:

> Task :Minimal.main()

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-04-29 11:53:47.560  INFO 4593 --- [           main] io.minimal.Minimal                       : Starting Minimal on y with PID 4593 (/x/y/z/spring-minimal/build/classes/java/main started by x in /x/y/z/spring-minimal)
2019-04-29 11:53:47.563  INFO 4593 --- [           main] io.minimal.Minimal                       : No active profile set, falling back to default profiles: default
2019-04-29 11:53:48.745  INFO 4593 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-04-29 11:53:48.780  INFO 4593 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-04-29 11:53:48.781  INFO 4593 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-04-29 11:53:48.892  INFO 4593 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-04-29 11:53:48.893  INFO 4593 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1269 ms
2019-04-29 11:53:49.130  INFO 4593 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-29 11:53:49.375  INFO 4593 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-29 11:53:49.380  INFO 4593 --- [           main] io.minimal.Minimal                       : Started Minimal in 2.525 seconds (JVM running for 2.9)
2019-04-29 11:54:01.267  INFO 4593 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-04-29 11:54:01.267  INFO 4593 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-04-29 11:54:01.286  INFO 4593 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 19 ms
MINIMAL: INTERCEPTOR PREHANDLE CALLED
MINIMAL: GETMINIMAL()
MINIMAL: INTERCEPTOR POSTHANDLE CALLED
MINIMAL: INTERCEPTOR AFTERCOMPLETION CALLED

How to initailize byte array of 100 bytes in java with all 0's

Actually the default value of byte is 0.

Changing all files' extensions in a folder with one command on Windows

You can use ren (as in rename):

ren *.XXX *.YYY

And of course, switch XXX and YYY for the appropriate extensions. It will change from XXX to YYY. If you want to change all extensions, just use the wildcard again:

ren *.* *.YYY

One way to make this work recursively is with the FOR command. It can be used with the /R option to recursively apply a command to matching files. For example:

for /R %x in (*.txt) do ren "%x" *.renamed

will change all .txt extensions to .renamed recursively, starting in the current directory. %x is the variable that holds the matched file names.

And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.

Note: this works only on cmd. Won't work on Powershell or Bash

How to define Singleton in TypeScript

Singleton classes in TypeScript are generally an anti-pattern. You can simply use namespaces instead.

Useless singleton pattern

class Singleton {
    /* ... lots of singleton logic ... */
    public someMethod() { ... }
}

// Using
var x = Singleton.getInstance();
x.someMethod();

Namespace equivalent

export namespace Singleton {
    export function someMethod() { ... }
}
// Usage
import { SingletonInstance } from "path/to/Singleton";

SingletonInstance.someMethod();
var x = SingletonInstance; // If you need to alias it for some reason

Big-oh vs big-theta

Because there are algorithms whose best-case is quick, and thus it's technically a big O, not a big Theta.

Big O is an upper bound, big Theta is an equivalence relation.

How to deep merge instead of shallow merge?

Does anybody know if deep merging exists in the ES6/ES7 spec?

Object.assign documentation suggests it doesn't do deep clone.

"Keep Me Logged In" - the best approach

I think you could just do this:

$cookieString = password_hash($username, PASSWORD_DEFAULT);

Store $cookiestring in the DB and and set it as a cookie. Also set the username of the person as a cookie. The whole point of a hash is that it can't be reverse-engineered.

When a user turns up, get the username from one cookie, than $cookieString from another. If $cookieString matches the one stored in the DB, then the user is authenticated. As password_hash uses a different salt each time, it is irrelevant as to what the clear text is.

Sending HTTP POST with System.Net.WebClient

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

Probably is the use of the "on" event that Bootstrap use a lot and was inserted at jQuery 1.7 http://api.jquery.com/on/

Tkinter module not found on Ubuntu

this works for me:

from tkinter import *
root = Tk()
l = Label(root, text="Does it work")
l.pack()

python and sys.argv

I would do it this way:

import sys

def main(argv):
    if len(argv) < 2:
        sys.stderr.write("Usage: %s <database>" % (argv[0],))
        return 1

    if not os.path.exists(argv[1]):
        sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
        return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv))

This allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be.

How to trim a string to N chars in Javascript?

I suggest to use an extension for code neatness. Note that extending an internal object prototype could potentially mess with libraries that depend on them.

String.prototype.trimEllip = function (length) {
  return this.length > length ? this.substring(0, length) + "..." : this;
}

And use it like:

var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)

Using `date` command to get previous, current and next month

If you happen to be using date in a MacOS environment, try this:

ST1:~ ejf$ date
Mon Feb 20 21:55:48 CST 2017
ST1:~ ejf$ date -v-1m +%m
01
ST1:~ ejf$ date -v+1m +%m
03

Also, I'd rather calculate the previous and next month on the first day of each month, this way you won't have issues with months ending the 30/31 or 28/29 (Feb/Feb leap year)

Duplicating a MySQL table, indices, and data

Apart from the solution above, you can use AS to make it in one line.

CREATE TABLE tbl_new AS SELECT * FROM tbl_old;

Use superscripts in R axis labels

@The Thunder Chimp You can split text in such a way that some sections are affected by super(or sub) script and others aren't through the use of *. For your example, with splitting the word "moment" from "4th" -

plot(rnorm(30), xlab = expression('4'^th*'moment'))

How to Clear Console in Java?

If your terminal supports ANSI escape codes, this clears the screen and moves the cursor to the first row, first column:

System.out.print("\033[H\033[2J");
System.out.flush();

This works on almost all UNIX terminals and terminal emulators. The Windows cmd.exe does not interprete ANSI escape codes.

Switch statement: must default be the last case?

It's valid, but rather nasty. I would suggest it's generally bad to allow fall-throughs as it can lead to some very messy spaghetti code.

It's almost certainly better to break these cases up into several switch statements or smaller functions.

[edit] @Tristopia: Your example:

Example from UCS-2 to UTF-8 conversion 

r is the destination array, 
wc is the input wchar_t  

switch(utf8_length) 
{ 
    /* Note: code falls through cases! */ 
    case 3: r[2] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x800; 
    case 2: r[1] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x0c0; 
    case 1: r[0] = wc;
}

would be clearer as to it's intention (I think) if it were written like this:

if( utf8_length >= 1 )
{
    r[0] = wc;

    if( utf8_length >= 2 )
    {
        r[1] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x0c0; 

        if( utf8_length == 3 )
        {
            r[2] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x800; 
        }
    }
}   

[edit2] @Tristopia: Your second example is probably the cleanest example of a good use for follow-through:

for(i=0; s[i]; i++)
{
    switch(s[i])
    {
    case '"': 
    case '\'': 
    case '\\': 
        d[dlen++] = '\\'; 
        /* fall through */ 
    default: 
        d[dlen++] = s[i]; 
    } 
}

..but personally I would split the comment recognition into it's own function:

bool isComment(char charInQuestion)
{   
    bool charIsComment = false;
    switch(charInQuestion)
    {
    case '"': 
    case '\'': 
    case '\\': 
        charIsComment = true; 
    default: 
        charIsComment = false; 
    } 
    return charIsComment;
}

for(i=0; s[i]; i++)
{
    if( isComment(s[i]) )
    {
        d[dlen++] = '\\'; 
    }
    d[dlen++] = s[i]; 
}

Setting Custom ActionBar Title from Fragment

===Update October, 30, 2019===

Since we have new components such as ViewModel and LiveData, we can have a different/easier way to update Activity Title from Fragment by using ViewModel and Live Data

Activity

class MainActivity : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main_activity)
    if (savedInstanceState == null) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.container, MainFragment.newInstance())
            .commitNow()
    }
    viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
    viewModel.title.observe(this, Observer {
        supportActionBar?.title = it
    })
} }

MainFragment

class MainFragment : Fragment() {
companion object {
    fun newInstance() = MainFragment()
}
private lateinit var viewModel: MainViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View {
    return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    activity?.run {
        viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
    } ?: throw Throwable("invalid activity")
    viewModel.updateActionBarTitle("Custom Title From Fragment")
} }

And MainModelView:

class MainViewModel : ViewModel() {
private val _title = MutableLiveData<String>()
val title: LiveData<String>
get() = _title
fun updateActionBarTitle(title: String) = _title.postValue(title) }

And then you can update the Activity title from Fragment using viewModel.updateActionBarTitle("Custom Title From Fragment")

===Update April, 10, 2015===

You should use listener to update your action bar title

Fragment:

public class UpdateActionBarTitleFragment extends Fragment {
    private OnFragmentInteractionListener mListener;

    public UpdateActionBarTitleFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mListener != null) {
            mListener.onFragmentInteraction("Custom Title");
        }
        return inflater.inflate(R.layout.fragment_update_action_bar_title2, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(String title);
    }
}

And Activity:

public class UpdateActionBarTitleActivity extends ActionBarActivity implements UpdateActionBarTitleFragment.OnFragmentInteractionListener {

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

    @Override
    public void onFragmentInteraction(String title) {
        getSupportActionBar().setTitle(title);
    }
}

Read more here: https://developer.android.com/training/basics/fragments/communicating.html

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

What is Common Gateway Interface (CGI)?

CGI is an interface which tells the webserver how to pass data to and from an application. More specifically, it describes how request information is passed in environment variables (such as request type, remote IP address), how the request body is passed in via standard input, and how the response is passed out via standard output. You can refer to the CGI specification for details.

To use your image:

user (client) request for page ---> webserver ---[CGI]----> Server side Program ---> MySQL Server.

Most if not all, webservers can be configured to execute a program as a 'CGI'. This means that the webserver, upon receiving a request, will forward the data to a specific program, setting some environment variables and marshalling the parameters via standard input and standard output so the program can know where and what to look for.

The main benefit is that you can run ANY executable code from the web, given that both the webserver and the program know how CGI works. That's why you could write web programs in C or Bash with a regular CGI-enabled webserver. That, and that most programming environments can easily use standard input, standard output and environment variables.

In your case you most likely used another, specific for PHP, means of communication between your scripts and the webserver, this, as you well mention in your question, is an embedded interpreter called mod_php.

So, answering your questions:

What exactly is CGI?

See above.

Whats the big deal with /cgi-bin/*.cgi? Whats up with this? I don't know what is this cgi-bin directory on the server for. I don't know why they have *.cgi extensions.

That's the traditional place for cgi programs, many webservers come with this directory pre configured to execute all binaries there as CGI programs. The .cgi extension denotes an executable that is expected to work through the CGI.

Why does Perl always comes in the way. CGI & Perl (language). I also don't know whats up with these two. Almost all the time I keep hearing these two in combination "CGI & Perl". This book is another great example CGI Programming with Perl Why not "CGI Programming with PHP/JSP/ASP". I never saw such things.

Because Perl is ancient (older than PHP, JSP and ASP which all came to being when CGI was already old, Perl existed when CGI was new) and became fairly famous for being a very good language to serve dynamic webpages via the CGI. Nowadays there are other alternatives to run Perl in a webserver, mainly mod_perl.

CGI Programming in C this confuses me a lot. in C?? Seriously?? I don't know what to say. I"m just confused. "in C"?? This changes everything. Program needs to be compiled and executed. This entirely changes my view of web programming. When do I compile? How does the program gets executed (because it will be a machine code, so it must execute as a independent process). How does it communicate with the web server? IPC? and interfacing with all the servers (in my example MATLAB & MySQL) using socket programming? I'm lost!!

You compile the executable once, the webserver executes the program and passes the data in the request to the program and outputs the received response. CGI specifies that one program instance will be launched per each request. This is why CGI is inefficient and kind of obsolete nowadays.

They say that CGI is deprecated. Its no more in use. Is it so? What is its latest update?

CGI is still used when performance is not paramount and a simple means of executing code is required. It is inefficient for the previously stated reasons and there are more modern means of executing any program in a web enviroment. Currently the most famous is FastCGI.

Connecting to Postgresql in a docker container from outside

I already had running postgres on host machine and didn't want to allow connections from network, so I did run temporary postgres instance in container and created database in just two lines:

# Run PostgreSQL
docker run --name postgres-container -e POSTGRES_PASSWORD=password -it -p 5433:5432 postgres

# Create database
docker exec -it postgres-container createdb -U postgres my-db

Where do I put image files, css, js, etc. in Codeigniter?

The link_tag() helper is clearly the way to do this. Put your css where it usually belongs, in site_root/css/ and then use the helper:

From The CodeIgniter docs...

echo link_tag('css/mystyles.css');

Output

<link href="http://example.com/css/mystyles.css" rel="stylesheet" type="text/css" />

How can I create a border around an Android LinearLayout?

Try this:

For example, let's define res/drawable/my_custom_background.xml as:

(create this layout in your drawable folder) layout_border.xml

  <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:height="2dp"
                android:color="#FF0000" />
            <solid android:color="#000000" />
            <padding android:left="1dp" android:top="1dp" android:right="1dp"
                android:bottom="1dp" />

            <corners android:radius="1dp" android:bottomRightRadius="5dp"
                android:bottomLeftRadius="0dp" android:topLeftRadius="5dp"
                android:topRightRadius="0dp" />
        </shape>
    </item>

</layer-list>

main.xml

<LinearLayout 
    android:layout_gravity="center"
    android:layout_width="200dp" 
    android:layout_height="200dp"   
    android:background="@drawable/layout_border" />
</LinearLayout>

Has anyone ever got a remote JMX JConsole to work?

I am running JConsole/JVisualVm on windows hooking to tomcat running Linux Redhat ES3.

Disabling packet filtering using the following command did the trick for me:

/usr/sbin/iptables -I INPUT -s jconsole-host -p tcp --destination-port jmxremote-port -j ACCEPT

where jconsole-host is either the hostname or the host address on which JConsole runs on and jmxremote-port is the port number set for com.sun.management.jmxremote.port for remote management.

Twitter API returns error 215, Bad Authentication Data

You need to send customerKey and customerSecret to Zend_Service_Twitter

$twitter = new Zend_Service_Twitter(array(
                'consumerKey' => $this->consumer_key,
                'consumerSecret' => $this->consumer_secret,
                'username' => $user->screenName,
                'accessToken' => unserialize($user->token)
));

Permission denied on CopyFile in VBS

Another thing to check is if any applications still have a hold on the file.

Had some issues with MoveFile. Part of my permissions problem was that my script opens the file (in this case in Excel), makes a modification, closes it, then moves it to a "processed" folder.

In debugging a couple things, the script crashed a few times. Digging into the permission denied error I found that I had 4 instances of Excel running in the background because the script was never able to properly terminate the application due to said crashes. Apparently one of them still had a hold on the file and, thusly, "permission denied."

calling parent class method from child class object in java

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.

public class PolyTest{
    public static void main(String args[]){
        new Child().foo();
    }

}
class Parent{
    public void foo(){
        System.out.println("I'm the parent.");
    }
}

class Child extends Parent{
    @Override
    public void foo(){
        //super.foo();
        System.out.println("I'm the child.");
    }
}

This would print:

I'm the child.

Uncomment the commented line and it would print:

I'm the parent.

I'm the child.

You should look for the concept of Polymorphism.

What is a blob URL and why it is used?

Blob URLs (ref W3C, official name) or Object-URLs (ref. MDN and method name) are used with a Blob or a File object.

src="blob:https://crap.crap" I opened the blob url that was in src of video it gave a error and i can't open but was working with the src tag how it is possible?

Blob URLs can only be generated internally by the browser. URL.createObjectURL() will create a special reference to the Blob or File object which later can be released using URL.revokeObjectURL(). These URLs can only be used locally in the single instance of the browser and in the same session (ie. the life of the page/document).

What is blob url?
Why it is used?

Blob URL/Object URL is a pseudo protocol to allow Blob and File objects to be used as URL source for things like images, download links for binary data and so forth.

For example, you can not hand an Image object raw byte-data as it would not know what to do with it. It requires for example images (which are binary data) to be loaded via URLs. This applies to anything that require an URL as source. Instead of uploading the binary data, then serve it back via an URL it is better to use an extra local step to be able to access the data directly without going via a server.

It is also a better alternative to Data-URI which are strings encoded as Base-64. The problem with Data-URI is that each char takes two bytes in JavaScript. On top of that a 33% is added due to the Base-64 encoding. Blobs are pure binary byte-arrays which does not have any significant overhead as Data-URI does, which makes them faster and smaller to handle.

Can i make my own blob url on a server?

No, Blob URLs/Object URLs can only be made internally in the browser. You can make Blobs and get File object via the File Reader API, although BLOB just means Binary Large OBject and is stored as byte-arrays. A client can request the data to be sent as either ArrayBuffer or as a Blob. The server should send the data as pure binary data. Databases often uses Blob to describe binary objects as well, and in essence we are talking basically about byte-arrays.

if you have then Additional detail

You need to encapsulate the binary data as a BLOB object, then use URL.createObjectURL() to generate a local URL for it:

var blob = new Blob([arrayBufferWithPNG], {type: "image/png"}),
    url = URL.createObjectURL(blob),
    img = new Image();

img.onload = function() {
    URL.revokeObjectURL(this.src);     // clean-up memory
    document.body.appendChild(this);   // add image to DOM
}

img.src = url;                         // can now "stream" the bytes

Note that URL may be prefixed in webkit-browsers, so use:

var url = (URL || webkitURL).createObjectURL(...);

jQuery disable a link

Just set preventDefault and return false

   $('#your-identifier').click(function(e) {
        e.preventDefault();
        return false;
    });

This will be disabled link but still, you will see a clickable icon(hand) icon. You can remove that too with below

$('#your-identifier').css('cursor', 'auto');

How can I transition height: 0; to height: auto; using CSS?

I just animated the <li> element instead of the whole container:

<style>
.menu {
    border: solid;
}
.menu ul li {
    height: 0px;
    transition: height 0.3s;
    overflow: hidden;
}
button:hover ~ .wrapper .menu ul li,
button:focus ~ .wrapper .menu ul li,
.menu:hover ul li {
    height: 20px;
}
</style>


<button>Button</button>
<div class="wrapper">
    <div class="menu">
        <ul>
            <li>menuitem</li>
            <li>menuitem</li>
            <li>menuitem</li>
            <li>menuitem</li>
            <li>menuitem</li>
            <li>menuitem</li>
        </ul>
    </div>
</div>

you can add ul: margin 0; to have 0 height.

How to clear the Entry widget after a button is pressed in Tkinter?

real gets the value ent.get() which is just a string. It has no idea where it came from, and no way to affect the widget.

Instead of real.delete(), call .delete() on the entry widget itself:

def res(ent, real, secret):
    if secret == eval(real):
        showinfo(message='that is right!')
    ent.delete(0, END)

def guess():
    ...
    btn = Button(ge, text="Enter", command=lambda: res(ent, ent.get(), secret))

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

In my case,

[[NSBundle mainBundle] loadNibNamed:@"NameOfTheSubviewNibFile" owner:self options:nil]

was the reason.

replacing this with initWithNibName, resolved.

JVM heap parameters

if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.

-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.

I think that second thing is better because you give to java the automatic memory management.

Why is MySQL InnoDB insert so slow?

things that speed up the inserts:

  • i had removed all keys from a table before large insert into empty table
  • then found i had a problem that the index did not fit in memory.
  • also found i had sync_binlog=0 (should be 1) even if binlog is not used.
  • also found i did not set innodb_buffer_pool_instances

How do I use MySQL through XAMPP?

XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.

After the successful installation navigate to your xampp folder and execute the xampp-control.exe

Press the start Button at the mysql row.

enter image description here

Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.

But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost or 127.0.0.1 in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.

Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.

enter image description here

how to find my angular version in my project?

  1. Browser > Inspect > Element >

    <.app-root _nghost-hey-c0="" ng-version="8.2.11">

  2. In terminal

    :> ng version
    :> ng --version
    :> ng -v

How do I obtain a Query Execution Plan in SQL Server?

You can also do it via powershell using SET STATISTICS XML ON to get the actual plan. I've written it so that it merges multi-statement plans into one plan;

    ########## BEGIN : SCRIPT VARIABLES #####################
    [string]$server = '.\MySQLServer'
    [string]$database = 'MyDatabase'
    [string]$sqlCommand = 'EXEC sp_ExampleSproc'
    [string]$XMLOutputFileName = 'sp_ExampleSproc'
    [string]$XMLOutputPath = 'C:\SQLDumps\ActualPlans\'
    ########## END   : SCRIPT VARIABLES #####################

    #Set up connection
    $connectionString = "Persist Security Info=False;Integrated Security=true;Connection Timeout=0;Initial Catalog=$database;Server=$server"
    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)

    #Set up commands
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
    $command.CommandTimeout = 0
    $commandXMLActPlanOn = new-object system.data.sqlclient.sqlcommand("SET STATISTICS XML ON",$connection)
    $commandXMLActPlanOff = new-object system.data.sqlclient.sqlcommand("SET STATISTICS XML OFF",$connection)

    $connection.Open()

    #Enable session XML plan
    $result = $commandXMLActPlanOn.ExecuteNonQuery()

    #Execute SP and return resultsets into a dataset
    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataSet) | Out-Null

    #Set up output file name and path
    [string]$fileNameDateStamp = get-date -f yyyyMMdd_HHmmss
    [string]$XMLOutputFilePath = "$XMLOutputPath$XMLOutputFileName`_$fileNameDateStamp.sqlplan"

    #Pull XML plans out of dataset and merge into one multi-statement plan
    [int]$cntr = 1
    ForEach($table in $dataset.Tables)
    {
            if($table.Columns[0].ColumnName -eq "Microsoft SQL Server 2005 XML Showplan")
            {

                [string]$fullXMLPlan = $Table.rows[0]."Microsoft SQL Server 2005 XML Showplan"

                if($cntr -eq 1)
                    {

                    [regex]$rx = "\<ShowPlanXML xmlns\=.{1,}\<Statements\>"
                    [string]$startXMLPlan = $rx.Match($fullXMLPlan).Value
                    [regex]$rx = "\<\/Statements\>.{1,}\<\/ShowPlanXML\>"
                    [string]$endXMLPlan = $rx.Match($fullXMLPlan).Value

                    $startXMLPlan | out-file -Append -FilePath $XMLOutputFilePath

                    }

                [regex]$rx = "\<StmtSimple.{1,}\<\/StmtSimple\>"
                [string]$bodyXMLPlan = $rx.Match($fullXMLPlan).Value

                $bodyXMLPlan | out-file -Append -FilePath $XMLOutputFilePath

                $cntr += 1
            } 
    }

    $endXMLPlan | out-file -Append -FilePath $XMLOutputFilePath

    #Disable session XML plan
    $result = $commandXMLActPlanOff.ExecuteNonQuery()

    $connection.Close()

What does the ">" (greater-than sign) CSS selector mean?

It matches p elements with class some_class that are directly under a div.

What are the benefits to marking a field as `readonly` in C#?

There is a potential case where the compiler can make a performance optimization based on the presence of the readonly keyword.

This only applies if the read-only field is also marked as static. In that case, the JIT compiler can assume that this static field will never change. The JIT compiler can take this into account when compiling the methods of the class.

A typical example: your class could have a static read-only IsDebugLoggingEnabled field that is initialized in the constructor (e.g. based on a configuration file). Once the actual methods are JIT-compiled, the compiler may omit whole parts of the code when debug logging is not enabled.

I have not checked if this optimization is actually implemented in the current version of the JIT compiler, so this is just speculation.

How to make google spreadsheet refresh itself every 1 minute?

If you're on the New Google Sheets, this is all you need to do, according to the docs:

change your recalculation setting to "On change and every minute" in your spreadsheet at File > Spreadsheet settings.

This will make the entire sheet update itself every minute, on the server side, regardless of whether you have the spreadsheet up in your browser or not.

If you're on the old Google Sheets, you'll want to add a cell with this formula to achieve the same functionality:

=GoogleClock()

EDIT to include old and new Google Sheets and change to =GoogleClock().

How can I convert uppercase letters to lowercase in Notepad++

In my notepad++ I press

Ctrl+A = To select all words

Ctrl+U = To convert lowercase

Ctrl+Shift+U = To convert uppercase

Hope to help you!

How do I wrap text in a span?

Try putting your text in another div inside your span:

i.e.

<span><div>some text</div></span>

Android SQLite: Update Statement

you can always execute SQL.

update [your table] set [your column]=value

for example

update Foo set Bar=125

REST / SOAP endpoints for a WCF service

You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>

An example of endpoint configuration in your scenario is

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>

so, the service will be available at

Apply [WebGet] to the operation contract to make it RESTful. e.g.

public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}

Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.

Reply to the post for SOAP and RESTful POX(XML)

For plain old XML as return format, this is an example that would work both for SOAP and XML.

[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}

POX behavior for REST Plain Old XML

<behavior name="poxBehavior">
  <webHttp/>
</behavior>

Endpoints

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>

Service will be available at

REST request try it in browser,

http://www.example.com/xml/accounts/A123

SOAP request client endpoint configuration for SOAP service after adding the service reference,

  <client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>

in C#

TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");

Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.

Angular 2: import external js file into component

After wasting a lot of time in finding its solution, I've found one. For your convenience I've used the complete code that you can replace your whole file with.

This is a general answer. Let's say you want to import a file named testjs.js into your angular 2 component. Create testjs.js in your assets folder:

assets > testjs.js

function test(){
    alert('TestingFunction')
}

include testjs.js in your index.html

index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Project1</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <script src="./assets/testjs.js"></script>

</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

In your app.component.ts or in any component.ts file where you want to call this js declare a variable and call the function like below:

app.component.ts

import { Component } from '@angular/core';

declare var test: any;


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app works!';


  f(){
    new test();
  }
}

Finally in your app.component.html test the function

app.component.html

<h1>
  <button (click)='f()'>Test</button>
</h1>

How to configure slf4j-simple

This is a sample simplelogger.properties which you can place on the classpath (uncomment the properties you wish to use):

# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.

# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info

# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=

# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false

# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z

# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true

# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true

# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false

What does "export default" do in JSX?

export default is used to export a single class, function or primitive from a script file.

The export can also be written as

export default class HelloWorld extends React.Component {
  render() {
    return <p>Hello, world!</p>;
  }
}

You could also write this as a function component like

export default const HelloWorld = () => (<p>Hello, world!</p>);

This is used to import this function in another script file

import HelloWorld from './HelloWorld';

You don't necessarily import it as HelloWorld you can give it any name as it's a default export

A little about export

As the name says, it's used to export functions, objects, classes or expressions from script files or modules

Utiliites.js

export function cube(x) {
  return x * x * x;
}
export const foo = Math.PI + Math.SQRT2;

This can be imported and used as

App.js

import { cube, foo } from 'Utilities';
console.log(cube(3)); // 27
console.log(foo);    // 4.555806215962888

Or

import * as utilities from 'Utilities';
console.log(utilities.cube(3)); // 27
console.log(utilities.foo);    // 4.555806215962888

When export default is used, this is much simpler. Script files just exports one thing. cube.js

export default function cube(x) {
  return x * x * x;
};

and used as App.js

import Cube from 'cube';
console.log(Cube(3)); // 27

Creating a blocking Queue<T> in .NET?

Well, you might look at System.Threading.Semaphore class. Other than that - no, you have to make this yourself. AFAIK there is no such built-in collection.

In Bash, how do I add a string after each line in a file?

If you have it, the lam (laminate) utility can do it, for example:

$ lam filename -s "string after each line"

How to extract Month from date in R

you can convert it into date format by-

new_date<- as.Date(old_date, "%m/%d/%Y")} 

from new_date, you can get the month by strftime()

month<- strftime(new_date, "%m")

old_date<- "01/01/1979"
new_date<- as.Date(old_date, "%m/%d/%Y")
new_date
#[1] "1979-01-01"
month<- strftime(new_date,"%m")
month
#[1] "01"
year<- strftime(new_date, "%Y")
year
#[1] "1979"

How to set javascript variables using MVC4 with Razor

I use a very simple function to solve syntax errors in body of JavaScript codes that mixed with Razor codes ;)

function n(num){return num;}

var nonID = n(@nonProID);
var proID= n(@proID);

Python - Using regex to find multiple matches and print them out

Instead of using re.search use re.findall it will return you all matches in a List. Or you could also use re.finditer (which i like most to use) it will return an Iterator Object and you can just use it to iterate over all found matches.

line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
    print match.group(1)

cocoapods - 'pod install' takes forever

This is what worked for me :

  1. Delete all the content under ~/.CocoaPods
  2. Delete your existing Podfile.lock and Pods folder.
  3. Leave your PodFile intact.
  4. Run sudo gem install cocoapods --verbose
  5. Run pod install --verbose

I recommend using the --verbose flag since Terminal is not great when giving progress on a command action. The verbose option helps a lot!

Download multiple files with a single action

_x000D_
_x000D_
var links = [_x000D_
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.exe',_x000D_
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.dmg',_x000D_
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar'_x000D_
];_x000D_
_x000D_
function downloadAll(urls) {_x000D_
  var link = document.createElement('a');_x000D_
_x000D_
  link.setAttribute('download', null);_x000D_
  link.style.display = 'none';_x000D_
_x000D_
  document.body.appendChild(link);_x000D_
_x000D_
  for (var i = 0; i < urls.length; i++) {_x000D_
    link.setAttribute('href', urls[i]);_x000D_
    link.click();_x000D_
  }_x000D_
_x000D_
  document.body.removeChild(link);_x000D_
}
_x000D_
<button onclick="downloadAll(window.links)">Test me!</button>
_x000D_
_x000D_
_x000D_

Python pandas: how to specify data types when reading an Excel file?

The read_excel() function has a converters argument, where you can apply functions to input in certain columns. You can use this to keep them as strings. Documentation:

Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the Excel cell content, and return the transformed content.

Example code:

pandas.read_excel(my_file, converters = {my_str_column: str})

MongoDB - admin user not authorized

It's a simple question.

  1. It's important that you must switch the target db NOT admin.

use yourDB

  1. check your db authentication by

show users

  1. If you get a {} empty object that is the question. You just need to type

db.createUser( { user: "yourUser", pwd: "password", roles: [ "readWrite", "dbAdmin" ] } )

or

db.grantRolesToUser('yourUser',[{ role: "dbAdmin", db: "yourDB" }])

MySQL "NOT IN" query

NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL in MySQL

MySQL, as well as all other systems except SQL Server, is able to optimize LEFT JOIN / IS NULL to return FALSE as soon the matching value is found, and it is the only system that cared to document this behavior. […] Since MySQL is not capable of using HASH and MERGE join algorithms, the only ANTI JOIN it is capable of is the NESTED LOOPS ANTI JOIN

[…]

Essentially, [NOT IN] is exactly the same plan that LEFT JOIN / IS NULL uses, despite the fact these plans are executed by the different branches of code and they look different in the results of EXPLAIN. The algorithms are in fact the same in fact and the queries complete in same time.

[…]

It’s hard to tell exact reason for [performance drop when using NOT EXISTS], since this drop is linear and does not seem to depend on data distribution, number of values in both tables etc., as long as both fields are indexed. Since there are three pieces of code in MySQL that essentialy do one job, it is possible that the code responsible for EXISTS makes some kind of an extra check which takes extra time.

[…]

MySQL can optimize all three methods to do a sort of NESTED LOOPS ANTI JOIN. […] However, these three methods generate three different plans which are executed by three different pieces of code. The code that executes EXISTS predicate is about 30% less efficient […]

That’s why the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS.

(emphases added)

HTTP Error 500.30 - ANCM In-Process Start Failure

This publish profile setting fixed for me:

Configure Publish Profile -> Settings -> Site Extensions Options ->

  • [x] Install ASP.NET Core Site Extension.

Pandas count(distinct) equivalent

Using crosstab, this will return more information than groupby nunique

pd.crosstab(df.YEARMONTH,df.CLIENTCODE)
Out[196]: 
CLIENTCODE  1  2  3
YEARMONTH          
201301      2  1  0
201302      1  2  1

After a little bit modify ,yield the result

pd.crosstab(df.YEARMONTH,df.CLIENTCODE).ne(0).sum(1)
Out[197]: 
YEARMONTH
201301    2
201302    3
dtype: int64

Displaying Windows command prompt output and redirecting it to a file

Here's a sample of what I've used based on one of the other answers

@echo off
REM SOME CODE
set __ERROR_LOG=c:\errors.txt
REM set __IPADDRESS=x.x.x.x

REM Test a variable
if not defined __IPADDRESS (
     REM Call function with some data and terminate
     call :TEE %DATE%,%TIME%,IP ADDRESS IS NOT DEFINED
     goto :EOF
)

REM If test happens to be successful, TEE out a message and end script.
call :TEE Script Ended Successful
goto :EOF


REM THE TEE FUNCTION
:TEE
for /f "tokens=*" %%Z in ("%*") do (
     >  CON ECHO.%%Z
     >> "%__ERROR_LOG%" ECHO.%%Z
     goto :EOF
)

Convert InputStream to byte array in Java

The other case to get correct byte array via stream, after send request to server and waiting for the response.

/**
         * Begin setup TCP connection to PC app
         * to open integrate connection between mobile app and pc app (or mobile app)
         */
        mSocket = new Socket(IP, port);
       // mSocket.setSoTimeout(30000);

        DataOutputStream mDos = new DataOutputStream(mSocket.getOutputStream());

        String str = "MobileRequest#" + params[0] + "#<EOF>";

        mDos.write(str.getBytes());

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /* Since data are accepted as byte, all of them will be collected in the
        following byte array which initialised with accepted data length. */
        DataInputStream mDis = new DataInputStream(mSocket.getInputStream());
        byte[] data = new byte[mDis.available()];

        // Collecting data into byte array
        for (int i = 0; i < data.length; i++)
            data[i] = mDis.readByte();

        // Converting collected data in byte array into String.
        String RESPONSE = new String(data);