Programs & Examples On #Android internet

Http Get using Android HttpURLConnection

Simple and Efficient Solution : use Volley

 StringRequest stringRequest = new StringRequest(Request.Method.GET, finalUrl ,
           new Response.Listener<String>() {
                    @Override
                    public void onResponse(String){
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            HashMap<String, Object> responseHashMap = new HashMap<>(Utility.toMap(jsonObject)) ;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("api", error.getMessage().toString());
            }
        });

        RequestQueue queue = Volley.newRequestQueue(context) ;
        queue.add(stringRequest) ;

Detect if Android device has Internet connection

You can do this with very simple class.

class CheckInternet {
    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
        val activeNetworkInfo = connectivityManager!!.activeNetworkInfo
        return activeNetworkInfo != null && activeNetworkInfo.isConnected
    }
}

Now you can check this from any class.

if (CheckInternet().isNetworkAvailable(this)) {
  //connected with internet
}else{
  //Not connected with internet
}

Detect whether there is an Internet connection available on Android

I check for both Wi-fi and Mobile internet as follows...

private boolean haveNetworkConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}

Obviously, It could easily be modified to check for individual specific connection types, e.g., if your app needs the potentially higher speeds of Wi-fi to work correctly etc.

JQuery How to extract value from href tag?

if ($('a').on('Clicked').text().search('1') == -1)
{
    //Page == 1
}
else
{
    //Page != 1
}

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Setup for Linux/Ubuntu/Mint

  1. download Android Studio or SDK only
  2. install
  3. set PATH

3.1) Open terminal and edit ~/.bashrc

sudo su
vim ~/.bashrc

3.2) Export ANDROID_HOME and add folders with binaries to your PATH

Common default install folders:

  • /root/Android/Sdk
  • ~/Android/Sdk

Example .bashrc

export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools
PATH=$PATH:$ANDROID_HOME/platform-tools

3.3) Refresh your PATH

source ~/.bashrc

4) Install correct SDK

When ionic build android still fails it could be because of wrong sdk version. To install correct versions and images run android from command line. Since it is now in your PATH you should be able to run it from anywhere.

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

how to parse JSONArray in android

getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for

{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"

but you need to get into the array and then do a search for "characters"

try this

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";

    JSONObject jsonResponse;
    try {
        ArrayList<String> temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters");
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

checked it :)

What is the difference between . (dot) and $ (dollar sign)?

A great way to learn more about anything (any function) is to remember that everything is a function! That general mantra helps, but in specific cases like operators, it helps to remember this little trick:

:t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c

and

:t ($)
($) :: (a -> b) -> a -> b

Just remember to use :t liberally, and wrap your operators in ()!

Codeigniter $this->input->post() empty while $_POST is working correctly

You are missing the parent constructor. When your controller is loaded you must Call the parent CI_Controller class constructor in your controller constructor

Eclipse : Failed to connect to remote VM. Connection refused.

when you have Failed to connect to remote VM Connection refused error, restart your eclipse

CSS to select/style first word

I have to disagree with Dale... The strong element is actually the wrong element to use, implying something about the meaning, use, or emphasis of the content while you are simply intending to provide style to the element.

Ideally you would be able to accomplish this with a pseudo-class and your stylesheet, but as that is not possible you should make your markup semantically correct and use <span class="first-word">.

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

addID in jQuery?

Like this :

var id = $('div.foo').attr('id');
$('div.foo').attr('id', id + ' id_adding');
  1. get actual ID
  2. put actuel ID and add the new one

How to create multiple class objects with a loop in python?

Creating a dictionary as it has mentioned, but in this case each key has the name of the object name that you want to create. Then the value is set as the class you want to instantiate, see for example:

class MyClass:
   def __init__(self, name):
       self.name = name
       self.checkme = 'awesome {}'.format(self.name)
...

instanceNames = ['red', 'green', 'blue']

# Here you use the dictionary
holder = {name: MyClass(name=name) for name in instanceNames}

Then you just call the holder key and you will have all the properties and methods of your class available for you.

holder['red'].checkme

output:

'awesome red'

How to retrieve form values from HTTPPOST, dictionary or?

The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.


Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.

<input type="hidden"   name="TrackingID" 
<input type="text"     name="FirstName"  id="firstnametext" />
<input type="checkbox" name="IsLegal"  value="Do you accept terms and conditions?" />

Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string is nullable)) otherwise the AJAX or POST back will fail.

[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
    MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}

You can also post back a model without using any razor helpers. I have come across that this is needed some times.

public Class HomeModel
{
  public int HouseNumber { get; set; }
  public string StreetAddress { get; set; }
}

The HTML markup will simply be ...

<input type="text" name="variableName.HouseNumber" id="whateverid" >

and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.

[HttpPost]
public ActionResult PostBack(HomeModel variableName){
    postBack.HouseNumber; //The value user entered
    postBack.StreetAddress; //the default value of NULL.
}

When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.

TIP: The name of the parameter in the controller is the name defined in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !


Using List<> is bit more complex in its mark-up.

<input type="text" name="variableNameHere[0].HouseNumber" id="id"           value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber"                   value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">

Index on List<> MUST always be zero based and sequential. 0,1,2,3.

[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
     int counter = MyHomes.Count()
     foreach(var home in MyHomes)
     { ... }
}

Using IEnumerable<> for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.

<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id"      value="3">

<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3"   value="4">

<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23"    value="5">

And the code just needs to use IEnumerable and call ToList()

[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
     int counter = variableNameHere.ToList().Count()
     foreach(var home in variableNameHere)
     { ... }
}

It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.

So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.

How to display errors for my MySQLi query?

Just simply add or die(mysqli_error($db)); at the end of your query, this will print the mysqli error.

 mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));

As a side note I'd say you are at risk of mysql injection, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.

fast way to copy formatting in excel

Just use the NumberFormat property after the Value property: In this example the Ranges are defined using variables called ColLetter and SheetRow and this comes from a for-next loop using the integer i, but they might be ordinary defined ranges of course.

TransferSheet.Range(ColLetter & SheetRow).Value = Range(ColLetter & i).Value TransferSheet.Range(ColLetter & SheetRow).NumberFormat = Range(ColLetter & i).NumberFormat

Converting a date in MySQL from string field

This:

STR_TO_DATE(t.datestring, '%d/%m/%Y')

...will convert the string into a datetime datatype. To be sure that it comes out in the format you desire, use DATE_FORMAT:

DATE_FORMAT(STR_TO_DATE(t.datestring, '%d/%m/%Y'), '%Y-%m-%d')

If you can't change the datatype on the original column, I suggest creating a view that uses the STR_TO_DATE call to convert the string to a DateTime data type.

How to convert a multipart file to File?

The answer by Alex78191 has worked for me.

public File getTempFile(MultipartFile multipartFile)
{

CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
FileItem fileItem = commonsMultipartFile.getFileItem();
DiskFileItem diskFileItem = (DiskFileItem) fileItem;
String absPath = diskFileItem.getStoreLocation().getAbsolutePath();
File file = new File(absPath);

//trick to implicitly save on disk small files (<10240 bytes by default)

if (!file.exists()) {
    file.createNewFile();
    multipartFile.transferTo(file);
}

return file;
}

For uploading files having size greater than 10240 bytes please change the maxInMemorySize in multipartResolver to 1MB.

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size t 20MB -->
<property name="maxUploadSize" value="20971520" />
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" />
<!-- 1MB --> </bean>

Substring with reverse index

Although this is an old question, to support answer by user187291

In case of fixed length of desired substring I would use substr() with negative argument for its short and readable syntax

"xxx_456".substr(-3)

For now it is compatible with common browsers and not yet strictly deprecated.

What is the purpose of flush() in Java streams?

In addition to other good answers here, this explanation made things crystal clear for me:

A buffer is a portion in memory that is used to store a stream of data (characters). These characters sometimes will only get sent to an output device (e.g. monitor) when the buffer is full or meets a certain number of characters. This can cause your system to lag if you just have a few characters to send to an output device. The flush() method will immediately flush the contents of the buffer to the output stream.

Source: https://www.youtube.com/watch?v=MjK3dZTc0Lg

Loop through each cell in a range of cells when given a Range object

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Cells
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

How to get client IP address in Laravel 5+

You can get a few way ip address utilizing Request ip, Request getClientIp and solicitation partner work. In this model, I will tell you the best way to get current client ip address in laravel 5.8.

$clientIP = request()->ip();

dd($clientIP);

You can follow this from here

Python Database connection Close

Connections have a close method as specified in PEP-249 (Python Database API Specification v2.0):

import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
csr.close()
conn.close()     #<--- Close the connection

Since the pyodbc connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:

import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 
with conn:
    crs = conn.cursor()
    do_stuff
    # conn.commit() will automatically be called when Python leaves the outer `with` statement
    # Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!! 

See https://github.com/mkleehammer/pyodbc/issues/43 for an explanation for why conn.close() is not called.

Note that unlike the original code, this causes conn.commit() to be called. Use the outer with statement to control when you want commit to be called.


Also note that regardless of whether or not you use the with statements, per the docs,

Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [conn.close()], but you can explicitly close the connection if you wish.

and similarly for cursors (my emphasis):

Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [csr.close()] is not usually necessary.

Switch firefox to use a different DNS than what is in the windows.host file

DNS resolving is usually done at the system level and not at the application level, so you can't normally have one program use one dns and another program use a different dns. I'm not aware of any firefox extensions that allow you to use a different dns.

Regex to check whether a string contains only numbers

If you need just positive integer numbers and don't need leading zeros (e.g. "0001234" or "00"):

var reg = /^(?:[1-9]\d*|\d)$/;

Encode String to UTF-8

In a moment I went through this problem and managed to solve it in the following way

first i need to import

import java.nio.charset.Charset;

Then i had to declare a constant to use UTF-8 and ISO-8859-1

private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Charset ISO = Charset.forName("ISO-8859-1");

Then I could use it in the following way:

String textwithaccent="Thís ís a text with accent";
String textwithletter="Ñandú";

text1 = new String(textwithaccent.getBytes(ISO), UTF_8);
text2 = new String(textwithletter.getBytes(ISO),UTF_8);

Simple URL GET/POST function in Python

I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)

#!/usr/bin/env python3
import http.client
import json

print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)


print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)


print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)


print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)

Delete a row from a table by id

to Vilx-:

var table = row.parentNode;
while ( table && table.tagName != 'TABLE' )
    table = table.parentNode;

and what if row.parentNode is TBODY?

You should check it out first, and after that do while by .tBodies, probably

ImportError: DLL load failed: The specified module could not be found

I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: https://www.microsoft.com/en-us/download/details.aspx?id=48145 fixed the missing DLLs.

I find it better and easier than downloading and pasting DLLs.

Find the files that have been changed in last 24 hours

Another, more humane way:

find /<directory> -newermt "-24 hours" -ls

or:

find /<directory> -newermt "1 day ago" -ls

or:

find /<directory> -newermt "yesterday" -ls

TypeError: unsupported operand type(s) for /: 'str' and 'str'

The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.

So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.

One way to convert a string to an integer is to use the int function. For example:

percent = (int(pyc) / int(tpy)) * 100

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

Added MSSQLSERVER full access to the folder, diskadmin and bulkadmin server roles.

In my c# application, when preparing for the bulk insert command,

string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And I get this error - Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 8 (STATUS).

I looked at my logfile and found that the terminator becomes ' ' instead of '\n'. The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error:

Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)". Query :BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\NEWSTAGEWWW\CalAtlasToPWCR\Results\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', **ROWTERMINATOR = ''**)

So I added extra escape to the rowterminator - string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And now it inserts successfully.

Bulk Insert SQL -   --->  BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\\NEWSTAGEWWW\\CalAtlasToPWCR\\Results\\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
Bulk Insert to PWCR_Contractor_vw_TEST successful...  --->  clsDatase.PerformBulkInsert

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

Parsing ISO 8601 date in Javascript

If you want to keep it simple, this should suffice:

function parseIsoDatetime(dtstr) {
    var dt = dtstr.split(/[: T-]/).map(parseFloat);
    return new Date(dt[0], dt[1] - 1, dt[2], dt[3] || 0, dt[4] || 0, dt[5] || 0, 0);
}

note parseFloat is must, parseInt doesn't always work. Map requires IE9 or later.

Works for formats:

  • 2014-12-28 15:30:30
  • 2014-12-28T15:30:30
  • 2014-12-28

Not valid for timezones, see other answers about those.

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

grid is not a global, it is local to the main function. Change this:

int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int row, int column)

to this:

int nonrecursivecountcells(color grid[ROW_SIZE][COL_SIZE], int row, int column)

Basically you forgot to give that first param a name, grid will do since it matches your code.

web.xml is missing and <failOnMissingWebXml> is set to true

Do this:

Go and right click on Deployment Descriptor and click Generate Deployment Descriptor Stub.

Make hibernate ignore class variables that are not mapped

JPA will use all properties of the class, unless you specifically mark them with @Transient:

@Transient
private String agencyName;

The @Column annotation is purely optional, and is there to let you override the auto-generated column name. Furthermore, the length attribute of @Column is only used when auto-generating table definitions, it has no effect on the runtime.

What should I use to open a url instead of urlopen in urllib3

In urlip3 there's no .urlopen, instead try this:

import requests
html = requests.get(url)

How do I create a comma-separated list using a SQL query?

MySQL

  SELECT r.name,
         GROUP_CONCAT(a.name SEPARATOR ',')
    FROM RESOURCES r
    JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
    JOIN APPLICATIONS a ON a.id = ar.app_id
GROUP BY r.name

**


MS SQL Server

SELECT r.name,
       STUFF((SELECT ','+ a.name
               FROM APPLICATIONS a
               JOIN APPLICATIONRESOURCES ar ON ar.app_id = a.id
              WHERE ar.resource_id = r.id
           GROUP BY a.name
            FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, '')
 FROM RESOURCES r
 GROUP BY deptno;

Oracle

  SELECT r.name,
         LISTAGG(a.name SEPARATOR ',') WITHIN GROUP (ORDER BY a.name)
  FROM RESOURCES r
        JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
        JOIN APPLICATIONS a ON a.id = ar.app_id
  GROUP BY r.name;

When do you use the "this" keyword?

Never. Ever. If you have variable shadowing, your naming conventions are on crack. I mean, really, no distinguishing naming for member variables? Facepalm

What's the Android ADB shell "dumpsys" tool and what are its benefits?

What's dumpsys and what are its benefit

dumpsys is an android tool that runs on the device and dumps interesting information about the status of system services.

Obvious benefits:

  1. Possibility to easily get system information in a simple string representation.
  2. Possibility to use dumped CPU, RAM, Battery, storage stats for a pretty charts, which will allow you to check how your application affects the overall device!

What information can we retrieve from dumpsys shell command and how we can use it

If you run dumpsys you would see a ton of system information. But you can use only separate parts of this big dump.

to see all of the "subcommands" of dumpsys do:

dumpsys | grep "DUMP OF SERVICE"

Output:

DUMP OF SERVICE SurfaceFlinger:
DUMP OF SERVICE accessibility:
DUMP OF SERVICE account:
DUMP OF SERVICE activity:
DUMP OF SERVICE alarm:
DUMP OF SERVICE appwidget:
DUMP OF SERVICE audio:
DUMP OF SERVICE backup:
DUMP OF SERVICE battery:
DUMP OF SERVICE batteryinfo:
DUMP OF SERVICE clipboard:
DUMP OF SERVICE connectivity:
DUMP OF SERVICE content:
DUMP OF SERVICE cpuinfo:
DUMP OF SERVICE device_policy:
DUMP OF SERVICE devicestoragemonitor:
DUMP OF SERVICE diskstats:
DUMP OF SERVICE dropbox:
DUMP OF SERVICE entropy:
DUMP OF SERVICE hardware:
DUMP OF SERVICE input_method:
DUMP OF SERVICE iphonesubinfo:
DUMP OF SERVICE isms:
DUMP OF SERVICE location:
DUMP OF SERVICE media.audio_flinger:
DUMP OF SERVICE media.audio_policy:
DUMP OF SERVICE media.player:
DUMP OF SERVICE meminfo:
DUMP OF SERVICE mount:
DUMP OF SERVICE netstat:
DUMP OF SERVICE network_management:
DUMP OF SERVICE notification:
DUMP OF SERVICE package:
DUMP OF SERVICE permission:
DUMP OF SERVICE phone:
DUMP OF SERVICE power:
DUMP OF SERVICE reboot:
DUMP OF SERVICE screenshot:
DUMP OF SERVICE search:
DUMP OF SERVICE sensor:
DUMP OF SERVICE simphonebook:
DUMP OF SERVICE statusbar:
DUMP OF SERVICE telephony.registry:
DUMP OF SERVICE throttle:
DUMP OF SERVICE usagestats:
DUMP OF SERVICE vibrator:
DUMP OF SERVICE wallpaper:
DUMP OF SERVICE wifi:
DUMP OF SERVICE window:

Some Dumping examples and output

1) Getting all possible battery statistic:

$~ adb shell dumpsys battery

You will get output:

Current Battery Service state:
AC powered: false
AC capacity: 500000
USB powered: true
status: 5
health: 2
present: true
level: 100
scale: 100
voltage:4201
temperature: 271 <---------- Battery temperature! %)
technology: Li-poly <---------- Battery technology! %)

2)Getting wifi informations

~$ adb shell dumpsys wifi

Output:

Wi-Fi is enabled
Stay-awake conditions: 3

Internal state:
interface tiwlan0 runState=Running
SSID: XXXXXXX BSSID: xx:xx:xx:xx:xx:xx, MAC: xx:xx:xx:xx:xx:xx, Supplicant state: COMPLETED, RSSI: -60, Link speed: 54, Net ID: 2, security: 0, idStr: null
ipaddr 192.168.1.xxx gateway 192.168.x.x netmask 255.255.255.0 dns1 192.168.x.x dns2 8.8.8.8 DHCP server 192.168.x.x lease 604800 seconds
haveIpAddress=true, obtainingIpAddress=false, scanModeActive=false
lastSignalLevel=2, explicitlyDisabled=false

Latest scan results:

Locks acquired: 28 full, 0 scan
Locks released: 28 full, 0 scan

Locks held:

3) Getting CPU info

~$ adb shell dumpsys cpuinfo

Output:

Load: 0.08 / 0.4 / 0.64
CPU usage from 42816ms to 34683ms ago:
system_server: 1% = 1% user + 0% kernel / faults: 16 minor
kdebuglog.sh: 0% = 0% user + 0% kernel / faults: 160 minor
tiwlan_wq: 0% = 0% user + 0% kernel
usb_mass_storag: 0% = 0% user + 0% kernel
pvr_workqueue: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
TOTAL: 6% = 1% user + 3% kernel + 0% irq

4)Getting memory usage informations

~$ adb shell dumpsys meminfo 'your apps package name'

Output:

** MEMINFO in pid 5527 [com.sec.android.widgetapp.weatherclock] **
                    native   dalvik    other    total
            size:     2868     5767      N/A     8635
       allocated:     2861     2891      N/A     5752
            free:        6     2876      N/A     2882
           (Pss):      532       80     2479     3091
  (shared dirty):      932     2004     6060     8996
    (priv dirty):      512       36     1872     2420

 Objects
           Views:        0        ViewRoots:        0
     AppContexts:        0       Activities:        0
          Assets:        3    AssetManagers:        3
   Local Binders:        2    Proxy Binders:        8
Death Recipients:        0
 OpenSSL Sockets:        0


 SQL
               heap:        0         MEMORY_USED:        0
 PAGECACHE_OVERFLOW:        0         MALLOC_SIZE:        0

If you want see the info for all processes, use ~$ adb shell dumpsys meminfo

enter image description here

dumpsys is ultimately flexible and useful tool!

If you want to use this tool do not forget to add permission into your android manifest automatically android.permission.DUMP

Try to test all commands to learn more about dumpsys. Happy dumping!

How to get a table creation script in MySQL Workbench?

To get an individual table's creation script just right click on the table name and click Copy to Clipboard > Create Statement.

To enable the File > Forward Engineering SQL_CREATE Script.. option and to get the creation script for your entire database :

  1. Database > Reverse Engineer (Ctrl+R)
  2. Go through the steps to create the EER Diagram
  3. When viewing the EER Diagram click File > Forward Engineering SQL_CREATE Script... (Ctrl+Shift+G)

Case insensitive string compare in LINQ-to-SQL

I tried this using Lambda expression, and it worked.

List<MyList>.Any (x => (String.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)) && (x.Type == qbType) );

How do you configure HttpOnly cookies in tomcat / java webapps?

For cookies that I am explicitly setting, I switched to use SimpleCookie provided by Apache Shiro. It does not inherit from javax.servlet.http.Cookie so it takes a bit more juggling to get everything to work correctly however it does provide a property set HttpOnly and it works with Servlet 2.5.

For setting a cookie on a response, rather than doing response.addCookie(cookie) you need to do cookie.saveTo(request, response).

Retrieve a single file from a repository

for bitbucket directly from browser (I used safari...) right-click on 'View Raw" and choose "Download Linked File":

enter image description here

Https to http redirect using htaccess

RewriteCond %{HTTP:X-Forwarded-Proto} =https

Add image in pdf using jspdf

maybe a little bit late, but I come to this situation recently and found a simple solution, 2 functions are needed.

  1. load the image.

    function getImgFromUrl(logo_url, callback) {
        var img = new Image();
        img.src = logo_url;
        img.onload = function () {
            callback(img);
        };
    } 
    
  2. in onload event on first step, make a callback to use the jspdf doc.

    function generatePDF(img){
        var options = {orientation: 'p', unit: 'mm', format: custom};
        var doc = new jsPDF(options);
        doc.addImage(img, 'JPEG', 0, 0, 100, 50);}
    
  3. use the above functions.

    var logo_url = "/images/logo.jpg";
    getImgFromUrl(logo_url, function (img) {
        generatePDF(img);
    });
    

How to echo text during SQL script execution in SQLPLUS

You can use SET ECHO ON in the beginning of your script to achieve that, however, you have to specify your script using @ instead of < (also had to add EXIT at the end):

test.sql

SET ECHO ON

SELECT COUNT(1) FROM dual;

SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

EXIT

terminal

sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log

test.log

SQL> 
SQL> SELECT COUNT(1) FROM dual;

  COUNT(1)
----------
     1

SQL> 
SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

  COUNT(1)
----------
     2

SQL> 
SQL> EXIT

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

In Python 3, you can only print as:

print("STRING")

But in Python 2, the parentheses are not necessary.

Is the Javascript date object always one day off?

You are using the ISO date string format which, according to this page, causes the date to be constructed using the UTC timezone:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

If you format the text differently, such as "Jan 01 1970", then (at least on my machine) it uses your local timezone.

Redis command to get all available keys?

Get All Keys In Redis

Get all keys using the --scan option:

$ redis-cli --scan --pattern '*'

List all keys using the KEYS command:

$ redis-cli KEYS '*'

How do I do pagination in ASP.NET MVC?

I think the easiest way to create pagination in ASP.NET MVC application is using PagedList library.

There is a complete example in following github repository. Hope it would help.

public class ProductController : Controller
{
    public object Index(int? page)
    {
        var list = ItemDB.GetListOfItems();

        var pageNumber = page ?? 1; 
        var onePageOfItem = list.ToPagedList(pageNumber, 25); // will only contain 25 items max because of the pageSize

        ViewBag.onePageOfItem = onePageOfProducts;
        return View();
    }
}

Demo Link: http://ajaxpagination.azurewebsites.net/

Source Code: https://github.com/ungleng/SimpleAjaxPagedListAndSearchMVC5

How do I horizontally center a span element inside a div

<div style="text-align:center">
    <span>Short text</span><br />
    <span>This is long text</span>
</div>

Select and trigger click event of a radio button in jquery

$("#radio1").attr('checked', true).trigger('click');

how to modify the size of a column

If you run it, it will work, but in order for SQL Developer to recognize and not warn about a possible error you can change it as:

ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(300));

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

I did this-

sudo mysql -p

then i gave password for my root account(password that we use for sudo)then it asked to enter password and i gave password for mysql terminal(new password).

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

"You tried to execute a query that does not include the specified aggregate function"

I had a similar problem in a MS-Access query, and I solved it by changing my equivalent fName to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any Group By clause at the end.enter image description here

How can I reuse a navigation bar on multiple pages?

I know this is a quite old question, but when you have JavaScript available you could use jQuery and its AJAX methods.

First, create a page with all the navigation bar's HTML content.

Next, use jQuery's $.get method to fetch the content of the page. For example, let's say you've put all the navigation bar's HTML into a file called navigation.html and added a placeholder tag (Like <div id="nav-placeholder">) in your index.html, then you would use the following code:

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$.get("navigation.html", function(data){
    $("#nav-placeholder").replaceWith(data);
});
</script>

Jquery how to find an Object by attribute in an Array

No need for jQuery.

JavaScript arrays have a find method, so you can achieve that in one line:

array.find((o) => { return o[propertyName] === propertyValue }

Example


const purposeObjects = [
    {purpose: "daily"},
    {purpose: "weekly"},
    {purpose: "monthly"}
];

purposeObjects.find((o) => { return o["purpose"] === "weekly" }

// output -> {purpose: "weekly"}

If you need IE compatibility, import this polyfill in your code.

Swift: Display HTML data in a label or textView

If you want HTML, with images and a list, this isn't support by UILabel. However, I've found YYText does the trick.

Combining two Series into a DataFrame in pandas

A simplification of the solution based on join():

df = a.to_frame().join(b)

How to convert a Drawable to a Bitmap?

very simple

Bitmap tempBMP = BitmapFactory.decodeResource(getResources(),R.drawable.image);

How to set specific window (frame) size in java swing?

Try this, but you can adjust frame size with bounds and edit title.

package co.form.Try;

import javax.swing.JFrame;

public class Form {

    public static void main(String[] args) {
        JFrame obj =new JFrame();
        obj.setBounds(10,10,700,600); 
        obj.setTitle("Application Form");
        obj.setResizable(false);                
        obj.setVisible(true);       
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Two of them always produce the same answer:

  • COUNT(*) counts the number of rows
  • COUNT(1) also counts the number of rows

Assuming the pk is a primary key and that no nulls are allowed in the values, then

  • COUNT(pk) also counts the number of rows

However, if pk is not constrained to be not null, then it produces a different answer:

  • COUNT(possibly_null) counts the number of rows with non-null values in the column possibly_null.

  • COUNT(DISTINCT pk) also counts the number of rows (because a primary key does not allow duplicates).

  • COUNT(DISTINCT possibly_null_or_dup) counts the number of distinct non-null values in the column possibly_null_or_dup.

  • COUNT(DISTINCT possibly_duplicated) counts the number of distinct (necessarily non-null) values in the column possibly_duplicated when that has the NOT NULL clause on it.

Normally, I write COUNT(*); it is the original recommended notation for SQL. Similarly, with the EXISTS clause, I normally write WHERE EXISTS(SELECT * FROM ...) because that was the original recommend notation. There should be no benefit to the alternatives; the optimizer should see through the more obscure notations.

java- reset list iterator to first element of the list

What you may actually want to use is an Iterable that can return a fresh Iterator multiple times by calling iterator().

//A function that needs to iterate multiple times can be given one Iterable:
public void func(Iterable<Type> ible) {
    Iterator<Type> it = ible.iterator(); //Gets an iterator
    while (it.hasNext()) {
        it.next();
    }
    it = ible.iterator(); //Gets a NEW iterator, also from the beginning
    while (it.hasNext()) {
        it.next();
    }
}

You must define what the iterator() method does just once beforehand:

void main() {
    LinkedList<String> list; //This could be any type of object that has an iterator
    //Define an Iterable that knows how to retrieve a fresh iterator
    Iterable<Type> ible = new Iterable<Type>() {
        @Override
        public Iterator<Type> iterator() {
            return list.listIterator(); //Define how to get a fresh iterator from any object
        }
    };
    //Now with a single instance of an Iterable,
    func(ible); //you can iterate through it multiple times.
}

Eclipse "Invalid Project Description" when creating new project from existing source

What operating system are you using? I use Linux Mint. In my case it turned out to be a symbolic link issue. Every time I tried to create the project with the symlink path, it would give me that error. Creating the project elsewhere, and then migrating it to the symlinked directory solved it for me.

How to get a value inside an ArrayList java

import java.util.*;
import java.lang.*;
import java.io.*;

class hari
{
public static void main (String[] args) throws Exception
{  Scanner s=new Scanner(System.in);
    int i=0;
    int b=0;
    HashSet<Integer> h=new HashSet<Integer>();
    try{
        for(i=0;i<1000;i++)
    {   b=s.nextInt();
        h.add(b);
    }
    }
    catch(Exception e){
        System.out.println(h+","+h.size());
    }
}}

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

DECLARE @day CHAR(2)

SET @day = right('0'+ cast(day(getdate())as nvarchar(2)),2)

print @day

Creating all possible k combinations of n items in C++

Here is an algorithm i came up with for solving this problem. You should be able to modify it to work with your code.

void r_nCr(const unsigned int &startNum, const unsigned int &bitVal, const unsigned int &testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)
{
    unsigned int n = (startNum - bitVal) << 1;
    n += bitVal ? 1 : 0;

    for (unsigned int i = log2(testNum) + 1; i > 0; i--) // Prints combination as a series of 1s and 0s
        cout << (n >> (i - 1) & 1);
    cout << endl;

    if (!(n & testNum) && n != startNum)
        r_nCr(n, bitVal, testNum);

    if (bitVal && bitVal < testNum)
        r_nCr(startNum, bitVal >> 1, testNum);
}

You can see an explanation of how it works here.

How to format a date using ng-model?

Use custom validation of forms http://docs.angularjs.org/guide/forms Demo: http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=preview

Directive using formaters and parsers and MomentJS )

angModule.directive('moDateInput', function ($window) {
    return {
        require:'^ngModel',
        restrict:'A',
        link:function (scope, elm, attrs, ctrl) {
            var moment = $window.moment;
            var dateFormat = attrs.moDateInput;
            attrs.$observe('moDateInput', function (newValue) {
                if (dateFormat == newValue || !ctrl.$modelValue) return;
                dateFormat = newValue;
                ctrl.$modelValue = new Date(ctrl.$setViewValue);
            });

            ctrl.$formatters.unshift(function (modelValue) {
                if (!dateFormat || !modelValue) return "";
                var retVal = moment(modelValue).format(dateFormat);
                return retVal;
            });

            ctrl.$parsers.unshift(function (viewValue) {
                var date = moment(viewValue, dateFormat);
                return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : "";
            });
        }
    };
});

Turn a simple socket into an SSL socket

For others like me:

There was once an example in the SSL source in the directory demos/ssl/ with example code in C++. Now it's available only via the history: https://github.com/openssl/openssl/tree/691064c47fd6a7d11189df00a0d1b94d8051cbe0/demos/ssl

You probably will have to find a working version, I originally posted this answer at Nov 6 2015. And I had to edit the source -- not much.

Certificates: .pem in demos/certs/apps/: https://github.com/openssl/openssl/tree/master/demos/certs/apps

"Find next" in Vim

As discussed, there are several ways to search:

/pattern
?pattern
* (and g*, which I sometimes use in macros)
# (and g#)

plus, navigating prev/next with N and n.

You can also edit/recall your search history by pulling up the search prompt with / and then cycle with C-p/C-n. Even more useful is q/, which takes you to a window where you can navigate the search history.

Also for consideration is the all-important 'hlsearch' (type :hls to enable). This makes it much easier to find multiple instances of your pattern. You might even want make your matches extra bright with something like:

hi Search ctermfg=yellow ctermbg=red guifg=...

But then you might go crazy with constant yellow matches all over your screen. So you’ll often find yourself using :noh. This is so common that a mapping is in order:

nmap <leader>z :noh<CR>

I easily remember this one as z since I used to constantly type /zz<CR> (which is a fast-to-type uncommon occurrence) to clear my highlighting. But the :noh mapping is way better.

How to use sys.exit() in Python

I think you can use

sys.exit(0)

You may check it here in the python 2.7 doc:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.

How to convert milliseconds into a readable date?

This is a solution. Later you can split by ":" and take the values of the array

 /**
 * Converts milliseconds to human readeable language separated by ":"
 * Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
 */
function dhm(t){
    var cd = 24 * 60 * 60 * 1000,
        ch = 60 * 60 * 1000,
        d = Math.floor(t / cd),
        h = '0' + Math.floor( (t - d * cd) / ch),
        m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    return [d, h.substr(-2), m.substr(-2)].join(':');
}

//Example
var delay = 190980000;                   
var fullTime = dhm(delay);
console.log(fullTime);

Using str_replace so that it only acts on the first match?

I created this little function that replaces string on string (case-sensitive) with limit, without the need of Regexp. It works fine.

function str_replace_limit($search, $replace, $string, $limit = 1) {
    $pos = strpos($string, $search);

    if ($pos === false) {
        return $string;
    }

    $searchLen = strlen($search);

    for ($i = 0; $i < $limit; $i++) {
        $string = substr_replace($string, $replace, $pos, $searchLen);

        $pos = strpos($string, $search);

        if ($pos === false) {
            break;
        }
    }

    return $string;
}

Example usage:

$search  = 'foo';
$replace = 'bar';
$string  = 'foo wizard makes foo brew for evil foo and jack';
$limit   = 2;

$replaced = str_replace_limit($search, $replace, $string, $limit);

echo $replaced;
// bar wizard makes bar brew for evil foo and jack

How to download and save an image in Android

this code perfectly run in my project

downloadImagesToSdCard(imagepath,imagepath);

private void downloadImagesToSdCard(String downloadUrl,String imageName)
        {
            try
            {
                URL url = new URL("www.xxx.com"+downloadUrl); 
                /* making a directory in sdcard */
            //  String sdCard=Environment.getExternalStorageDirectory().toString();
                ContextWrapper cw = new ContextWrapper(getActivity());
                 // path to /data/data/yourapp/app_data/imageDir
                File directory = cw.getDir("files", Context.MODE_PRIVATE);

                File myDir = new File(directory,"folder");

                /*  if specified not exist create new */
                if(!myDir.exists())
                {
                    myDir.mkdir();
                    Log.v("", "inside mkdir");
                }

                /* checks the file and if it already exist delete */
                String fname = imageName;
                File file = new File (myDir, fname);
                Log.d("file===========path", ""+file);
                if (file.exists ()) 
                    file.delete (); 

                /* Open a connection */
                URLConnection ucon = url.openConnection();
                InputStream inputStream = null;
                HttpURLConnection httpConn = (HttpURLConnection)ucon;
                httpConn.setRequestMethod("GET");
                httpConn.connect();
                inputStream = httpConn.getInputStream();
                /*if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) 
                {
                    inputStream = httpConn.getInputStream();
                }*/

                FileOutputStream fos = new FileOutputStream(file);  
                int totalSize = httpConn.getContentLength();
                int downloadedSize = 0;   
                byte[] buffer = new byte[1024];
                int bufferLength = 0;
                while ( (bufferLength = inputStream.read(buffer)) >0 ) 
                {                 
                    fos.write(buffer, 0, bufferLength);                  
                    downloadedSize += bufferLength;                 
                    Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
                }   

                fos.close();
                Log.d("test", "Image Saved in sdcard..");  
                viewimage();
            }
            catch(IOException io)
            {                  
                io.printStackTrace();
            }
            catch(Exception e)
            {                     
                e.printStackTrace();
            }


        } 

        public void viewimage()
        {
              String path = serialnumber+".png";
               ContextWrapper cw = new ContextWrapper(getActivity());

                //path to /data/data/yourapp/app_data/dirName
                File directory = cw.getDir("files", Context.MODE_PRIVATE);

                File mypath=new File(directory,"folder/"+path);

                Bitmap b;
                try {
                    b = BitmapFactory.decodeStream(new FileInputStream(mypath));
                //  b.compress(format, quality, stream)
                    profile_image.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }

Laravel Blade html image

In Laravel 5.x, you can also do like this .

<img class="img-responsive" src="{{URL::to('/')}}/img/stuvi-logo.png" alt=""/>

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I had the same problem in Xcode 8.1 and iOS 10.1. What worked for me was going into Simulator-> Hardware->Keyboard and unchecking Connect Hardware Keyboard.

Pretty Printing a pandas dataframe

I've just found a great tool for that need, it is called tabulate.

It prints tabular data and works with DataFrame.

from tabulate import tabulate
import pandas as pd

df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
                   'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})
print(tabulate(df, headers='keys', tablefmt='psql'))

+----+-----------+-------------+
|    |   col_two | column_3    |
|----+-----------+-------------|
|  0 |    0.0001 | ABCD        |
|  1 |    1e-05  | ABCD        |
|  2 |    1e-06  | long string |
|  3 |    1e-07  | ABCD        |
+----+-----------+-------------+

Note:

To suppress row indices for all types of data, pass showindex="never" or showindex=False.

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.

More details here.

How to compile or convert sass / scss to css with node-sass (no Ruby)?

I picked node-sass implementer for libsass because it is based on node.js.

Installing node-sass

  • (Prerequisite) If you don't have npm, install Node.js first.
  • $ npm install -g node-sass installs node-sass globally -g.

This will hopefully install all you need, if not read libsass at the bottom.

How to use node-sass from Command line and npm scripts

General format:

$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css

Examples:

  1. $ node-sass my-styles.scss my-styles.css compiles a single file manually.
  2. $ node-sass my-sass-folder/ -o my-css-folder/ compiles all the files in a folder manually.
  3. $ node-sass -w sass/ -o css/ compiles all the files in a folder automatically whenever the source file(s) are modified. -w adds a watch for changes to the file(s).

More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.

You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.

  • If there is no package.json file in your project directory running $ npm init will create one. Use it with -y to skip the questions.
  • Add "sass": "node-sass -w sass/ -o css/" to scripts in package.json file. It should look something like this:
"scripts": {
    "test" : "bla bla bla",
    "sass": "node-sass -w sass/ -o css/"
 }
  • $ npm run sass will compile your files.

How to use with gulp

  • $ npm install -g gulp installs Gulp globally.
  • If there is no package.json file in your project directory running $ npm init will create one. Use it with -y to skip the questions.
  • $ npm install --save-dev gulp installs Gulp locally. --save-dev adds gulp to devDependencies in package.json.
  • $ npm install gulp-sass --save-dev installs gulp-sass locally.
  • Setup gulp for your project by creating a gulpfile.js file in your project root folder with this content:
'use strict';
var gulp = require('gulp');

A basic example to transpile

Add this code to your gulpfile.js:

var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
  gulp.src('./sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

$ gulp sass runs the above task which compiles .scss file(s) in the sass folder and generates .css file(s) in the css folder.

To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js:

gulp.task('sass:watch', function () {
  gulp.watch('./sass/**/*.scss', ['sass']);
});

All is set now! Just run the watch task:

$ gulp sass:watch

How to use with Node.js

As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.

What about libsass?

Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:

LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.

Angular 2 - Checking for server errors from subscribe

As stated in the relevant RxJS documentation, the .subscribe() method can take a third argument that is called on completion if there are no errors.

For reference:

  1. [onNext] (Function): Function to invoke for each element in the observable sequence.
  2. [onError] (Function): Function to invoke upon exceptional termination of the observable sequence.
  3. [onCompleted] (Function): Function to invoke upon graceful termination of the observable sequence.

Therefore you can handle your routing logic in the onCompleted callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).

this.httpService.makeRequest()
    .subscribe(
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here
      }
    );

As a side note, there is also a .finally() method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).

Rx.Observable.prototype.finally(action)

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

For instance, here is a basic example:

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';

// ...

this.httpService.getRequest()
    .finally(() => {
      // Execute after graceful or exceptionally termination
      console.log('Handle logging logic...');
    })
    .subscribe (
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // No errors, route to new page
      }
    );

Display date/time in user's locale format and time offset

getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js.

There's a few more options discussed in the answer to this question

How do I get the APK of an installed app without root access?

Or you can get 'Bluetooth File Transfer' from Google Play and set the home folder to /system/ . Then you can even go to / .

What causing this "Invalid length for a Base-64 char array"

During initial testing for Membership.ValidateUser with a SqlMembershipProvider, I use a hash (SHA1) algorithm combined with a salt, and, if I changed the salt length to a length not divisible by four, I received this error.

I have not tried any of the fixes above, but if the salt is being altered, this may help someone pinpoint that as the source of this particular error.

How to check if a word is an English word with Python?

For All Linux/Unix Users

If your OS uses the Linux kernel, there is a simple way to get all the words from the English/American dictionary. In the directory /usr/share/dict you have a words file. There is also a more specific american-english and british-english files. These contain all of the words in that specific language. You can access this throughout every programming language which is why I thought you might want to know about this.

Now, for python specific users, the python code below should assign the list words to have the value of every single word:

import re
file = open("/usr/share/dict/words", "r")
words = re.sub("[^\w]", " ",  file.read()).split()

def is_word(word):
    return word.lower() in words

is_word("tarts") ## Returns true
is_word("jwiefjiojrfiorj") ## Returns False

Hope this helps!!!

Customize UITableView header section

If I were you, I would make a method which returns an UIView given a NSString to contain. For example

+ (UIView *) sectionViewWithTitle:(NSString *)title;

In the implementation of this method create a UIView, add a UILabel to it with the properties you want to set, and of course set its title to the given one.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

How to Convert string "07:35" (HH:MM) to TimeSpan

Try

var ts = TimeSpan.Parse(stringTime);

With a newer .NET you also have

TimeSpan ts;

if(!TimeSpan.TryParse(stringTime, out ts)){
     // throw exception or whatnot
}
// ts now has a valid format

This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.

How to run Unix shell script from Java code?

Just the same thing that Solaris 5.10 it works like this ./batchstart.sh there is a trick I don´t know if your OS accept it use \\. batchstart.sh instead. This double slash may help.

Convert MySql DateTime stamp into JavaScript's Date format

To add even further to Marco's solution. I prototyped directly to the String object.

String.prototype.mysqlToDate = String.prototype.mysqlToDate || function() {
    var t = this.split(/[- :]/);
    return new Date(t[0], t[1]-1, t[2], t[3]||0, t[4]||0, t[5]||0);
};

This way you can go directly to:

var mySqlTimestamp = "2011-02-20 17:16:00";
var pickupDate = mySqlTimestamp.mysqlToDate();

How can I stop a running MySQL query?

If you have mysqladmin available, you may get the list of queries with:

> mysqladmin -uUSERNAME -pPASSWORD pr

+-----+------+-----------------+--------+---------+------+--------------+------------------+
| Id  | User | Host            | db     | Command | Time | State        | Info             |
+-----+------+-----------------+--------+---------+------+--------------+------------------+
| 137 | beet | localhost:53535 | people | Query   | 292  | Sending data | DELETE FROM      |
| 145 | root | localhost:55745 |        | Query   | 0    |              | show processlist |
+-----+------+-----------------+--------+---------+------+--------------+------------------+

Then you may stop the mysql process that is hosting the long running query:

> mysqladmin -uUSERNAME -pPASSWORD kill 137

checking if a number is divisible by 6 PHP

result = initial number + (6 - initial number % 6)

Using ListView : How to add a header view?

I found out that inflating the header view as:

inflater.inflate(R.layout.listheader, container, false);

being container the Fragment's ViewGroup, inflates the headerview with a LayoutParam that extends from FragmentLayout but ListView expect it to be a AbsListView.LayoutParams instead.

So, my problem was solved solved by inflating the header view passing the list as container:

ListView list = fragmentview.findViewById(R.id.listview);
View headerView = inflater.inflate(R.layout.listheader, list, false);

then

list.addHeaderView(headerView, null, false);

Kinda late answer but I hope this can help someone

Grep characters before and after match?

You mean, like this:

grep -o '.\{0,20\}test_pattern.\{0,20\}' file

?

That will print up to twenty characters on either side of test_pattern. The \{0,20\} notation is like *, but specifies zero to twenty repetitions instead of zero or more.The -o says to show only the match itself, rather than the entire line.

How can I delete a user in linux when the system says its currently used in a process

First use pkill or kill -9 <pid> to kill the process.

Then use following userdel command to delete user,

userdel -f cafe_fixer

According to userdel man page:

-f, --force

This option forces the removal of the user account, even if the user is still logged in. It also forces userdel to remove the user's home directory and mail spool, even if another user uses the same home directory or if the mail spool is not owned by the specified user. If USERGROUPS_ENAB is defined to yes in /etc/login.defs and if a group exists with the same name as the deleted user, then this group will be removed, even if it is still the primary group of another user.

Edit 1: (by @Ajedi32)

Note: This option (i.e. --force) is dangerous and may leave your system in an inconsistent state.

Edit 2: (by @socketpair)

In spite of the description about some files, this key allows removing the user while it is in use. Don't forget to chdir / before, because this command will also remove home directory.

Is there a decent wait function in C++?

Actually, contrary to the other answers, I believe that OP's solution is the one that is most elegant.

Here's what you gain by using an external .bat wrapper:

  1. The application obviously waits for user input, so it already does what you want.
  2. You don't clutter the code with awkward calls. Who should wait? main()?
  3. You don't need to deal with cross platform issues - see how many people suggested system("pause") here.
  4. Without this, to test your executable in automatic way in black box testing model, you need to simulate the enter keypress (unless you do things mentioned in the footnote).
  5. Perhaps most importantly - should any user want to run your application through terminal (cmd.exe on Windows platform), they don't want to wait, since they'll see the output anyway. With the .bat wrapper technique, they can decide whether to run the .bat (or .sh) wrapper, or run the executable directly.

Focusing on the last two points - with any other technique, I'd expect the program to offer at least --no-wait switch so that I, as the user, can use the application with all sort of operations such as piping the output, chaining it with other programs etc. These are part of normal CLI workflow, and adding waiting at the end when you're already inside a terminal just gets in the way and destroys user experience.

For these reasons, IMO .bat solution is the nicest here.

HTML character codes for this ? or this ?

Check this page http://www.alanwood.net/unicode/geometric_shapes.html, first is "9650 ? 25B2 BLACK UP-POINTING TRIANGLE (present in WGL4)" and 2nd "9660 ? 25BC BLACK DOWN-POINTING TRIANGLE (present in WGL4)".

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

  • validate: validates the schema, no change happens to the database.
  • update: updates the schema with current execute query.
  • create: creates new schema every time, and destroys previous data.
  • create-drop: drops the schema when the application is stopped or SessionFactory is closed explicitly.

Transaction marked as rollback only: How do I find the cause

Look for exceptions being thrown and caught in the ... sections of your code. Runtime and rollbacking application exceptions cause rollback when thrown out of a business method even if caught on some other place.

You can use context to find out whether the transaction is marked for rollback.

@Resource
private SessionContext context;

context.getRollbackOnly();

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

When you call figure, simply number the plot.

x = arange(5)
y = np.exp(5)
plt.figure(0)
plt.plot(x, y)

z = np.sin(x)
plt.figure(1)
plt.plot(x, z)

w = np.cos(x)
plt.figure(0) # Here's the part I need
plt.plot(x, w)

Edit: Note that you can number the plots however you want (here, starting from 0) but if you don't provide figure with a number at all when you create a new one, the automatic numbering will start at 1 ("Matlab Style" according to the docs).

How to check if memcache or memcached is installed for PHP?

Use this code to not only check if the memcache extension is enabled, but also whether the daemon is running and able to store and retrieve data successfully:

<?php
if (class_exists('Memcache')) {
    $server = 'localhost';
    if (!empty($_REQUEST['server'])) {
        $server = $_REQUEST['server'];
    }
    $memcache = new Memcache;
    $isMemcacheAvailable = @$memcache->connect($server);

    if ($isMemcacheAvailable) {
        $aData = $memcache->get('data');
        echo '<pre>';
        if ($aData) {
            echo '<h2>Data from Cache:</h2>';
            print_r($aData);
        } else {
            $aData = array(
                'me' => 'you',
                'us' => 'them',
            );
            echo '<h2>Fresh Data:</h2>';
            print_r($aData);
            $memcache->set('data', $aData, 0, 300);
        }
        $aData = $memcache->get('data');
        if ($aData) {
            echo '<h3>Memcache seem to be working fine!</h3>';
        } else {
            echo '<h3>Memcache DOES NOT seem to be working!</h3>';
        }
        echo '</pre>';
    }
}
if (!$isMemcacheAvailable) {
    echo 'Memcache not available';
}

?>

How to check whether input value is integer or float?

The ceil and floor methods will help you determine if the number is a whole number.

However if you want to determine if the number can be represented by an int value.

if(value == (int) value)

or a long (64-bit integer)

if(value == (long) value)

or can be safely represented by a float without a loss of precision

if(value == (float) value)

BTW: don't use a 32-bit float unless you have to. In 99% of cases a 64-bit double is a better choice.

Declaring array of objects

Well array.length should do the trick or not? something like, i mean you don't need to know the index range if you just read it..

var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
    arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}

Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.

IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:

var arrayContainingObjects = [];
for (;;){
    try{
        arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
    }
}
catch(err){
    break;
}

It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.

Python: Split a list into sub-lists based on index ranges

list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]

Quicksort: Choosing the pivot

I recommend using the middle index, as it can be calculated easily.

You can calculate it by rounding (array.length / 2).

jsonify a SQLAlchemy result set in Flask

Here's my answer if you're using the declarative base (with help from some of the answers already posted):

# in your models definition where you define and extend declarative_base()
from sqlalchemy.ext.declarative import declarative_base
...
Base = declarative_base()
Base.query = db_session.query_property()
...

# define a new class (call "Model" or whatever) with an as_dict() method defined
class Model():
    def as_dict(self):
        return { c.name: getattr(self, c.name) for c in self.__table__.columns }

# and extend both the Base and Model class in your model definition, e.g.
class Rating(Base, Model):
    ____tablename__ = 'rating'
    id = db.Column(db.Integer, primary_key=True)
    fullurl = db.Column(db.String())
    url = db.Column(db.String())
    comments = db.Column(db.Text)
    ...

# then after you query and have a resultset (rs) of ratings
rs = Rating.query.all()

# you can jsonify it with
s = json.dumps([r.as_dict() for r in rs], default=alchemyencoder)
print (s)

# or if you have a single row
r = Rating.query.first()

# you can jsonify it with
s = json.dumps(r.as_dict(), default=alchemyencoder)

# you will need this alchemyencoder where your are calling json.dumps to handle datetime and decimal format
# credit to Joonas @ http://codeandlife.com/2014/12/07/sqlalchemy-results-to-json-the-easy-way/
def alchemyencoder(obj):
    """JSON encoder function for SQLAlchemy special classes."""
    if isinstance(obj, datetime.date):
        return obj.isoformat()
    elif isinstance(obj, decimal.Decimal):
        return float(obj)

How do I read the contents of a Node.js stream into a string variable?

I had more luck using like that :

let string = '';
readstream
    .on('data', (buf) => string += buf.toString())
    .on('end', () => console.log(string));

I use node v9.11.1 and the readstream is the response from a http.get callback.

How to Detect Browser Window /Tab Close Event?

This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)

    window.onbeforeunload = function () {
        return "Are you sure?";
    }

    $(function () {
        $('input[type="checkbox"]').click(function () {
            window.onbeforeunload = function () { };
        });
    });

Angular.js directive dynamic templateURL

I had the same problem and I solved in a slightly different way from the others. I am using angular 1.4.4.

In my case, I have a shell template that creates a CSS Bootstrap panel:

<div class="class-container panel panel-info">
    <div class="panel-heading">
        <h3 class="panel-title">{{title}} </h3>
    </div>
    <div class="panel-body">
        <sp-panel-body panelbodytpl="{{panelbodytpl}}"></sp-panel-body>
    </div>
</div>

I want to include panel body templates depending on the route.

    angular.module('MyApp')
    .directive('spPanelBody', ['$compile', function($compile){
        return {
            restrict        : 'E',
            scope : true,
            link: function (scope, element, attrs) {
                scope.data = angular.fromJson(scope.data);
                element.append($compile('<ng-include src="\'' + scope.panelbodytpl + '\'"></ng-include>')(scope));
            }
        }
    }]);

I then have the following template included when the route is #/students:

<div class="students-wrapper">
    <div ng-controller="StudentsIndexController as studentCtrl" class="row">
        <div ng-repeat="student in studentCtrl.students" class="col-sm-6 col-md-4 col-lg-3">
            <sp-panel 
            title="{{student.firstName}} {{student.middleName}} {{student.lastName}}"
            panelbodytpl="{{'/student/panel-body.html'}}"
            data="{{student}}"
            ></sp-panel>
        </div>
    </div>
</div>

The panel-body.html template as follows:

Date of Birth: {{data.dob * 1000 | date : 'dd MMM yyyy'}}

Sample data in the case someone wants to have a go:

var student = {
    'id'            : 1,
    'firstName'     : 'John',
    'middleName'    : '',
    'lastName'      : 'Smith',
    'dob'           : 1130799600,
    'current-class' : 5
}

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

I had this issue when i refereed a library project from a console application, and the library project was using a nuget package which is not refereed in the console application. Referring the same package in the console application helped to resolve this issue.

Seeing the Inner exception can help.

How to play videos in android from assets folder or raw folder?

Did you try to put manually Video on SDCard and try to play video store on SDCard ?

If it's working you can find the way to copy from Raw to SDcard here :

android-copy-rawfile-to-sdcard-video-mp4.

How do I expand the output display to see more columns of a pandas DataFrame?

If you don't want to mess with your display options and you just want to see this one particular list of columns without expanding out every dataframe you view, you could try:

df.columns.values

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.

import numpy as np
import random
import cv2

def sp_noise(image,prob):
    '''
    Add salt and pepper noise to image
    prob: Probability of the noise
    '''
    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob 
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output

image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)

Python read-only property

Here is a way to avoid the assumption that

all users are consenting adults, and thus are responsible for using things correctly themselves.

please see my update below

Using @property, is very verbose e.g.:

   class AClassWithManyAttributes:
        '''refactored to properties'''
        def __init__(a, b, c, d, e ...)
             self._a = a
             self._b = b
             self._c = c
             self.d = d
             self.e = e

        @property
        def a(self):
            return self._a
        @property
        def b(self):
            return self._b
        @property
        def c(self):
            return self._c
        # you get this ... it's long

Using

No underscore: it's a public variable.
One underscore: it's a protected variable.
Two underscores: it's a private variable.

Except the last one, it's a convention. You can still, if you really try hard, access variables with double underscore.

So what do we do? Do we give up on having read only properties in Python?

Behold! read_only_properties decorator to the rescue!

@read_only_properties('readonly', 'forbidden')
class MyClass(object):
    def __init__(self, a, b, c):
        self.readonly = a
        self.forbidden = b
        self.ok = c

m = MyClass(1, 2, 3)
m.ok = 4
# we can re-assign a value to m.ok
# read only access to m.readonly is OK 
print(m.ok, m.readonly) 
print("This worked...")
# this will explode, and raise AttributeError
m.forbidden = 4

You ask:

Where is read_only_properties coming from?

Glad you asked, here is the source for read_only_properties:

def read_only_properties(*attrs):

    def class_rebuilder(cls):
        "The class decorator"

        class NewClass(cls):
            "This is the overwritten class"
            def __setattr__(self, name, value):
                if name not in attrs:
                    pass
                elif name not in self.__dict__:
                    pass
                else:
                    raise AttributeError("Can't modify {}".format(name))

                super().__setattr__(name, value)
        return NewClass
    return class_rebuilder

update

I never expected this answer will get so much attention. Surprisingly it does. This encouraged me to create a package you can use.

$ pip install read-only-properties

in your python shell:

In [1]: from rop import read_only_properties

In [2]: @read_only_properties('a')
   ...: class Foo:
   ...:     def __init__(self, a, b):
   ...:         self.a = a
   ...:         self.b = b
   ...:         

In [3]: f=Foo('explodes', 'ok-to-overwrite')

In [4]: f.b = 5

In [5]: f.a = 'boom'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-a5226072b3b4> in <module>()
----> 1 f.a = 'boom'

/home/oznt/.virtualenvs/tracker/lib/python3.5/site-packages/rop.py in __setattr__(self, name, value)
    116                     pass
    117                 else:
--> 118                     raise AttributeError("Can't touch {}".format(name))
    119 
    120                 super().__setattr__(name, value)

AttributeError: Can't touch a

git push vs git push origin <branchname>

The first push should be a:

git push -u origin branchname

That would make sure:

Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.

How to position a DIV in a specific coordinates?

You don't have to use Javascript to do this. Using plain-old css:

div.blah {
  position:absolute;
  top: 0; /*[wherever you want it]*/
  left:0; /*[wherever you want it]*/
}

If you feel you must use javascript, or are trying to do this dynamically Using JQuery, this affects all divs of class "blah":

var blahclass =  $('.blah'); 
blahclass.css('position', 'absolute');
blahclass.css('top', 0); //or wherever you want it
blahclass.css('left', 0); //or wherever you want it

Alternatively, if you must use regular old-javascript you can grab by id

var domElement = document.getElementById('myElement');// don't go to to DOM every time you need it. Instead store in a variable and manipulate.
domElement.style.position = "absolute";
domElement.style.top = 0; //or whatever 
domElement.style.left = 0; // or whatever

Editing specific line in text file in Python

Suppose I have a file named file_name as following:

this is python
it is file handling
this is editing of line

We have to replace line 2 with "modification is done":

f=open("file_name","r+")
a=f.readlines()
for line in f:
   if line.startswith("rai"):
      p=a.index(line)
#so now we have the position of the line which to be modified
a[p]="modification is done"
f.seek(0)
f.truncate() #ersing all data from the file
f.close()
#so now we have an empty file and we will write the modified content now in the file
o=open("file_name","w")
for i in a:
   o.write(i)
o.close()
#now the modification is done in the file

Configuring user and password with Git Bash

Try ssh-agent for installing the SSH key for use with Git. It should auto login after use of a passphrase.

How to use log levels in java

Generally, you don't need all those levels, SEVERE, WARNING, INFO, FINE might be enough. We're using Log4J (not java.util.logging directly) and the following levels (which might differ in name from other logging frameworks):

  • ERROR: Any error/exception that is or might be critical. Our Logger automatically sends an email for each such message on our servers (usage: logger.error("message"); )

  • WARN: Any message that might warn us of potential problems, e.g. when a user tried to log in with wrong credentials - which might indicate an attack if that happens often or in short periods of time (usage: logger.warn("message"); )

  • INFO: Anything that we want to know when looking at the log files, e.g. when a scheduled job started/ended (usage: logger.info("message"); )

  • DEBUG: As the name says, debug messages that we only rarely turn on. (usage: logger.debug("message"); )

The beauty of this is that if you set the log level to WARN, info and debug messages have next to no performance impact. If you need to get additional information from a production system you just can lower the level to INFO or DEBUG for a short period of time (since you'd get much more log entries which make your log files bigger and harder to read). Adjusting log levels etc. can normally be done at runtime (our JBoss instance checks for changes in that config every minute or so).

Draw a line in a div

No need for css, you can just use the HR tag from HTML

<hr />

Add class to an element in Angular 4

If you want to set only one specific class, you might write a TypeScript function returning a boolean to determine when the class should be appended.

TypeScript

function hideThumbnail():boolean{
    if (/* Your criteria here */)
        return true;
}

CSS:

.request-card-hidden {
    display: none;
}

HTML:

<ion-note [class.request-card-hidden]="hideThumbnail()"></ion-note>

How do I escape only single quotes?

If you want to escape characters with a \, you have addcslashes(). For example, if you want to escape only single quotes like the question, you can do:

echo addcslashes($value, "'");

And if you want to escape ', ", \, and nul (the byte null), you can use addslashes():

echo addslashes($value);

How to allow <input type="file"> to accept only image files?

Using this:

<input type="file" accept="image/*">

works in both FF and Chrome.

How do I get a value of a <span> using jQuery?

Assuming you intended it to read id="item1", you need

$('#item1 span').text()

How to display a content in two-column layout in LaTeX?

Use two minipages.

\begin{minipage}[position]{width}
  text
 \end{minipage}

JQuery Datatables : Cannot read property 'aDataSort' of undefined

I had this problem and it was because another script was deleting all of the tables and recreating them, but my table wasn't being recreated. I spent ages on this issue before I noticed that my table wasn't even visible on the page. Can you see your table before you initialize DataTables?

Essentially, the other script was doing:

let tables = $("table");
for (let i = 0; i < tables.length; i++) {
  const table = tables[i];
  if ($.fn.DataTable.isDataTable(table)) {
    $(table).DataTable().destroy(remove);
    $(table).empty();
  }
}

And it should have been doing:

let tables = $("table.some-class-only");
... the rest ...

JavaScript: how to change form action attribute value based on selection?

Simple and easy in javascipt

<script>

  document.getElementById("selectsearch").addEventListener("change", function(){

  var get_form =   document.getElementById("search-form") // get form 
  get_form.action =  '/search/' +  this.value; // assign value 

});

</script>

How to find the 'sizeof' (a pointer pointing to an array)?

There is no magic solution. C is not a reflective language. Objects don't automatically know what they are.

But you have many choices:

  1. Obviously, add a parameter
  2. Wrap the call in a macro and automatically add a parameter
  3. Use a more complex object. Define a structure which contains the dynamic array and also the size of the array. Then, pass the address of the structure.

First char to upper case

For completeness, if you wanted to use replaceFirst, try this:

public static String cap1stChar(String userIdea)
{
  String betterIdea = userIdea;
  if (userIdea.length() > 0)
  {
    String first = userIdea.substring(0,1);
    betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
  }
  return betterIdea;
}//end cap1stChar

How can I put CSS and HTML code in the same file?

Two options: 1, add css inline like style="background:black" Or 2. In the head include the css as a style tag block.

jQuery - Sticky header that shrinks when scrolling down

This should be what you are looking for using jQuery.

$(function(){
  $('#header_nav').data('size','big');
});

$(window).scroll(function(){
  if($(document).scrollTop() > 0)
{
    if($('#header_nav').data('size') == 'big')
    {
        $('#header_nav').data('size','small');
        $('#header_nav').stop().animate({
            height:'40px'
        },600);
    }
}
else
  {
    if($('#header_nav').data('size') == 'small')
      {
        $('#header_nav').data('size','big');
        $('#header_nav').stop().animate({
            height:'100px'
        },600);
      }  
  }
});

Demonstration: http://jsfiddle.net/jezzipin/JJ8Jc/

Fullscreen Activity in Android?

TIP: Using getWindow().setLayout() can screw up your full screen display! Note the documentation for this method says:

Set the width and height layout parameters of the window... you can change them to ... an absolute value to make a window that is not full-screen.

http://developer.android.com/reference/android/view/Window.html#setLayout%28int,%20int%29

For my purposes, I found that I had to use setLayout with absolute parameters to resize my full screen window correctly. Most of the time, this worked fine. It was called by an onConfigurationChanged() event. There was a hiccup, however. If the user exited the app, changed the orientation, and reentered, it would lead to firing off my code which included setLayout(). During this re-entry time window, my status bar (which was hidden by the manifest) would be made to re-appear, but at any other time setLayout() would not cause this! The solution was to add an additional setLayout() call after the one with the hard values like so:

       public static void setSize( final int width, final int height ){
//DO SOME OTHER STUFF...
            instance_.getWindow().setLayout( width, height );
            // Prevent status bar re-appearance
            Handler delay = new Handler();
            delay.postDelayed( new Runnable(){ public void run() {
                instance_.getWindow().setLayout(
                    WindowManager.LayoutParams.FILL_PARENT,
                    WindowManager.LayoutParams.FILL_PARENT );
            }}, FILL_PARENT_ON_RESIZE_DELAY_MILLIS );
        }

The window then correctly re-sized, and the status bar did not re-appear regardless of the event which triggered this.

How to Generate unique file names in C#

You can have a unique file name automatically generated for you without any custom methods. Just use the following with the StorageFolder Class or the StorageFile Class. The key here is: CreationCollisionOption.GenerateUniqueName and NameCollisionOption.GenerateUniqueName

To create a new file with a unique filename:

var myFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myfile.txt", NameCollisionOption.GenerateUniqueName);

To copy a file to a location with a unique filename:

var myFile2 = await myFile1.CopyAsync(ApplicationData.Current.LocalFolder, myFile1.Name, NameCollisionOption.GenerateUniqueName);

To move a file with a unique filename in the destination location:

await myFile.MoveAsync(ApplicationData.Current.LocalFolder, myFile.Name, NameCollisionOption.GenerateUniqueName);

To rename a file with a unique filename in the destination location:

await myFile.RenameAsync(myFile.Name, NameCollisionOption.GenerateUniqueName);

Popup window in PHP?

You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.

How do I center a Bootstrap div with a 'spanX' class?

If anyone wants the true solution for centering BOTH images and text within a span using bootstrap row-fluid, here it is (how to implement this and explanation follows my example):

css

div.row-fluid [class*="span"] .center-in-span { 
   float: none; 
   margin: 0 auto; 
   text-align: center; 
   display: block; 
   width: auto; 
   height: auto;
}

html

<div class="row-fluid">
   <div class="span12">
      <img class="center-in-span" alt="MyExample" src="/path/to/example.jpg"/>
   </div>
</div>

<div class="row-fluid">
   <div class="span12">
      <p class="center-in-span">this is text</p>
   </div>
</div>

USAGE: To use this css to center an image within a span, simply apply the .center-in-span class to the img element, as shown above.

To use this css to center text within a span, simply apply the .center-in-span class to the p element, as shown above.

EXPLANATION: This css works because we are overriding specific bootstrap styling. The notable differences from the other answers that were posted are that the width and height are set to auto, so you don't have to used a fixed with (good for a dynamic webpage). also, the combination of setting the margin to auto, text-align:center and display:block, takes care of both images and paragraphs.

Let me know if this is thorough enough for easy implementation.

What is the facade design pattern?

Facade Design Pattern comes under Structural Design Pattern. In short Facade means the exterior appearance. It means in Facade design pattern we hide something and show only what actually client requires. Read more at below blog: http://www.sharepointcafe.net/2017/03/facade-design-pattern-in-aspdotnet.html

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

What is the Ruby <=> (spaceship) operator?

Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning 1 (true) or 0 (false) depending on whether the arguments are equal or unequal, the spaceship operator will return 1, 0, or -1 depending on the value of the left argument relative to the right argument.

a <=> b :=
  if a < b then return -1
  if a = b then return  0
  if a > b then return  1
  if a and b are not comparable then return nil

It's useful for sorting an array.

Search of table names

I am assuming you want to pass the database name as a parameter and not just run:

SELECT  *
FROM    DBName.sys.tables
WHERE   Name LIKE '%XXX%'

If so, you could use dynamic SQL to add the dbname to the query:

DECLARE @DBName NVARCHAR(200) = 'YourDBName',
        @TableName NVARCHAR(200) = 'SomeString';

IF NOT EXISTS (SELECT 1 FROM master.sys.databases WHERE Name = @DBName)
    BEGIN
        PRINT 'DATABASE NOT FOUND';
        RETURN;
    END;

DECLARE @SQL NVARCHAR(MAX) = '  SELECT  Name
                                FROM    ' + QUOTENAME(@DBName) + '.sys.tables
                                WHERE   Name LIKE ''%'' + @Table + ''%''';

EXECUTE SP_EXECUTESQL @SQL, N'@Table NVARCHAR(200)', @TableName;

Understanding checked vs unchecked exceptions in Java

I think that checked exceptions are a good reminder for the developer that uses an external library that things can go wrong with the code from that library in exceptional situations.

How to import a module given its name as string?

With Python older than 2.7/3.1, that's pretty much how you do it.

For newer versions, see importlib.import_module for Python 2 and and Python 3.

You can use exec if you want to as well.

Or using __import__ you can import a list of modules by doing this:

>>> moduleNames = ['sys', 'os', 're', 'unittest'] 
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)

Ripped straight from Dive Into Python.

TypeError: 'float' object is not callable

There is an operator missing, likely a *:

-3.7 need_something_here (prof[x])

The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.

The parenthesis are also not needed in this case, the following may be sufficient/correct:

-3.7 * prof[x]

As Legolas points out, there are other things which may need to be addressed:

2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
                                  ^-- op missing
                                                    extra parenthesis --^
               valid but questionable float*tuple --^
                                     expression yields 0.0 always --^

Javac is not found

  1. Go to my computer;
  2. Right click properties;
  3. Go to advanced system settings;
  4. Go to environment variables;
  5. In user variables for user click on new(top new button, not on system variables);
  6. Set variable name as: Path
  7. Set the value of that variable to: C:\Program Files\Java\jdk1.7.0_76\bin
  8. Click ok;
  9. Click ok;
  10. Click ok.

Now you're set. Type javac in cmd. All javac options will be displayed.

Is log(n!) = T(n·log(n))?

For lower bound,

lg(n!) = lg(n)+lg(n-1)+...+lg(n/2)+...+lg2+lg1
       >= lg(n/2)+lg(n/2)+...+lg(n/2)+ ((n-1)/2) lg 2 (leave last term lg1(=0); replace first n/2 terms as lg(n/2); replace last (n-1)/2 terms as lg2 which will make cancellation easier later)
       = n/2 lg(n/2) + (n/2) lg 2 - 1/2 lg 2
       = n/2 lg n - (n/2)(lg 2) + n/2 - 1/2
       = n/2 lg n - 1/2

lg(n!) >= (1/2) (n lg n - 1)

Combining both bounds :

1/2 (n lg n - 1) <= lg(n!) <= n lg n

By choosing lower bound constant greater than (1/2) we can compensate for -1 inside the bracket.

Thus lg(n!) = Theta(n lg n)

Android: show/hide status bar/power bar

For Kotlin users

TO SHOW

activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)

TO HIDE

activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)

How Connect to remote host from Aptana Studio 3

There's also an option to Auto Sync built-in in Aptana.

step 1

step 2

Vertical alignment of text and icon in button

Just wrap the button label in an extra span and add class="align-middle" to both (the icon and the label). This will center your icon with text vertical.

<button id="edit-listing-form-house_Continue" 
    class="btn btn-large btn-primary"
    style=""
    value=""
    name="Continue"
    type="submit">
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>

Changing the browser zoom level

I could't find a way to change the actual browser zoom level, but you can get pretty close with CSS transform: scale(). Here is my solution based on JavaScript and jQuery:

<!-- Trigger -->
<ul id="zoom_triggers">
    <li><a id="zoom_in">zoom in</a></li>
    <li><a id="zoom_out">zoom out</a></li>
    <li><a id="zoom_reset">reset zoom</a></li>
</ul>

<script>
    jQuery(document).ready(function($)
    {
        // Set initial zoom level
        var zoom_level=100;

        // Click events
        $('#zoom_in').click(function() { zoom_page(10, $(this)) });
        $('#zoom_out').click(function() { zoom_page(-10, $(this)) });
        $('#zoom_reset').click(function() { zoom_page(0, $(this)) });

        // Zoom function
        function zoom_page(step, trigger)
        {
            // Zoom just to steps in or out
            if(zoom_level>=120 && step>0 || zoom_level<=80 && step<0) return;

            // Set / reset zoom
            if(step==0) zoom_level=100;
            else zoom_level=zoom_level+step;

            // Set page zoom via CSS
            $('body').css({
                transform: 'scale('+(zoom_level/100)+')', // set zoom
                transformOrigin: '50% 0' // set transform scale base
            });

            // Adjust page to zoom width
            if(zoom_level>100) $('body').css({ width: (zoom_level*1.2)+'%' });
            else $('body').css({ width: '100%' });

            // Activate / deaktivate trigger (use CSS to make them look different)
            if(zoom_level>=120 || zoom_level<=80) trigger.addClass('disabled');
            else trigger.parents('ul').find('.disabled').removeClass('disabled');
            if(zoom_level!=100) $('#zoom_reset').removeClass('disabled');
            else $('#zoom_reset').addClass('disabled');
        }
    });
</script>

Apache POI Excel - how to configure columns to be expanded?

You can add this, after your loop.

for (int i = 0; i<53;i++) {
    sheet.autoSizeColumn(i);
}

How to linebreak an svg text within javascript?

With the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here: http://bl.ocks.org/mbostock/7555321

That automatically does line breaks for long text svg for a given width in pixel.

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

Yes, LINQ to Objects supports this with Enumerable.Concat:

var together = first.Concat(second);

NB: Should first or second be null you would receive a ArgumentNullException. To avoid this & treat nulls as you would an empty set, use the null coalescing operator like so:

var together = (first ?? Enumerable.Empty<string>()).Concat(second ?? Enumerable.Empty<string>()); //amending `<string>` to the appropriate type

Where does flask look for image files?

Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static directory? If you move it to your static directory and update your HTML as such:

<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">

It should work.

Also, it is worth noting, there is a better way to structure this.

File structure:

app.py
static
   |----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
   |----index.html

app.py

from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route('/index', methods=['GET', 'POST'])
def lionel(): 
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

templates/index.html

<html>
  <head>

  </head>
  <body>
    <h1>Hi Lionel Messi</h1>

  <img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />

  </body>

</html>

Doing it this way ensures that you are not hard-coding a URL path for your static assets.

max value of integer

That's because in C - integer on 32 bit machine doesn't mean that 32 bits are used for storing it, it may be 16 bits as well. It depends on the machine (implementation-dependent).

Looping each row in datagridview

Best aproach for me was:

  private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        int X = 1;
        foreach(DataGridViewRow row in grid_receptie.Rows)
        {
            row.Cells["NR_CRT"].Value = X;
            X++;
        }
    }

Regex for empty string or white space

If you are looking for empty string in addition to whitespace you meed to use * rather than +

var regex = /^\s*$/ ;
                ^

Iterating through a list to render multiple widgets in Flutter?

You can use ListView to render a list of items. But if you don't want to use ListView, you can create a method which returns a list of Widgets (Texts in your case) like below:

var list = ["one", "two", "three", "four"];

    @override
    Widget build(BuildContext context) {
      return new MaterialApp(
          home: new Scaffold(
        appBar: new AppBar(
          title: new Text('List Test'),
        ),
        body: new Center(
          child: new Column( // Or Row or whatever :)
            children: createChildrenTexts(),
          ),
        ),
      ));
    }

     List<Text> createChildrenTexts() {
    /// Method 1
//    List<Text> childrenTexts = List<Text>();
//    for (String name in list) {
//      childrenTexts.add(new Text(name, style: new TextStyle(color: Colors.red),));
//    }
//    return childrenTexts;

    /// Method 2
    return list.map((text) => Text(text, style: TextStyle(color: Colors.blue),)).toList();
  }

How do you do a ‘Pause’ with PowerShell 2.0?

I assume that you want to read input from the console. If so, use Read-Host.

How to execute a program or call a system command from Python

I would recommend the following method 'run' and it will help us in getting STDOUT, STDERR and exit status as dictionary; The caller of this can read the dictionary return by 'run' method to know the actual state of process.

  def run (cmd):
       print "+ DEBUG exec({0})".format(cmd)
       p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)
       (out, err) = p.communicate()
       ret        = p.wait()
       out        = filter(None, out.split('\n'))
       err        = filter(None, err.split('\n'))
       ret        = True if ret == 0 else False
       return dict({'output': out, 'error': err, 'status': ret})
  #end

How to output a comma delimited list in jinja python template?

You want your if check to be:

{% if not loop.last %}
    ,
{% endif %}

Note that you can also shorten the code by using If Expression:

{{ ", " if not loop.last else "" }}

momentJS date string add 5 days

moment(moment('2015/04/09 16:00:00').add(7, 'd').format('YYYY/MM/DD HH:mm:mm'))

has to format and then convert to moment again.

Skipping every other element after the first

There are more ways than one to skin a cat. - Seba Smith

arr = list(range(10)) # Range from 0-9

# List comprehension: Range with conditional
print [arr[index] for index in range(len(arr)) if index % 2 == 0]

# List comprehension: Range with step
print [arr[index] for index in range(0, len(arr), 2)]

# List comprehension: Enumerate with conditional
print [item for index, item in enumerate(arr) if index % 2 == 0]

# List filter: Index in range
print filter(lambda index: index % 2 == 0, range(len(arr)))

# Extended slice
print arr[::2]

CSS: styled a checkbox to look like a button, is there a hover?

it looks like you need a rule very similar to your checked rule

http://jsfiddle.net/VWBN4/3

#ck-button input:hover + span {
    background-color:#191;
    color:#fff;
}

and for hover and clicked state:

#ck-button input:checked:hover + span {
    background-color:#c11;
    color:#fff;
}

the order is important though.

Password must have at least one non-alpha character

Use regex pattern ^(?=.{8})(?=.*[^a-zA-Z])


Explanation:

^(?=.{8})(?=.*[^a-zA-Z])
¦+------++-------------+
¦   ¦           ¦
¦   ¦           + string contains some non-letter character
¦   ¦
¦   + string contains at least 8 characters
¦
+ begining of line/string

If you want to limit also maximum length (let's say 16), then use regex pattern:

^(?=.{8,16}$)(?=.*[^a-zA-Z])

How can I get input radio elements to horizontally align?

In your case, you just need to remove the line breaks (<br> tags) between the elements - input elements are inline-block by default (in Chrome at least). (updated example).

<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change

I'd suggest using <label> elements, though. In doing so, clicking on the label will check the element too. Either associate the <label>'s for attribute with the <input>'s id: (example)

<input type="radio" name="editList" id="always" value="always"/>
<label for="always">Always</label>

<input type="radio" name="editList" id="never" value="never"/>
<label for="never">Never</label>

<input type="radio" name="editList" id="change" value="costChange"/>
<label for="change">Cost Change</label>

..or wrap the <label> elements around the <input> elements directly: (example)

<label>
    <input type="radio" name="editList" value="always"/>Always
</label>
<label>
    <input type="radio" name="editList" value="never"/>Never
</label>
<label>
    <input type="radio" name="editList" value="costChange"/>Cost Change
</label>

You can also get fancy and use the :checked pseudo class.

How to use split?

Look in JavaScript split() Method

Usage:

"something -- something_else".split(" -- ") 

Troubleshooting misplaced .git directory (nothing to commit)

Go to your workspace folder

  1. find .git folder
  2. delete the folder and its contents
  3. use git init command to initialize.

Now it will show what all the files can be committed.

Get MIME type from filename extension

a combination of both solutions presented here:

using System;
using System.Collections.Generic;

namespace Mime
{
    class Mime
    {

        public static string GetMimeType(string fileName)
        {
            if (string.IsNullOrEmpty(fileName) || string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("filename must contain a filename");
            }
            string extension = System.IO.Path.GetExtension(fileName).ToLower();

            if (!extension.StartsWith("."))
            {
                extension = "." + extension;
            }


            string mime;

            if (_mappings.TryGetValue(extension, out mime))
                return mime;
            if (GetWindowsMimeType(extension, out mime))
            {
                _mappings.Add(extension, mime);
                return mime;
            }
            return "application/octet-stream";
        }

        public static bool GetWindowsMimeType(string ext, out string mime)
        {
            mime="application/octet-stream";
            Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);

            if (regKey != null)
            { 
             object val=regKey.GetValue("Content Type") ;
             if (val != null)
             {
                 string strval = val.ToString();
                 if(!(string.IsNullOrEmpty(strval)||string.IsNullOrWhiteSpace(strval)))
                 {
                     mime=strval;
                     return true;
                 }
             }
            }
            return false;
        }

        static IDictionary<string, string> _mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {

        #region Big freaking list of mime types
        // combination of values from Windows 7 Registry and 
        // from C:\Windows\System32\inetsrv\config\applicationHost.config
        // some added, including .7z and .dat
        {".323", "text/h323"},
        {".3g2", "video/3gpp2"},
        {".3gp", "video/3gpp"},
        {".3gp2", "video/3gpp2"},
        {".3gpp", "video/3gpp"},
        {".7z", "application/x-7z-compressed"},
        {".aa", "audio/audible"},
        {".AAC", "audio/aac"},
        {".aaf", "application/octet-stream"},
        {".aax", "audio/vnd.audible.aax"},
        {".ac3", "audio/ac3"},
        {".aca", "application/octet-stream"},
        {".accda", "application/msaccess.addin"},
        {".accdb", "application/msaccess"},
        {".accdc", "application/msaccess.cab"},
        {".accde", "application/msaccess"},
        {".accdr", "application/msaccess.runtime"},
        {".accdt", "application/msaccess"},
        {".accdw", "application/msaccess.webapplication"},
        {".accft", "application/msaccess.ftemplate"},
        {".acx", "application/internet-property-stream"},
        {".AddIn", "text/xml"},
        {".ade", "application/msaccess"},
        {".adobebridge", "application/x-bridge-url"},
        {".adp", "application/msaccess"},
        {".ADT", "audio/vnd.dlna.adts"},
        {".ADTS", "audio/aac"},
        {".afm", "application/octet-stream"},
        {".ai", "application/postscript"},
        {".aif", "audio/x-aiff"},
        {".aifc", "audio/aiff"},
        {".aiff", "audio/aiff"},
        {".air", "application/vnd.adobe.air-application-installer-package+zip"},
        {".amc", "application/x-mpeg"},
        {".application", "application/x-ms-application"},
        {".art", "image/x-jg"},
        {".asa", "application/xml"},
        {".asax", "application/xml"},
        {".ascx", "application/xml"},
        {".asd", "application/octet-stream"},
        {".asf", "video/x-ms-asf"},
        {".ashx", "application/xml"},
        {".asi", "application/octet-stream"},
        {".asm", "text/plain"},
        {".asmx", "application/xml"},
        {".aspx", "application/xml"},
        {".asr", "video/x-ms-asf"},
        {".asx", "video/x-ms-asf"},
        {".atom", "application/atom+xml"},
        {".au", "audio/basic"},
        {".avi", "video/x-msvideo"},
        {".axs", "application/olescript"},
        {".bas", "text/plain"},
        {".bcpio", "application/x-bcpio"},
        {".bin", "application/octet-stream"},
        {".bmp", "image/bmp"},
        {".c", "text/plain"},
        {".cab", "application/octet-stream"},
        {".caf", "audio/x-caf"},
        {".calx", "application/vnd.ms-office.calx"},
        {".cat", "application/vnd.ms-pki.seccat"},
        {".cc", "text/plain"},
        {".cd", "text/plain"},
        {".cdda", "audio/aiff"},
        {".cdf", "application/x-cdf"},
        {".cer", "application/x-x509-ca-cert"},
        {".chm", "application/octet-stream"},
        {".class", "application/x-java-applet"},
        {".clp", "application/x-msclip"},
        {".cmx", "image/x-cmx"},
        {".cnf", "text/plain"},
        {".cod", "image/cis-cod"},
        {".config", "application/xml"},
        {".contact", "text/x-ms-contact"},
        {".coverage", "application/xml"},
        {".cpio", "application/x-cpio"},
        {".cpp", "text/plain"},
        {".crd", "application/x-mscardfile"},
        {".crl", "application/pkix-crl"},
        {".crt", "application/x-x509-ca-cert"},
        {".cs", "text/plain"},
        {".csdproj", "text/plain"},
        {".csh", "application/x-csh"},
        {".csproj", "text/plain"},
        {".css", "text/css"},
        {".csv", "text/csv"},
        {".cur", "application/octet-stream"},
        {".cxx", "text/plain"},
        {".dat", "application/octet-stream"},
        {".datasource", "application/xml"},
        {".dbproj", "text/plain"},
        {".dcr", "application/x-director"},
        {".def", "text/plain"},
        {".deploy", "application/octet-stream"},
        {".der", "application/x-x509-ca-cert"},
        {".dgml", "application/xml"},
        {".dib", "image/bmp"},
        {".dif", "video/x-dv"},
        {".dir", "application/x-director"},
        {".disco", "text/xml"},
        {".dll", "application/x-msdownload"},
        {".dll.config", "text/xml"},
        {".dlm", "text/dlm"},
        {".doc", "application/msword"},
        {".docm", "application/vnd.ms-word.document.macroEnabled.12"},
        {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
        {".dot", "application/msword"},
        {".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
        {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
        {".dsp", "application/octet-stream"},
        {".dsw", "text/plain"},
        {".dtd", "text/xml"},
        {".dtsConfig", "text/xml"},
        {".dv", "video/x-dv"},
        {".dvi", "application/x-dvi"},
        {".dwf", "drawing/x-dwf"},
        {".dwp", "application/octet-stream"},
        {".dxr", "application/x-director"},
        {".eml", "message/rfc822"},
        {".emz", "application/octet-stream"},
        {".eot", "application/octet-stream"},
        {".eps", "application/postscript"},
        {".etl", "application/etl"},
        {".etx", "text/x-setext"},
        {".evy", "application/envoy"},
        {".exe", "application/octet-stream"},
        {".exe.config", "text/xml"},
        {".fdf", "application/vnd.fdf"},
        {".fif", "application/fractals"},
        {".filters", "Application/xml"},
        {".fla", "application/octet-stream"},
        {".flr", "x-world/x-vrml"},
        {".flv", "video/x-flv"},
        {".fsscript", "application/fsharp-script"},
        {".fsx", "application/fsharp-script"},
        {".generictest", "application/xml"},
        {".gif", "image/gif"},
        {".group", "text/x-ms-group"},
        {".gsm", "audio/x-gsm"},
        {".gtar", "application/x-gtar"},
        {".gz", "application/x-gzip"},
        {".h", "text/plain"},
        {".hdf", "application/x-hdf"},
        {".hdml", "text/x-hdml"},
        {".hhc", "application/x-oleobject"},
        {".hhk", "application/octet-stream"},
        {".hhp", "application/octet-stream"},
        {".hlp", "application/winhlp"},
        {".hpp", "text/plain"},
        {".hqx", "application/mac-binhex40"},
        {".hta", "application/hta"},
        {".htc", "text/x-component"},
        {".htm", "text/html"},
        {".html", "text/html"},
        {".htt", "text/webviewhtml"},
        {".hxa", "application/xml"},
        {".hxc", "application/xml"},
        {".hxd", "application/octet-stream"},
        {".hxe", "application/xml"},
        {".hxf", "application/xml"},
        {".hxh", "application/octet-stream"},
        {".hxi", "application/octet-stream"},
        {".hxk", "application/xml"},
        {".hxq", "application/octet-stream"},
        {".hxr", "application/octet-stream"},
        {".hxs", "application/octet-stream"},
        {".hxt", "text/html"},
        {".hxv", "application/xml"},
        {".hxw", "application/octet-stream"},
        {".hxx", "text/plain"},
        {".i", "text/plain"},
        {".ico", "image/x-icon"},
        {".ics", "application/octet-stream"},
        {".idl", "text/plain"},
        {".ief", "image/ief"},
        {".iii", "application/x-iphone"},
        {".inc", "text/plain"},
        {".inf", "application/octet-stream"},
        {".inl", "text/plain"},
        {".ins", "application/x-internet-signup"},
        {".ipa", "application/x-itunes-ipa"},
        {".ipg", "application/x-itunes-ipg"},
        {".ipproj", "text/plain"},
        {".ipsw", "application/x-itunes-ipsw"},
        {".iqy", "text/x-ms-iqy"},
        {".isp", "application/x-internet-signup"},
        {".ite", "application/x-itunes-ite"},
        {".itlp", "application/x-itunes-itlp"},
        {".itms", "application/x-itunes-itms"},
        {".itpc", "application/x-itunes-itpc"},
        {".IVF", "video/x-ivf"},
        {".jar", "application/java-archive"},
        {".java", "application/octet-stream"},
        {".jck", "application/liquidmotion"},
        {".jcz", "application/liquidmotion"},
        {".jfif", "image/pjpeg"},
        {".jnlp", "application/x-java-jnlp-file"},
        {".jpb", "application/octet-stream"},
        {".jpe", "image/jpeg"},
        {".jpeg", "image/jpeg"},
        {".jpg", "image/jpeg"},
        {".js", "application/x-javascript"},
        {".jsx", "text/jscript"},
        {".jsxbin", "text/plain"},
        {".latex", "application/x-latex"},
        {".library-ms", "application/windows-library+xml"},
        {".lit", "application/x-ms-reader"},
        {".loadtest", "application/xml"},
        {".lpk", "application/octet-stream"},
        {".lsf", "video/x-la-asf"},
        {".lst", "text/plain"},
        {".lsx", "video/x-la-asf"},
        {".lzh", "application/octet-stream"},
        {".m13", "application/x-msmediaview"},
        {".m14", "application/x-msmediaview"},
        {".m1v", "video/mpeg"},
        {".m2t", "video/vnd.dlna.mpeg-tts"},
        {".m2ts", "video/vnd.dlna.mpeg-tts"},
        {".m2v", "video/mpeg"},
        {".m3u", "audio/x-mpegurl"},
        {".m3u8", "audio/x-mpegurl"},
        {".m4a", "audio/m4a"},
        {".m4b", "audio/m4b"},
        {".m4p", "audio/m4p"},
        {".m4r", "audio/x-m4r"},
        {".m4v", "video/x-m4v"},
        {".mac", "image/x-macpaint"},
        {".mak", "text/plain"},
        {".man", "application/x-troff-man"},
        {".manifest", "application/x-ms-manifest"},
        {".map", "text/plain"},
        {".master", "application/xml"},
        {".mda", "application/msaccess"},
        {".mdb", "application/x-msaccess"},
        {".mde", "application/msaccess"},
        {".mdp", "application/octet-stream"},
        {".me", "application/x-troff-me"},
        {".mfp", "application/x-shockwave-flash"},
        {".mht", "message/rfc822"},
        {".mhtml", "message/rfc822"},
        {".mid", "audio/mid"},
        {".midi", "audio/mid"},
        {".mix", "application/octet-stream"},
        {".mk", "text/plain"},
        {".mmf", "application/x-smaf"},
        {".mno", "text/xml"},
        {".mny", "application/x-msmoney"},
        {".mod", "video/mpeg"},
        {".mov", "video/quicktime"},
        {".movie", "video/x-sgi-movie"},
        {".mp2", "video/mpeg"},
        {".mp2v", "video/mpeg"},
        {".mp3", "audio/mpeg"},
        {".mp4", "video/mp4"},
        {".mp4v", "video/mp4"},
        {".mpa", "video/mpeg"},
        {".mpe", "video/mpeg"},
        {".mpeg", "video/mpeg"},
        {".mpf", "application/vnd.ms-mediapackage"},
        {".mpg", "video/mpeg"},
        {".mpp", "application/vnd.ms-project"},
        {".mpv2", "video/mpeg"},
        {".mqv", "video/quicktime"},
        {".ms", "application/x-troff-ms"},
        {".msi", "application/octet-stream"},
        {".mso", "application/octet-stream"},
        {".mts", "video/vnd.dlna.mpeg-tts"},
        {".mtx", "application/xml"},
        {".mvb", "application/x-msmediaview"},
        {".mvc", "application/x-miva-compiled"},
        {".mxp", "application/x-mmxp"},
        {".nc", "application/x-netcdf"},
        {".nsc", "video/x-ms-asf"},
        {".nws", "message/rfc822"},
        {".ocx", "application/octet-stream"},
        {".oda", "application/oda"},
        {".odc", "text/x-ms-odc"},
        {".odh", "text/plain"},
        {".odl", "text/plain"},
        {".odp", "application/vnd.oasis.opendocument.presentation"},
        {".ods", "application/oleobject"},
        {".odt", "application/vnd.oasis.opendocument.text"},
        {".one", "application/onenote"},
        {".onea", "application/onenote"},
        {".onepkg", "application/onenote"},
        {".onetmp", "application/onenote"},
        {".onetoc", "application/onenote"},
        {".onetoc2", "application/onenote"},
        {".orderedtest", "application/xml"},
        {".osdx", "application/opensearchdescription+xml"},
        {".p10", "application/pkcs10"},
        {".p12", "application/x-pkcs12"},
        {".p7b", "application/x-pkcs7-certificates"},
        {".p7c", "application/pkcs7-mime"},
        {".p7m", "application/pkcs7-mime"},
        {".p7r", "application/x-pkcs7-certreqresp"},
        {".p7s", "application/pkcs7-signature"},
        {".pbm", "image/x-portable-bitmap"},
        {".pcast", "application/x-podcast"},
        {".pct", "image/pict"},
        {".pcx", "application/octet-stream"},
        {".pcz", "application/octet-stream"},
        {".pdf", "application/pdf"},
        {".pfb", "application/octet-stream"},
        {".pfm", "application/octet-stream"},
        {".pfx", "application/x-pkcs12"},
        {".pgm", "image/x-portable-graymap"},
        {".pic", "image/pict"},
        {".pict", "image/pict"},
        {".pkgdef", "text/plain"},
        {".pkgundef", "text/plain"},
        {".pko", "application/vnd.ms-pki.pko"},
        {".pls", "audio/scpls"},
        {".pma", "application/x-perfmon"},
        {".pmc", "application/x-perfmon"},
        {".pml", "application/x-perfmon"},
        {".pmr", "application/x-perfmon"},
        {".pmw", "application/x-perfmon"},
        {".png", "image/png"},
        {".pnm", "image/x-portable-anymap"},
        {".pnt", "image/x-macpaint"},
        {".pntg", "image/x-macpaint"},
        {".pnz", "image/png"},
        {".pot", "application/vnd.ms-powerpoint"},
        {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
        {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
        {".ppa", "application/vnd.ms-powerpoint"},
        {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
        {".ppm", "image/x-portable-pixmap"},
        {".pps", "application/vnd.ms-powerpoint"},
        {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
        {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
        {".ppt", "application/vnd.ms-powerpoint"},
        {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
        {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
        {".prf", "application/pics-rules"},
        {".prm", "application/octet-stream"},
        {".prx", "application/octet-stream"},
        {".ps", "application/postscript"},
        {".psc1", "application/PowerShell"},
        {".psd", "application/octet-stream"},
        {".psess", "application/xml"},
        {".psm", "application/octet-stream"},
        {".psp", "application/octet-stream"},
        {".pub", "application/x-mspublisher"},
        {".pwz", "application/vnd.ms-powerpoint"},
        {".qht", "text/x-html-insertion"},
        {".qhtm", "text/x-html-insertion"},
        {".qt", "video/quicktime"},
        {".qti", "image/x-quicktime"},
        {".qtif", "image/x-quicktime"},
        {".qtl", "application/x-quicktimeplayer"},
        {".qxd", "application/octet-stream"},
        {".ra", "audio/x-pn-realaudio"},
        {".ram", "audio/x-pn-realaudio"},
        {".rar", "application/octet-stream"},
        {".ras", "image/x-cmu-raster"},
        {".rat", "application/rat-file"},
        {".rc", "text/plain"},
        {".rc2", "text/plain"},
        {".rct", "text/plain"},
        {".rdlc", "application/xml"},
        {".resx", "application/xml"},
        {".rf", "image/vnd.rn-realflash"},
        {".rgb", "image/x-rgb"},
        {".rgs", "text/plain"},
        {".rm", "application/vnd.rn-realmedia"},
        {".rmi", "audio/mid"},
        {".rmp", "application/vnd.rn-rn_music_package"},
        {".roff", "application/x-troff"},
        {".rpm", "audio/x-pn-realaudio-plugin"},
        {".rqy", "text/x-ms-rqy"},
        {".rtf", "application/rtf"},
        {".rtx", "text/richtext"},
        {".ruleset", "application/xml"},
        {".s", "text/plain"},
        {".safariextz", "application/x-safari-safariextz"},
        {".scd", "application/x-msschedule"},
        {".sct", "text/scriptlet"},
        {".sd2", "audio/x-sd2"},
        {".sdp", "application/sdp"},
        {".sea", "application/octet-stream"},
        {".searchConnector-ms", "application/windows-search-connector+xml"},
        {".setpay", "application/set-payment-initiation"},
        {".setreg", "application/set-registration-initiation"},
        {".settings", "application/xml"},
        {".sgimb", "application/x-sgimb"},
        {".sgml", "text/sgml"},
        {".sh", "application/x-sh"},
        {".shar", "application/x-shar"},
        {".shtml", "text/html"},
        {".sit", "application/x-stuffit"},
        {".sitemap", "application/xml"},
        {".skin", "application/xml"},
        {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
        {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
        {".slk", "application/vnd.ms-excel"},
        {".sln", "text/plain"},
        {".slupkg-ms", "application/x-ms-license"},
        {".smd", "audio/x-smd"},
        {".smi", "application/octet-stream"},
        {".smx", "audio/x-smd"},
        {".smz", "audio/x-smd"},
        {".snd", "audio/basic"},
        {".snippet", "application/xml"},
        {".snp", "application/octet-stream"},
        {".sol", "text/plain"},
        {".sor", "text/plain"},
        {".spc", "application/x-pkcs7-certificates"},
        {".spl", "application/futuresplash"},
        {".src", "application/x-wais-source"},
        {".srf", "text/plain"},
        {".SSISDeploymentManifest", "text/xml"},
        {".ssm", "application/streamingmedia"},
        {".sst", "application/vnd.ms-pki.certstore"},
        {".stl", "application/vnd.ms-pki.stl"},
        {".sv4cpio", "application/x-sv4cpio"},
        {".sv4crc", "application/x-sv4crc"},
        {".svc", "application/xml"},
        {".swf", "application/x-shockwave-flash"},
        {".t", "application/x-troff"},
        {".tar", "application/x-tar"},
        {".tcl", "application/x-tcl"},
        {".testrunconfig", "application/xml"},
        {".testsettings", "application/xml"},
        {".tex", "application/x-tex"},
        {".texi", "application/x-texinfo"},
        {".texinfo", "application/x-texinfo"},
        {".tgz", "application/x-compressed"},
        {".thmx", "application/vnd.ms-officetheme"},
        {".thn", "application/octet-stream"},
        {".tif", "image/tiff"},
        {".tiff", "image/tiff"},
        {".tlh", "text/plain"},
        {".tli", "text/plain"},
        {".toc", "application/octet-stream"},
        {".tr", "application/x-troff"},
        {".trm", "application/x-msterminal"},
        {".trx", "application/xml"},
        {".ts", "video/vnd.dlna.mpeg-tts"},
        {".tsv", "text/tab-separated-values"},
        {".ttf", "application/octet-stream"},
        {".tts", "video/vnd.dlna.mpeg-tts"},
        {".txt", "text/plain"},
        {".u32", "application/octet-stream"},
        {".uls", "text/iuls"},
        {".user", "text/plain"},
        {".ustar", "application/x-ustar"},
        {".vb", "text/plain"},
        {".vbdproj", "text/plain"},
        {".vbk", "video/mpeg"},
        {".vbproj", "text/plain"},
        {".vbs", "text/vbscript"},
        {".vcf", "text/x-vcard"},
        {".vcproj", "Application/xml"},
        {".vcs", "text/plain"},
        {".vcxproj", "Application/xml"},
        {".vddproj", "text/plain"},
        {".vdp", "text/plain"},
        {".vdproj", "text/plain"},
        {".vdx", "application/vnd.ms-visio.viewer"},
        {".vml", "text/xml"},
        {".vscontent", "application/xml"},
        {".vsct", "text/xml"},
        {".vsd", "application/vnd.visio"},
        {".vsi", "application/ms-vsi"},
        {".vsix", "application/vsix"},
        {".vsixlangpack", "text/xml"},
        {".vsixmanifest", "text/xml"},
        {".vsmdi", "application/xml"},
        {".vspscc", "text/plain"},
        {".vss", "application/vnd.visio"},
        {".vsscc", "text/plain"},
        {".vssettings", "text/xml"},
        {".vssscc", "text/plain"},
        {".vst", "application/vnd.visio"},
        {".vstemplate", "text/xml"},
        {".vsto", "application/x-ms-vsto"},
        {".vsw", "application/vnd.visio"},
        {".vsx", "application/vnd.visio"},
        {".vtx", "application/vnd.visio"},
        {".wav", "audio/wav"},
        {".wave", "audio/wav"},
        {".wax", "audio/x-ms-wax"},
        {".wbk", "application/msword"},
        {".wbmp", "image/vnd.wap.wbmp"},
        {".wcm", "application/vnd.ms-works"},
        {".wdb", "application/vnd.ms-works"},
        {".wdp", "image/vnd.ms-photo"},
        {".webarchive", "application/x-safari-webarchive"},
        {".webtest", "application/xml"},
        {".wiq", "application/xml"},
        {".wiz", "application/msword"},
        {".wks", "application/vnd.ms-works"},
        {".WLMP", "application/wlmoviemaker"},
        {".wlpginstall", "application/x-wlpg-detect"},
        {".wlpginstall3", "application/x-wlpg3-detect"},
        {".wm", "video/x-ms-wm"},
        {".wma", "audio/x-ms-wma"},
        {".wmd", "application/x-ms-wmd"},
        {".wmf", "application/x-msmetafile"},
        {".wml", "text/vnd.wap.wml"},
        {".wmlc", "application/vnd.wap.wmlc"},
        {".wmls", "text/vnd.wap.wmlscript"},
        {".wmlsc", "application/vnd.wap.wmlscriptc"},
        {".wmp", "video/x-ms-wmp"},
        {".wmv", "video/x-ms-wmv"},
        {".wmx", "video/x-ms-wmx"},
        {".wmz", "application/x-ms-wmz"},
        {".wpl", "application/vnd.ms-wpl"},
        {".wps", "application/vnd.ms-works"},
        {".wri", "application/x-mswrite"},
        {".wrl", "x-world/x-vrml"},
        {".wrz", "x-world/x-vrml"},
        {".wsc", "text/scriptlet"},
        {".wsdl", "text/xml"},
        {".wvx", "video/x-ms-wvx"},
        {".x", "application/directx"},
        {".xaf", "x-world/x-vrml"},
        {".xaml", "application/xaml+xml"},
        {".xap", "application/x-silverlight-app"},
        {".xbap", "application/x-ms-xbap"},
        {".xbm", "image/x-xbitmap"},
        {".xdr", "text/plain"},
        {".xht", "application/xhtml+xml"},
        {".xhtml", "application/xhtml+xml"},
        {".xla", "application/vnd.ms-excel"},
        {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
        {".xlc", "application/vnd.ms-excel"},
        {".xld", "application/vnd.ms-excel"},
        {".xlk", "application/vnd.ms-excel"},
        {".xll", "application/vnd.ms-excel"},
        {".xlm", "application/vnd.ms-excel"},
        {".xls", "application/vnd.ms-excel"},
        {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
        {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
        {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
        {".xlt", "application/vnd.ms-excel"},
        {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
        {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
        {".xlw", "application/vnd.ms-excel"},
        {".xml", "text/xml"},
        {".xmta", "application/xml"},
        {".xof", "x-world/x-vrml"},
        {".XOML", "text/plain"},
        {".xpm", "image/x-xpixmap"},
        {".xps", "application/vnd.ms-xpsdocument"},
        {".xrm-ms", "text/xml"},
        {".xsc", "application/xml"},
        {".xsd", "text/xml"},
        {".xsf", "text/xml"},
        {".xsl", "text/xml"},
        {".xslt", "text/xml"},
        {".xsn", "application/octet-stream"},
        {".xss", "application/xml"},
        {".xtp", "application/octet-stream"},
        {".xwd", "image/x-xwindowdump"},
        {".z", "application/x-compress"},
        {".zip", "application/x-zip-compressed"},
        #endregion

        };

    }
}

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

I tried the top-most answers to this question, but encountered error messages. Then I found the answer here:

PowerShell says "execution of scripts is disabled on this system."

What worked well for me was to use this solution:

powershell -ExecutionPolicy Bypass -File script.ps1

You can paste that into a .bat file and double-click on it.

Match two strings in one line with grep

When the both strings are in sequence then put a pattern in between on grep command:

$ grep -E "string1(?.*)string2" file

Example if the following lines are contained in a file named Dockerfile:

FROM python:3.8 as build-python
FROM python:3.8-slim

To get the line that contains the strings: FROM python and as build-python then use:

$ grep -E "FROM python:(?.*) as build-python" Dockerfile

Then the output will show only the line that contain both strings:

FROM python:3.8 as build-python

How to hide a status bar in iOS?

I am supporting iOS 5, 6, & 7. My app is iPad only. I needed to use all of the following:

[[UIApplication sharedApplication] setStatusBarHidden:YES];

View Controller:

- (BOOL)prefersStatusBarHidden{ return YES; }

Info.plist

    <key>UIStatusBarHidden</key>
    <string>YES</string>

    <key>UIStatusBarHidden~ipad</key>
    <true/>

    <key>UIViewControllerBasedStatusBarAppearance</key>
    <string>NO</string>

C++ Calling a function from another class

What you should do, is put CallFunction into *.cpp file, where you include B.h.

After edit, files will look like:

B.h:

#pragma once //or other specific to compiler...
using namespace std;

class A 
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
        {
            //stuff done here
        }
};

B.cpp

#include "B.h"
void A::CallFunction(){
//use B object here...
}

Referencing to your explanation, that you have tried to change B b; into pointer- it would be okay, if you wouldn't use it in that same place. You can use pointer of undefined class(but declared), because ALL pointers have fixed byte size(4), so compiler doesn't have problems with that. But it knows nothing about the object they are pointing to(simply: knows the size/boundary, not the content).

So as long as you are using the knowledge, that all pointers are same size, you can use them anywhere. But if you want to use the object, they are pointing to, the class of this object must be already defined and known by compiler.

And last clarification: objects may differ in size, unlike pointers. Pointer is a number/index, which indicates the place in RAM, where something is stored(for example index: 0xf6a7b1).

Npm Please try using this command again as root/administrator

Try following steps

1. Run this command on Terminal or CMD - npm cache clean

2. Go to this folder on windows %APPDATA%\npm-cache And delete folder which you want to install module (Ex:- laravel-elixir) or if you are using PowerShell, $env:APPDATA\npm-cache

3. Then Run your command EX:- npm install laravel-elixir

How do I make a Git commit in the past?

In my case, while using the --date option, my git process crashed. May be I did something terrible. And as a result some index.lock file appeared. So I manually deleted the .lock files from .git folder and executed, for all modified files to be commited in passed dates and it worked this time. Thanx for all the answers here.

git commit --date="`date --date='2 day ago'`" -am "update"

Using String Format to show decimal up to 2 places or simple integer

If none of the other answers work for you, it may be because you are binding the ContentProperty of a control in the OnLoad function, which means this won't work:

private void UserControl_Load(object sender, RoutedEventArgs e)
{
  Bind.SetBindingElement(labelName, String.Format("{0:0.00}", PropertyName), Label.ContentProperty) 
}

The solution is simple: there is a ContentStringFormat property in the xaml. So when you create the label do this:

//if you want the decimal places definite
<Label Content="0" Name="labelName" ContentStringFormat="0.00"/>

Or

//if you want the decimal places to be optional
<Label Content="0" Name="labelName" ContentStringFormat="0.##"/>

How do I finish the merge after resolving my merge conflicts?

A merge conflict occurs when two branches you're trying to merge both changed the same part of the same file. You can generate a list of conflicts with git status.

When the conflicted line is encountered, Git will edit the content of the affected files with visual indicators that mark both sides of the conflicting content.

<<<<<<< HEAD
conflicted text from HEAD
=======
conflicted text from merging_branch
>>>>>>> merging_branch

When you fix your conflicted files and you are ready to merge, all you have to do is run git add and git commit to generate the merge commit. Once the commit was made ,git push the changes to the branch.

Reference article: Git merge.

CSS to keep element at "fixed" position on screen

You can do like this:

#mydiv {
    position: fixed; 
    height: 30px; 
    top: 0; 
    left: 0; 
    width: 100%; 
}

This will create a div, that will be fixed on top of your screen. - fixed

symfony2 : failed to write cache directory

If you face this error when you start Symfony project with docker (my Symfony version 5.1). Or errors like these:

Uncaught Exception: Failed to write file "/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainer.xml"" while reading upstream

Uncaught Warning: file_put_contents(/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainerDeprecations.log): failed to open stream: Permission denied" while reading upstream

Fix below helped me.

In Dockerfile for nginx container add line:

RUN usermod -u 1000 www-data

In Dockerfile for php-fpm container add line:

RUN usermod -u 1000 www-data

Then remove everything in directories "/var/cache", "/var/log" and rebuild docker's containers.

Convert Float to Int in Swift

Just use type casting

 var floatValue:Float = 5.4
 var integerValue:Int = Int(floatValue)

 println("IntegerValue = \(integerValue)")

it will show roundoff value eg: IntegerValue = 5 means the decimal point will be loss

How do you count the number of occurrences of a certain substring in a SQL varchar?

I finally write this function that should cover all the possible situations, adding a char prefix and suffix to the input. this char is evaluated to be different to any of the char conteined in the search parameter, so it can't affect the result.

CREATE FUNCTION [dbo].[CountOccurrency]
(
@Input nvarchar(max),
@Search nvarchar(max)
)
RETURNS int AS
BEGIN
    declare @SearhLength as int = len('-' + @Search + '-') -2;
    declare @conteinerIndex as int = 255;
    declare @conteiner as char(1) = char(@conteinerIndex);
    WHILE ((CHARINDEX(@conteiner, @Search)>0) and (@conteinerIndex>0))
    BEGIN
        set @conteinerIndex = @conteinerIndex-1;
        set @conteiner = char(@conteinerIndex);
    END;
    set @Input = @conteiner + @Input + @conteiner
    RETURN (len(@Input) - len(replace(@Input, @Search, ''))) / @SearhLength
END 

usage

select dbo.CountOccurrency('a,b,c,d ,', ',')

Update TextView Every Second

This Code work for me..

//Get Time and Date
private String getTimeMethod(String formate)
{
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat(formate);
    String formattedDate= dateFormat.format(date);
    return formattedDate;
}

//this method is used to refresh Time every Second
private void refreshTime() //Call this method to refresh time
{
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    txtV_Time.setText(getTimeMethod("hh:mm:ss a")); //hours,Min and Second with am/pm
                    txtV_Date.setText(getTimeMethod("dd-MMM-yy")); //You have to pass your DateFormate in getTimeMethod()          
                };
            });
        }
    }, 0, 1000);//1000 is a Refreshing Time (1second)
}

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

You need to make sure you have installed grunt globally

Can I pass parameters by reference in Java?

Can I pass parameters by reference in Java?

No.

Why ? Java has only one mode of passing arguments to methods: by value.

Note:

For primitives this is easy to understand: you get a copy of the value.

For all other you get a copy of the reference and this is called also passing by value.

It is all in this picture:

enter image description here

add elements to object array

If you can, use a List<Subject> instead of Subject[]... this will let you do Student.Subject.Add(new Subject()). If that is not possible, you'll have to resize your array... look at Array.Resize() at http://msdn.microsoft.com/en-us/library/bb348051.aspx

How do I make a C++ console program exit?

Allowing the execution flow to leave main by returning a value or allowing execution to reach the end of the function is the way a program should terminate except under unrecoverable circumstances. Returning a value is optional in C++, but I typically prefer to return EXIT_SUCCESS found in cstdlib (a platform-specific value that indicates the program executed successfully).

#include <cstdlib>

int main(int argc, char *argv[]) {
  ...
  return EXIT_SUCCESS;
}

If, however, your program reaches an unrecoverable state, it should throw an exception. It's important to realise the implications of doing so, however. There are no widely-accepted best practices for deciding what should or should not be an exception, but there are some general rules you need to be aware of.

For example, throwing an exception from a destructor is nearly always a terrible idea because the object being destroyed might have been destroyed because an exception had already been thrown. If a second exception is thrown, terminate is called and your program will halt without any further clean-up having been performed. You can use uncaught_exception to determine if it's safe, but it's generally better practice to never allow exceptions to leave a destructor.

While it's generally always possible for functions you call but didn't write to throw exceptions (for example, new will throw std::bad_alloc if it can't allocate enough memory), it's often difficult for beginner programmers to keep track of or even know about all of the special rules surrounding exceptions in C++. For this reason, I recommend only using them in situations where there's no sensible way for your program to continue execution.

#include <stdexcept>
#include <cstdlib>
#include <iostream>

int foo(int i) {
  if (i != 5) {
    throw std::runtime_error("foo: i is not 5!");
  }
  return i * 2;
}

int main(int argc, char *argv[]) {
  try {
    foo(3);
  }
  catch (const std::exception &e) {
    std::cout << e.what() << std::endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}

exit is a hold-over from C and may result in objects with automatic storage to not be cleaned up properly. abort and terminate effectively causes the program to commit suicide and definitely won't clean up resources.

Whatever you do, don't use exceptions, exit, or abort/terminate as a crutch to get around writing a properly structured program. Save them for exceptional situations.

Java balanced expressions check {[()]}

**// balanced parentheses problem (By fabboys)**
#include <iostream>
#include <string.h>

using namespace std;

class Stack{

char *arr;
int size;
int top;

public:

Stack(int s)
{
  size = s;
  arr = new char[size];
  top = -1;
}

bool isEmpty()
{
  if(top == -1)
    return true;
 else
    return false;
 }

 bool isFull()
 {
  if(top == size-1)
    return true;
 else
    return false;
 }


 void push(char n)
 {
 if(isFull() == false)
 {
     top++;
     arr[top] = n;
 }
}

char pop()
{
 if(isEmpty() == false)
 {
     char x = arr[top];
     top--;
     return x;
 }
 else
    return -1;
}

char Top()
{
 if(isEmpty() == false)
 {
    return arr[top];
 }
 else
    return -1;
}
Stack{
 delete []arr;
 }

};

int main()
{
int size=0;


string LineCode;
cout<<"Enter a String : ";
  cin >> LineCode;



    size = LineCode.length();

    Stack s1(size);


    char compare;

    for(int i=0;i<=size;i++)
    {

 if(LineCode[i]=='(' || LineCode[i] == '{' || LineCode[i] =='[')

 s1.push(LineCode[i]);

 else if(LineCode[i]==']')
 {
     if(s1.isEmpty()==false){
                    compare =  s1.pop();
                if(compare == 91){}
                    else
                        {
                        cout<<" Error Founded";
                            return 0;}
        }
            else
            {
               cout<<" Error Founded";
               return 0;
            }

 } else if(LineCode[i] == ')')
 {
     if(s1.isEmpty() == false)
     {
         compare = s1.pop();
         if(compare == 40){}
         else{
            cout<<" Error Founded";
                            return 0;
         }
     }else
     {
        cout<<"Error Founded";
               return 0;
     }
 }else if(LineCode[i] == '}')
 {
       if(s1.isEmpty() == false)
     {
         compare = s1.pop();
         if(compare == 123){}
         else{
            cout<<" Error Founded";
                            return 0;
         }
     }else
     {
        cout<<" Error Founded";
               return 0;
     }


 }
}

if(s1.isEmpty()==true)
{
    cout<<"No Error in Program:\n";
}
else
{
     cout<<" Error Founded";
}

 return 0;
}

how to make a div to wrap two float divs inside?

Here's another, I found helpful. It works even for Responsive CSS design too.

#wrap
{
   display: table;
   table-layout: fixed; /* it'll enable the div to be responsive */
   width: 100%; /* as display table will shrink the div to content-wide */
}

WARNING: But this theory won't work for holder contains inner elements with absolute positions. And it will create problem for fixed-width layout. But for responsive design, it's just excellent. :)

ADDITION TO Meep3D's ANSWER

With CSS3, in a dynamic portion, you can add clear float to the last element by:

#wrap [class*='my-div-class']:last-of-type {
  display: block;
  clear: both;
}

Where your divs are:

<div id="wrap">
<?php for( $i = 0; $i < 3; $i++ ) {
   <div class="my-div-class-<?php echo $i ?>>
      <p>content</p>
   </div> <!-- .my-div-class-<?php echo $i ?> -->
}
</div>

Reference:

Check if argparse optional argument is set or not

In order to address @kcpr's comment on the (currently accepted) answer by @Honza Osobne

Unfortunately it doesn't work then the argument got it's default value defined.

one can first check if the argument was provided by comparing it with the Namespace object and providing the default=argparse.SUPPRESS option (see @hpaulj's and @Erasmus Cedernaes answers and this python3 doc) and if it hasn't been provided, then set it to a default value.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--infile', default=argparse.SUPPRESS)
args = parser.parse_args()
if 'infile' in args: 
    # the argument is in the namespace, it's been provided by the user
    # set it to what has been provided
    theinfile = args.infile
    print('argument \'--infile\' was given, set to {}'.format(theinfile))
else:
    # the argument isn't in the namespace
    # set it to a default value
    theinfile = 'your_default.txt'
    print('argument \'--infile\' was not given, set to default {}'.format(theinfile))

Usage

$ python3 testargparse_so.py
argument '--infile' was not given, set to default your_default.txt

$ python3 testargparse_so.py --infile user_file.txt
argument '--infile' was given, set to user_file.txt

Match line break with regular expression

You could search for:

<li><a href="#">[^\n]+

And replace with:

$0</a>

Where $0 is the whole match. The exact semantics will depend on the language are you using though.


WARNING: You should avoid parsing HTML with regex. Here's why.

How do you get the path to the Laravel Storage folder?

You can use the storage_path(); function to get storage folder path.

storage_path(); // Return path like: laravel_app\storage

Suppose you want to save your logfile mylog.log inside Log folder of storage folder. You have to write something like

storage_path() . '/LogFolder/mylog.log'

how to add script inside a php code?

You mean you want to show a javascript alert when a button is clicked on a PHP generated page?

echo('<button type="button" onclick="alert(\'Alrt Text!\');">My Button</button>');

Would do that

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

You can use RTRIM or cast your value to VARCHAR:

SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)

Or

SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)

Stretch horizontal ul to fit width of div

This is the easiest way to do it: http://jsfiddle.net/thirtydot/jwJBd/

(or with table-layout: fixed for even width distribution: http://jsfiddle.net/thirtydot/jwJBd/59/)

This won't work in IE7.

#horizontal-style {
    display: table;
    width: 100%;
    /*table-layout: fixed;*/
}
#horizontal-style li {
    display: table-cell;
}
#horizontal-style a {
    display: block;
    border: 1px solid red;
    text-align: center;
    margin: 0 5px;
    background: #999;
}

Old answer before your edit: http://jsfiddle.net/thirtydot/DsqWr/

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

Using freegate as agent in China. Run Freegate,latest version. Run SDK Manager, Tools -> Options, Proxy Server 127.0.0.1, Port 8580. I hope it will help you.

How ViewBag in ASP.NET MVC works

It's a dynamic object, meaning you can add properties to it in the controller, and read them later in the view, because you are essentially creating the object as you do, a feature of the dynamic type. See this MSDN article on dynamics. See this article on it's usage in relation to MVC.

If you wanted to use this for web forms, add a dynamic property to a base page class like so:

public class BasePage : Page
{

    public dynamic ViewBagProperty
    {
        get;
        set;
    }
}

Have all of your pages inherit from this. You should be able to, in your ASP.NET markup, do:

<%= ViewBagProperty.X %>

That should work. If not, there are ways to work around it.

How to center links in HTML

The <p> will show up on a new line. Try wrapping all of your links in one single <p> tag:

<p style="text-align:center;"><a href="http//www.google.com">Search</a><a href="Contact Us">Contact Us</a></p>

How to show math equations in general github's markdown(not github's blog)

Regarding tex?image conversion, the tool LaTeXiT produces much higher quality output. I believe it is standard in most TeX distributions but you can certainly find it online if you don't already have it. All you need to do is put it in the TeX, drag the image to your desktop, then drag from your desktop to an image hosting site (I use imgur).

How to format a phone number with jQuery

Quick roll your own code:

Here is a solution modified from Cruz Nunez's solution above.

// Used to format phone number
function phoneFormatter() {
  $('.phone').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length < 7) {
      number = number.replace(/(\d{0,3})(\d{0,3})/, "($1) $2");
    } else if (number.length <= 10) {
    number = number.replace(/(\d{3})(\d{3})(\d{1,4})/, "($1) $2-$3");
    } else {
    // ignore additional digits
    number = number.replace(/(\d{3})(\d{1,3})(\d{1,4})(\d.*)/, "($1) $2-$3");
    }
    $(this).val(number)
  });
};

$(phoneFormatter);

JSFiddle

  • In this solution, the formatting is applied no matter how many digits the user has entered. (In Nunes' solution, the formatting is applied only when exactly 7 or 10 digits has been entered.)

  • It requires the zip code for a 10-digit US phone number to be entered.

  • Both solutions, however, editing already entered digits is problematic, as typed digits always get added to the end.

  • I recommend, instead, the robust jQuery Mask Plugin code, mentioned below:

Recommend jQuery Mask Plugin

I recommend using jQuery Mask Plugin (page has live examples), on github.
These links have minimal explanations on how to use:

CDN
Instead of installing/hosting the code, you can also add a link to a CDN of the script CDN Link for jQuery Mask Plugin
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>

or
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>

WordPress Contact Form 7: use Masks Form Fields plugin

If you are using Contact Form 7 plugin on a WordPress site, the easiest option to control form fields is if you can simply add a class to your input field to take care of it for you.
Masks Form Fields plugin is one option that makes this easy to do.
I like this option, as, Internally, it embeds a minimized version of the code from jQuery Mask Plugin mentioned above.

Example usage on a Contact Form 7 form:

<label> Your Phone Number (required)
    [tel* customer-phone class:phone_us minlength:14 placeholder "(555) 555-5555"]
</label>

The important part here is class:phone_us.
Note that if you use minlength/maxlength, the length must include the mask characters, in addition to the digits.