Programs & Examples On #Isolatedstoragefile

How to upload file to server with HTTP POST multipart/form-data?

Here's my final working code. My web service needed one file (POST parameter name was "file") & a string value (POST parameter name was "userid").

/// <summary>
/// Occurs when upload backup application bar button is clicked. Author : Farhan Ghumra
 /// </summary>
private async void btnUploadBackup_Click(object sender, EventArgs e)
{
    var dbFile = await ApplicationData.Current.LocalFolder.GetFileAsync(Util.DBNAME);
    var fileBytes = await GetBytesAsync(dbFile);
    var Params = new Dictionary<string, string> { { "userid", "9" } };
    UploadFilesToServer(new Uri(Util.UPLOAD_BACKUP), Params, Path.GetFileName(dbFile.Path), "application/octet-stream", fileBytes);
}

/// <summary>
/// Creates HTTP POST request & uploads database to server. Author : Farhan Ghumra
/// </summary>
private void UploadFilesToServer(Uri uri, Dictionary<string, string> data, string fileName, string fileContentType, byte[] fileData)
{
    string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
    httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    httpWebRequest.Method = "POST";
    httpWebRequest.BeginGetRequestStream((result) =>
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            using (Stream requestStream = request.EndGetRequestStream(result))
            {
                WriteMultipartForm(requestStream, boundary, data, fileName, fileContentType, fileData);
            }
            request.BeginGetResponse(a =>
            {
                try
                {
                    var response = request.EndGetResponse(a);
                    var responseStream = response.GetResponseStream();
                    using (var sr = new StreamReader(responseStream))
                    {
                        using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                        {
                            string responseString = streamReader.ReadToEnd();
                            //responseString is depend upon your web service.
                            if (responseString == "Success")
                            {
                                MessageBox.Show("Backup stored successfully on server.");
                            }
                            else
                            {
                                MessageBox.Show("Error occurred while uploading backup on server.");
                            } 
                        }
                    }
                }
                catch (Exception)
                {

                }
            }, null);
        }
        catch (Exception)
        {

        }
    }, httpWebRequest);
}

/// <summary>
/// Writes multi part HTTP POST request. Author : Farhan Ghumra
/// </summary>
private void WriteMultipartForm(Stream s, string boundary, Dictionary<string, string> data, string fileName, string fileContentType, byte[] fileData)
{
    /// The first boundary
    byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
    /// the last boundary.
    byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
    /// the form data, properly formatted
    string formdataTemplate = "Content-Dis-data; name=\"{0}\"\r\n\r\n{1}";
    /// the form-data file upload, properly formatted
    string fileheaderTemplate = "Content-Dis-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type: {2}\r\n\r\n";

    /// Added to track if we need a CRLF or not.
    bool bNeedsCRLF = false;

    if (data != null)
    {
        foreach (string key in data.Keys)
        {
            /// if we need to drop a CRLF, do that.
            if (bNeedsCRLF)
                WriteToStream(s, "\r\n");

            /// Write the boundary.
            WriteToStream(s, boundarybytes);

            /// Write the key.
            WriteToStream(s, string.Format(formdataTemplate, key, data[key]));
            bNeedsCRLF = true;
        }
    }

    /// If we don't have keys, we don't need a crlf.
    if (bNeedsCRLF)
        WriteToStream(s, "\r\n");

    WriteToStream(s, boundarybytes);
    WriteToStream(s, string.Format(fileheaderTemplate, "file", fileName, fileContentType));
    /// Write the file data to the stream.
    WriteToStream(s, fileData);
    WriteToStream(s, trailer);
}

/// <summary>
/// Writes string to stream. Author : Farhan Ghumra
/// </summary>
private void WriteToStream(Stream s, string txt)
{
    byte[] bytes = Encoding.UTF8.GetBytes(txt);
    s.Write(bytes, 0, bytes.Length);
}

/// <summary>
/// Writes byte array to stream. Author : Farhan Ghumra
/// </summary>
private void WriteToStream(Stream s, byte[] bytes)
{
    s.Write(bytes, 0, bytes.Length);
}

/// <summary>
/// Returns byte array from StorageFile. Author : Farhan Ghumra
/// </summary>
private async Task<byte[]> GetBytesAsync(StorageFile file)
{
    byte[] fileBytes = null;
    using (var stream = await file.OpenReadAsync())
    {
        fileBytes = new byte[stream.Size];
        using (var reader = new DataReader(stream))
        {
            await reader.LoadAsync((uint)stream.Size);
            reader.ReadBytes(fileBytes);
        }
    }

    return fileBytes;
}

I am very much thankful to Darin Rousseau for helping me.

Nested routes with react router v4 / v5

react-router v6

Update for 2021

The upcoming v6 will have nested Route components that Just Work™

See example code in this blog post

The question is about v4/v5, but when v6 ships the correct answer will be just use that if you can.


react-router v4 & v5

It's true that in order to nest Routes you need to place them in the child component of the Route.

However if you prefer a more inline syntax rather than breaking your Routes up across components, you can provide a functional component to the render prop of the Route you want to nest under.

<BrowserRouter>

  <Route path="/" component={Frontpage} exact />
  <Route path="/home" component={HomePage} />
  <Route path="/about" component={AboutPage} />

  <Route
    path="/admin"
    render={({ match: { url } }) => (
      <>
        <Route path={`${url}/`} component={Backend} exact />
        <Route path={`${url}/home`} component={Dashboard} />
        <Route path={`${url}/users`} component={UserPage} />
      </>
    )}
  />

</BrowserRouter>

If you're interested in why the render prop should be used, and not the component prop, it's because it stops the inline functional component from being remounted on every render. See the documentation for more detail.

Note that the example wraps the nested Routes in a Fragment. Prior to React 16, you can use a container <div> instead.

Get an object's class name at runtime

See this question.

Since TypeScript is compiled to JavaScript, at runtime you are running JavaScript, so the same rules will apply.

Python regular expressions return true/false

If you really need True or False, just use bool

>>> bool(re.search("hi", "abcdefghijkl"))
True
>>> bool(re.search("hi", "abcdefgijkl"))
False

As other answers have pointed out, if you are just using it as a condition for an if or while, you can use it directly without wrapping in bool()

How can I send an xml body using requests library?

Just send xml bytes directly:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests

xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text

Output

{
  "origin": "x.x.x.x",
  "files": {},
  "form": {},
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "48",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Connection": "keep-alive",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
    "Host": "httpbin.org",
    "Content-Type": "application/xml"
  },
  "json": null,
  "data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}

How do you easily horizontally center a <div> using CSS?

you can use the position:relative; and then set the left and the top values:

.cenverDiv{
    position:relative;
    left:30%;
    top:0px;
}

Cannot resolve symbol 'AppCompatActivity'

If all else has failed, make sure you have added the import statement. I had removed it as it was showing error and forgot to add it back and was trying everything else to fix:

import android.support.v7.app.AppCompatActivity;

Pass entire form as data in jQuery Ajax function

A good jQuery option to do this is through FormData. This method is also suited when sending files through a form!

<form id='test' method='post' enctype='multipart/form-data'>
   <input type='text' name='testinput' id='testinput'>
   <button type='submit'>submit</button>
</form>

Your send function in jQuery would look like this:

$( 'form#test' ).submit( function(){
   var data = new FormData( $( 'form#test' )[ 0 ] );

   $.ajax( {
      processData: false,
      contentType: false,

      data: data,
      dataType: 'json',
      type: $( this ).attr( 'method' );
      url: 'yourapi.php',
      success: function( feedback ){
         console.log( "the feedback from your API: " + feedback );
      }
});

to add data to your form you can either use a hidden input in your form, or you add it on the fly:

var data = new FormData( $( 'form#test' )[ 0 ] );
data.append( 'command', 'value_for_command' );

Does a TCP socket connection have a "keep alive"?

TCP keepalive and HTTP keepalive are very different concepts. In TCP, the keepalive is the administrative packet sent to detect stale connection. In HTTP, keepalive means the persistent connection state.

This is from TCP specification,

Keep-alive packets MUST only be sent when no data or acknowledgement packets have been received for the connection within an interval. This interval MUST be configurable and MUST default to no less than two hours.

As you can see, the default TCP keepalive interval is too long for most applications. You might have to add keepalive in your application protocol.

How to determine the version of Gradle?

I found the solution Do change in your cordovaLib file build.gradle file

dependencies { classpath 'com.android.tools.build:gradle:3.1.0' }

and now make changes in you,

platforms\android\gradle\wrapper\gradle-wrapper.properties

distributionUrl=\
https://services.gradle.org/distributions/gradle-4.4-all.zip

this works for.

How to read the value of a private field from a different class in Java?

Try FieldUtils from apache commons-lang3:

FieldUtils.readField(object, fieldName, true);

jQuery loop over JSON result from AJAX Success?

Access the json array like you would any other array.

for(var i =0;i < itemData.length-1;i++)
{
  var item = itemData[i];
  alert(item.Test1 + item.Test2 + item.Test3);
}

How can I inspect the file system of a failed `docker build`?

Everytime docker successfully executes a RUN command from a Dockerfile, a new layer in the image filesystem is committed. Conveniently you can use those layers ids as images to start a new container.

Take the following Dockerfile:

FROM busybox
RUN echo 'foo' > /tmp/foo.txt
RUN echo 'bar' >> /tmp/foo.txt

and build it:

$ docker build -t so-2622957 .
Sending build context to Docker daemon 47.62 kB
Step 1/3 : FROM busybox
 ---> 00f017a8c2a6
Step 2/3 : RUN echo 'foo' > /tmp/foo.txt
 ---> Running in 4dbd01ebf27f
 ---> 044e1532c690
Removing intermediate container 4dbd01ebf27f
Step 3/3 : RUN echo 'bar' >> /tmp/foo.txt
 ---> Running in 74d81cb9d2b1
 ---> 5bd8172529c1
Removing intermediate container 74d81cb9d2b1
Successfully built 5bd8172529c1

You can now start a new container from 00f017a8c2a6, 044e1532c690 and 5bd8172529c1:

$ docker run --rm 00f017a8c2a6 cat /tmp/foo.txt
cat: /tmp/foo.txt: No such file or directory

$ docker run --rm 044e1532c690 cat /tmp/foo.txt
foo

$ docker run --rm 5bd8172529c1 cat /tmp/foo.txt
foo
bar

of course you might want to start a shell to explore the filesystem and try out commands:

$ docker run --rm -it 044e1532c690 sh      
/ # ls -l /tmp
total 4
-rw-r--r--    1 root     root             4 Mar  9 19:09 foo.txt
/ # cat /tmp/foo.txt 
foo

When one of the Dockerfile command fails, what you need to do is to look for the id of the preceding layer and run a shell in a container created from that id:

docker run --rm -it <id_last_working_layer> bash -il

Once in the container:

  • try the command that failed, and reproduce the issue
  • then fix the command and test it
  • finally update your Dockerfile with the fixed command

If you really need to experiment in the actual layer that failed instead of working from the last working layer, see Drew's answer.

Currently running queries in SQL Server

There's this, from SQL Server DMV's In Action book:

The output shows the spid (process identifier), the ecid (this is similar to a thread within the same spid and is useful for identifying queries running in parallel), the user running the SQL, the status (whether the SQL is running or waiting), the wait status (why it’s waiting), the hostname, the domain name, and the start time (useful for determining how long the batch has been running).

The nice part is the query and parent query. That shows, for example, a stored proc as the parent and the query within the stored proc that is running. It has been very handy for me. I hope this helps someone else.

USE master
GO
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
er.session_Id AS [Spid]
, sp.ecid
, er.start_time
, DATEDIFF(SS,er.start_time,GETDATE()) as [Age Seconds]
, sp.nt_username
, er.status
, er.wait_type
, SUBSTRING (qt.text, (er.statement_start_offset/2) + 1,
((CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE er.statement_end_offset
END - er.statement_start_offset)/2) + 1) AS [Individual Query]
, qt.text AS [Parent Query]
, sp.program_name
, sp.Hostname
, sp.nt_domain


FROM sys.dm_exec_requests er
INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
WHERE session_Id > 50
AND session_Id NOT IN (@@SPID)
ORDER BY session_Id, ecid

How to add row of data to Jtable from values received from jtextfield and comboboxes

Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder

  • Set the table column headers
    1. Highglight the table in the design view then go to properties pane on the very right. Should be a tab that says "Properties". Make sure to highlight the table and not the scroll pane surrounding it, or the next step wont work
    2. Click on the ... button to the right of the property model. A dialog should appear.
    3. Set rows to 0, set the number of columns you want, and their names.
  • Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row

    1. Right-click on the button and select Events -> Action -> actionPerformed
    2. You should see code like the following auto-generated

      private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
      
  • The jTable1 will have a DefaultTableModel. You can add rows to the model with your data

    private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
        String data1 = something1.getSomething();
        String data2 = something2.getSomething();
        String data3 = something3.getSomething();
        String data4 = something4.getSomething();
    
        Object[] row = { data1, data2, data3, data4 };
    
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    
        model.addRow(row);
    
        // clear the entries.
    }
    

So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.

Force IE10 to run in IE10 Compatibility View?

I had the same problem. The problem is a bug in MSIE 10, so telling people to fix their issues isn't helpful. Neither is telling visitors to your site to add your site to compatibility view, bleh. In my case, the problem was that the following code displayed no text:

document.write ('<P>'); 
document.write ('Blah, blah, blah... ');
document.write ('</P>');

After much trial and error, I determined that removing the <P> and </P> tags caused the text to appear properly on the page (thus, the problem IS with document mode rather than browser mode, at least in my case). Removing the <P> tags when userAgent is MSIE is not a "fix" I want to put into my pages.

The solution, as others have said, is:

<!DOCTYPE HTML whatever doctype you're using....> 
<HTML>
 <HEAD>
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
  <TITLE>Blah...

Yes, the meta tag has to be the FIRST tag after HEAD.

How do you append rows to a table using jQuery?

Add as first row or last row in a table

To add as first row in table

$(".table tbody").append("<tr><td>New row</td></tr>");

To add as last row in table

$(".table tbody").prepend("<tr><td>New row</td></tr>");

How do we use runOnUiThread in Android?

If using in fragment then simply write

getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Do something on UiThread
    }
});

Creating an array of objects in Java

The genaral form to declare a new array in java is as follows:

type arrayName[] = new type[numberOfElements];

Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).

Lets initialize an array to store the salaries of all employees in a small company of 5 people:

int salaries[] = new int[5];

The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.

Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:

int salaries[] = {50000, 75340, 110500, 98270, 39400};

Or to do it at a later point like this:

salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;

More visual example of array creation: enter image description here

To learn more about Arrays, check out the guide.

How can I set the Secure flag on an ASP.NET Session Cookie?

In the <system.web> element, add the following element:

<httpCookies requireSSL="true" />

However, if you have a <forms> element in your system.web\authentication block, then this will override the setting in httpCookies, setting it back to the default false.

In that case, you need to add the requireSSL="true" attribute to the forms element as well.

So you will end up with:

<system.web>
    <authentication mode="Forms">
        <forms requireSSL="true">
            <!-- forms content -->
        </forms>
    </authentication>
</system.web>

See here and here for MSDN documentation of these elements.

How to select the row with the maximum value in each group

One more base R solution:

merge(aggregate(pt ~ Subject, max, data = group), group)

  Subject pt Event
1       1  5     2
2       2 17     2
3       3  5     2

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

How to get input textfield values when enter key is pressed in react js?

html

<input id="something" onkeyup="key_up(this)" type="text">

script

function key_up(e){
    var enterKey = 13; //Key Code for Enter Key
    if (e.which == enterKey){
        //Do you work here
    }
}

Next time, Please try providing some code.

launch sms application with an intent

If android version is Kitkat or above, users can change default sms application. This method will get default sms app and start default sms app.

private void sendSMS() {    
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) // At least KitKat
      {
         String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(this); // Need to change the build to API 19

         Intent sendIntent = new Intent(Intent.ACTION_SEND);
         sendIntent.setType("text/plain");
         sendIntent.putExtra(Intent.EXTRA_TEXT, "text");

         if (defaultSmsPackageName != null)// Can be null in case that there is no default, then the user would be able to choose
         // any app that support this intent.
         {
            sendIntent.setPackage(defaultSmsPackageName);
         }
         startActivity(sendIntent);

      }
      else // For early versions, do what worked for you before.
      {
         Intent smsIntent = new Intent(android.content.Intent.ACTION_VIEW);
         smsIntent.setType("vnd.android-dir/mms-sms");
         smsIntent.putExtra("address","phoneNumber");         
         smsIntent.putExtra("sms_body","message");
         startActivity(smsIntent);
      }
   }

Iterating over JSON object in C#

dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
    Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName, 
        item.slug, item.imageUrl);
}

or

var list = JsonConvert.DeserializeObject<List<MyItem>>(json);

public class MyItem
{
    public string id;
    public string displayName;
    public string name;
    public string slug;
    public string imageUrl;
}

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

JSON Naming Convention (snake_case, camelCase or PascalCase)

There is no SINGLE standard, but I have seen 3 styles you mention ("Pascal/Microsoft", "Java" (camelCase) and "C" (underscores, snake_case)) -- as well as at least one more, kebab-case like longer-name).

It mostly seems to depend on what background developers of the service in question had; those with c/c++ background (or languages that adopt similar naming, which includes many scripting languages, ruby etc) often choose underscore variant; and rest similarly (Java vs .NET). Jackson library that was mentioned, for example, assumes Java bean naming convention (camelCase)

UPDATE: my definition of "standard" is a SINGLE convention. So while one could claim "yes, there are many standards", to me there are multiple Naming Conventions, none of which is "The" standard overall. One of them could be considered the standard for specific platform, but given that JSON is used for interoperability between platforms that may or may not make much sense.

Add custom message to thrown exception while maintaining stack trace in Java

There is an Exception constructor that takes also the cause argument: Exception(String message, Throwable t).

You can use it to propagate the stacktrace:

try{
    //...
}catch(Exception E){
    if(!transNbr.equals("")){
        throw new Exception("transaction: " + transNbr, E); 
    }
    //...
}

Return list from async/await method

You need to correct your code to wait for the list to be downloaded:

List<Item> list = await GetListAsync();

Also, make sure that the method, where this code is located, has async modifier.

The reason why you get this error is that GetListAsync method returns a Task<T> which is not a completed result. As your list is downloaded asynchronously (because of Task.Run()) you need to "extract" the value from the task using the await keyword.

If you remove Task.Run(), you list will be downloaded synchronously and you don't need to use Task, async or await.

One more suggestion: you don't need to await in GetListAsync method if the only thing you do is just delegating the operation to a different thread, so you can shorten your code to the following:

private Task<List<Item>> GetListAsync(){
    return Task.Run(() => manager.GetList());
}

Convert xlsx to csv in Linux with command line

Use csvkit

in2csv data.xlsx > data.csv

For details check their excellent docs

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

My +1 to mata's comment at https://stackoverflow.com/a/10561979/1346705 and to the Nick Craig-Wood's demonstration. You have decoded the string correctly. The problem is with the print command as it converts the Unicode string to the console encoding, and the console is not capable to display the string. Try to write the string into a file and look at the result using some decent editor that supports Unicode:

import codecs

s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
s1 = s.decode('utf-8')
f = codecs.open('out.txt', 'w', encoding='utf-8')
f.write(s1)
f.close()

Then you will see (?????)?.

SQL Server 2005 Setting a variable to the result of a select query

You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.

Incidentally, since you are using a predicate like this:

CONVERT(...) = CONVERT(...)

that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.

Here is one way to make the original query somewhat better:

DECLARE @ooDate datetime
SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  FF.FaultDate >= @ooDate AND
  FF.FaultDate < DATEADD(day, 1, @ooDate) AND
  OFIO.OutageID = 1

This version could leverage in index that involved FaultDate, and achieves the same goal.

Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
  OFIO.OutageID = 1

Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.

Regards.

"Proxy server connection failed" in google chrome

  1. Open Google Chrome.
  2. Click Menu on the upper right side. Beside the STAR symbol (Bookmark).
  3. Click Show Advanced Settings.
  4. Scroll down and find Network.
  5. Click Change proxy settings.
  6. On the Connections tab, click LAN settings.
  7. Uncheck "Use a proxy server for your LAN."
  8. Then click OK.

Hope it helps .

Displaying Image in Java

If you want to load/process/display images I suggest you use an image processing framework. Using Marvin, for instance, you can do that easily with just a few lines of source code.

Source code:

public class Example extends JFrame{

    MarvinImagePlugin prewitt           = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.prewitt");
    MarvinImagePlugin errorDiffusion    = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion");
    MarvinImagePlugin emboss            = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.emboss");

    public Example(){
        super("Example");

        // Layout
        setLayout(new GridLayout(2,2));

        // Load images
        MarvinImage img1 = MarvinImageIO.loadImage("./res/car.jpg");
        MarvinImage img2 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img3 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img4 = new MarvinImage(img1.getWidth(), img1.getHeight());

        // Image Processing plug-ins
        errorDiffusion.process(img1, img2);
        prewitt.process(img1, img3);
        emboss.process(img1, img4);

        // Set panels
        addPanel(img1);
        addPanel(img2);
        addPanel(img3);
        addPanel(img4);

        setSize(560,380);
        setVisible(true);
    }

    public void addPanel(MarvinImage image){
        MarvinImagePanel imagePanel = new MarvinImagePanel();
        imagePanel.setImage(image);
        add(imagePanel);
    }

    public static void main(String[] args) {
        new Example().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Output:

enter image description here

Core dumped, but core file is not in the current directory?

My efforts in WSL have been unsuccessful.

For those running on Windows Subsystem for Linux (WSL) there seems to be an open issue at this time for missing core dump files.

The comments indicate that

This is a known issue that we are aware of, it is something we are investigating.

Github issue

Windows Developer Feedback

psql: server closed the connection unexepectedly

If you are using Docker make sure you are not using the same port in another service, in my case i was mistakenly using the same port for both PostgreSQL and Redis.

How to use store and use session variables across pages?

In the possibility that the second page doesn't have shared access to the session cookie, you'll need to set the session cookie path using session_set_cookie_params:

<?php
session_set_cookie_params( $lifetime, '/shared/path/to/files/' );
session_start();
$_SESSION['myvar']='myvalue';

And

<?php
session_set_cookie_params( $lifetime, '/shared/path/to/files/' );
session_start();
echo("1");
if(isset($_SESSION['myvar']))
{
    echo("2");
   if($_SESSION['myvar'] == 'myvalue')
   {
       echo("3");
       exit;
   }
}

JAVA Unsupported major.minor version 51.0

The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.

For Ubuntu use

apt-get install openjdk-7-jdk

to get Java 7 as default. You may have to uninstall openjdk-6 first.

Prevent PDF file from downloading and printing

That is not possible. Reading is downloading. When a user is reading a file, browser is downloading that file to temp. So even if you disable the download button, the user can click "File -> Save As" or copy that file from temp folder.

There are a few things you can do:

Method 1

The following code will embed a PDF without any toolbars and hide the print/download icons

<embed src="{URL_TO_PDF.PDF}#toolbar=0&navpanes=0&scrollbar=0" width="425" height="425">

Method 02

Using Google Drive

Right click on pdf and goto Share(below image)

enter image description here

Then go to Advanced option in left bottom

enter image description here

Tick Both check boxes. After copy embed link and paste it to your src. No download and Save drive option is not allowed

Git - Pushing code to two remotes

To send to both remote with one command, you can create a alias for it:

git config alias.pushall '!git push origin devel && git push github devel'

With this, when you use the command git pushall, it will update both repositories.

show distinct column values in pyspark dataframe: python

You can use df.dropDuplicates(['col1','col2']) to get only distinct rows based on colX in the array.

Getting The ASCII Value of a character in a C# string

Here's an alternative since you don't like the cast to int:

foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))
    Console.Write(b.ToString());

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

2 month old thread, but better late than never! On 10.6, I have my webserver documents folder set to:

owner:root
group:_www
permission:755

_www is the user that runs apache under Mac OS X. I then added an ACL to allow full permissions to the Administrators group. That way, I can still make any changes with my admin user without having to authenticate as root. Also, when I want to allow the webserver to write to a folder, I can simply chmod to 775, leaving everyone other than root:_www with only read/execute permissions (excluding any ACLs that I have applied)

Infinite Recursion with Jackson JSON and Hibernate JPA issue

I'm a late comer and it's such a long thread already. But I spent a couple of hours trying to figure this out too, and would like to give my case as another example.

I tried both JsonIgnore, JsonIgnoreProperties and BackReference solutions, but strangely enough it was like they weren't picked up.

I used Lombok and thought that maybe it interferes, since it creates constructors and overrides toString (saw toString in stackoverflowerror stack).

Finally it wasn't Lombok's fault - I used automatic NetBeans generation of JPA entities from database tables, without giving it much thought - well, and one of the annotations that were added to the generated classes was @XmlRootElement. Once I removed it everything started working. Oh well.

Escape string Python for MySQL

>>> import MySQLdb
>>> example = r"""I don't like "special" chars ¯\_(?)_/¯"""
>>> example
'I don\'t like "special" chars \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf'
>>> MySQLdb.escape_string(example)
'I don\\\'t like \\"special\\" chars \xc2\xaf\\\\_(\xe3\x83\x84)_/\xc2\xaf'

How to Debug Variables in Smarty like in PHP var_dump()

Try out with the Smarty Session:

{$smarty.session|@debug_print_var}

or

{$smarty.session|@print_r}

To beautify your output, use it between <pre> </pre> tags

calling parent class method from child class object in java

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

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

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

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

This would print:

I'm the child.

Uncomment the commented line and it would print:

I'm the parent.

I'm the child.

You should look for the concept of Polymorphism.

Curl : connection refused

Try curl -v http://localhost:8080/ instead of 127.0.0.1

HTML: How to make a submit button with text + image in it?

You're really close to the answer yourself

<button type="submit">
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>

Or, you can just remove the type-attribute

<button>
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>

PostgreSQL database default location on Linux

/var/lib/postgresql/[version]/data/

At least in Gentoo Linux and Ubuntu 14.04 by default.

You can find postgresql.conf and look at param data_directory. If it is commented then database directory is the same as this config file directory.

Calling a Javascript Function from Console

I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:

function indirect(js) { return eval(js); }

With that function in each module, you can then execute any code in the context of it.

E.g. if you had this import in your module:

import { imported_fn } from "./import.js";

You could then get the results of calling imported_fn from the console by doing this:

indirect("imported_fn()");

Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.

What does collation mean?

The collation is how SQL server decides on how to sort and compare text.

See MSDN.

How to pass parameter to a promise function

Even shorter

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

datatable jquery - table header width not aligned with body width

I had a similar issue. I would create tables in expandable/collapsible panels. As long as the tables were visible, no problem. But if you collapsed a panel, resized the browser, and then expanded, the problem was there. I fixed it by placing the following in the click function for the panel header, whenever this function expanded the panel:

            // recalculate column widths, because they aren't recalculated when the table is hidden'
            $('.homeTable').DataTable()
                .columns.adjust()
                .responsive.recalc();

html select scroll bar

Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:

1. First create a css class

<style type="text/css">
 .scrollable{
   overflow: auto;
   width: 70px; /* adjust this width depending to amount of text to display */
   height: 80px; /* adjust height depending on number of options to display */
   border: 1px silver solid;
 }
 .scrollable select{
   border: none;
 }
</style>

2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.

<div class="scrollable">
<select size="6" multiple="multiple">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>
</div>

Get index of current item in a PowerShell loop

.NET has some handy utility methods for this sort of thing in System.Array:

PS> $a = 'a','b','c'
PS> [array]::IndexOf($a, 'b')
1
PS> [array]::IndexOf($a, 'c')
2

Good points on the above approach in the comments. Besides "just" finding an index of an item in an array, given the context of the problem, this is probably more suitable:

$letters = { 'A', 'B', 'C' }
$letters | % {$i=0} {"Value:$_ Index:$i"; $i++}

Foreach (%) can have a Begin sciptblock that executes once. We set an index variable there and then we can reference it in the process scripblock where it gets incremented before exiting the scriptblock.

Laravel Eloquent Join vs Inner Join?

I'm sure there are other ways to accomplish this, but one solution would be to use join through the Query Builder.

If you have tables set up something like this:

users
    id
    ...

friends
    id
    user_id
    friend_id
    ...

votes, comments and status_updates (3 tables)
    id
    user_id
    ....

In your User model:

class User extends Eloquent {
    public function friends()
    {
        return $this->hasMany('Friend');
    }
}

In your Friend model:

class Friend extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:

$user = User::find(1);
$friends_votes = $user->friends()
    ->with('user') // bring along details of the friend
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id')
    ->get(['votes.*']); // exclude extra details from friends table

Run the same join for the comments and status_updates tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.


Edit

To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where instead:

$friends_votes = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id');

$friends_comments = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('comments', 'comments.user_id', '=', 'friends.friend_id');

$friends_status_updates = 
    DB::table('status_updates')->where('status_updates.user_id','1')
    ->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');

$friends_events = 
    $friends_votes
    ->union($friends_comments)
    ->union($friends_status_updates)
    ->get();

At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.

Installing Apache Maven Plugin for Eclipse

This has been moved to a new location now -- and please use the below site for updates.

   http://download.eclipse.org/technology/m2e/releases

Passing ArrayList from servlet to JSP

here list attribute name set in request request.setAttribute("List",list); and ArrayList list=new ArrayList();

<%

ArrayList<Category> a=(ArrayList<Category>)request.getAttribute("List");

out.print(a);

for(int i=0;i<a.size();i++)

{
    out.println(a.get(i));

}


%>

How to make a UILabel clickable?

Good and convenient solution:

In your ViewController:

@IBOutlet weak var label: LabelButton!

override func viewDidLoad() {
    super.viewDidLoad()

    self.label.onClick = {
        // TODO
    }
}

You can place this in your ViewController or in another .swift file(e.g. CustomView.swift):

@IBDesignable class LabelButton: UILabel {
    var onClick: () -> Void = {}
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        onClick()
    }
}

In Storyboard select Label and on right pane in "Identity Inspector" in field class select LabelButton.

Don't forget to enable in Label Attribute Inspector "User Interaction Enabled"

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

How do I get current URL in Selenium Webdriver 2 Python?

Use current_url element for Python 2:

print browser.current_url

For Python 3 and later versions of selenium:

print(driver.current_url)

How do I combine two lists into a dictionary in Python?

If there are duplicate keys in the first list that map to different values in the second list, like a 1-to-many relationship, but you need the values to be combined or added or something instead of updating, you can do this:

i = iter(["a", "a", "b", "c", "b"])
j = iter([1,2,3,4,5])
k = list(zip(i, j))
for (x,y) in k:
    if x in d:
        d[x] = d[x] + y #or whatever your function needs to be to combine them
    else:
        d[x] = y

In that example, d == {'a': 3, 'c': 4, 'b': 8}

Multidimensional arrays in Swift

var array: Int[][] = [[1,2,3],[4,5,6],[7,8,9]]

for first in array {
    for second in first {
        println("value \(second)")
    }
}

To achieve what you're looking for you need to initialize the array to the correct template and then loop to add the row and column arrays:

var NumColumns = 27
var NumRows = 52
var array = Array<Array<Int>>()
var value = 1

for column in 0..NumColumns {
    var columnArray = Array<Int>()
    for row in 0..NumRows {
        columnArray.append(value++)
    }
    array.append(columnArray)
}

println("array \(array)")

jQuery remove all list items from an unordered list

Look your class or id. Perhaps Like This $("#resi_result").html(''); This should work:

LIMIT 10..20 in SQL Server

Unfortunately, the ROW_NUMBER() is the best you can do. It's actually more correct, because the results of a limit or top clause don't really have meaning without respect to some specific order. But it's still a pain to do.

Update: Sql Server 2012 adds a limit -like feature via OFFSET and FETCH keywords. This is the ansi-standard approach, as opposed to LIMIT, which is a non-standard MySql extension.

Jackson overcoming underscores in favor of camel-case

The current best practice is to configure Jackson within the application.yml (or properties) file.

Example:

spring:
  jackson:
    property-naming-strategy: SNAKE_CASE

If you have more complex configuration requirements, you can also configure Jackson programmatically.

import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class JacksonConfiguration {

    @Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        return new Jackson2ObjectMapperBuilder()
                .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        // insert other configurations
    }

} 

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

If you're getting this error in the build somewhere else, while your IDE says everything is perfectly fine, then check that you are using the same Java versions in both places.

For example, Java 7 and Java 8 have different APIs, so calling a non-existent API in an older Java version would cause this error.

Read XML Attribute using XmlDocument

You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.

Then the code would be something similar to

string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;

Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.

Decode Base64 data in Java

If You are prefering performance based solution then you can use "MiGBase64"

http://migbase64.sourceforge.net/

public class Base64Test {
    public static void main(String[] args) {
    String encodeToString = Base64.encodeToString("JavaTips.net".getBytes(), true);
    System.out.println("encodeToString " + encodeToString);
    byte[] decodedBytes = Base64.decode(encodeToString.getBytes());
    System.out.println("decodedBytes " + new String(decodedBytes));
    }
}

Check if file exists and whether it contains a specific string

You should use the grep -q flag for quiet output. See the man pages below:

man grep output :

 General Output Control

  -q, --quiet, --silent
              Quiet;  do  not write anything to standard output.  Exit immediately with zero status
              if any match is  found,  even  if  an  error  was  detected.   Also  see  the  -s  or
              --no-messages option.  (-q is specified by POSIX.)

This KornShell (ksh) script demos the grep quiet output and is a solution to your question.

grepUtil.ksh :

#!/bin/ksh

#Initialize Variables
file=poet.txt
var=""
dir=tempDir
dirPath="/"${dir}"/"
searchString="poet"

#Function to initialize variables
initialize(){
    echo "Entering initialize"
    echo "Exiting initialize"
}

#Function to create File with Input
#Params: 1}Directory 2}File 3}String to write to FileName
createFileWithInput(){
    echo "Entering createFileWithInput"
    orgDirectory=${PWD}
    cd ${1}
    > ${2}
    print ${3} >> ${2}
    cd ${orgDirectory}
    echo "Exiting createFileWithInput"
}

#Function to create File with Input
#Params: 1}directoryName
createDir(){
    echo "Entering createDir"
    mkdir -p ${1}
    echo "Exiting createDir"
}

#Params: 1}FileName
readLine(){
    echo "Entering readLine"
    file=${1}
    while read line
    do
        #assign last line to var
        var="$line"
    done <"$file"
    echo "Exiting readLine"
}
#Check if file exists 
#Params: 1}File
doesFileExit(){
    echo "Entering doesFileExit"
    orgDirectory=${PWD}
    cd ${PWD}${dirPath}
    #echo ${PWD}
    if [[ -e "${1}" ]]; then
        echo "${1} exists"
    else
        echo "${1} does not exist"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileExit"
}
#Check if file contains a string quietly
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainStringQuiet(){
    echo "Entering doesFileContainStringQuiet"
    orgDirectory=${PWD}
    cd ${PWD}${1}
    #echo ${PWD}
    grep -q ${3} ${2}
    if [ ${?} -eq 0 ];then
        echo "${3} found in ${2}"
    else
        echo "${3} not found in ${2}"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileContainStringQuiet"
}
#Check if file contains a string with output
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainString(){
    echo "Entering doesFileContainString"
    orgDirectory=${PWD}
    cd ${PWD}${1}
    #echo ${PWD}
    grep ${3} ${2}
    if [ ${?} -eq 0 ];then
        echo "${3} found in ${2}"
    else
        echo "${3} not found in ${2}"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileContainString"
}

#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
#initialize #function call#
createDir ${dir} #function call#
createFileWithInput ${dir} ${file} ${searchString} #function call#
doesFileExit ${file} #function call#
if [ ${?} -eq 0 ];then
    doesFileContainStringQuiet ${dirPath} ${file} ${searchString} #function call#
    doesFileContainString ${dirPath} ${file} ${searchString} #function call#
fi
echo "Exiting: ${PWD}/${0}"

grepUtil.ksh Output :

user@foo /tmp
$ ksh grepUtil.ksh
Starting: /tmp/grepUtil.ksh with Input Parameters: {1:  {2:  {3:
Entering createDir
Exiting createDir
Entering createFileWithInput
Exiting createFileWithInput
Entering doesFileExit
poet.txt exists
Exiting doesFileExit
Entering doesFileContainStringQuiet
poet found in poet.txt
Exiting doesFileContainStringQuiet
Entering doesFileContainString
poet
poet found in poet.txt
Exiting doesFileContainString
Exiting: /tmp/grepUtil.ksh

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

I had the same issue when using an .exe to install a Python package (because I use Anaconda and it didn't add Python to the registry). I fixed the problem by running this script:

#
# script to register Python 2.0 or later for use with 
# Python extensions that require Python registry settings
#
# written by Joakim Loew for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm
#
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/[email protected]/msg10512.html

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)

def RegisterPy():
    try:
        reg = OpenKey(HKEY_CURRENT_USER, regpath)
    except EnvironmentError as e:
        try:
            reg = CreateKey(HKEY_CURRENT_USER, regpath)
            SetValue(reg, installkey, REG_SZ, installpath)
            SetValue(reg, pythonkey, REG_SZ, pythonpath)
            CloseKey(reg)
        except:
            print "*** Unable to register!"
            return
        print "--- Python", version, "is now registered!"
        return
    if (QueryValue(reg, installkey) == installpath and
        QueryValue(reg, pythonkey) == pythonpath):
        CloseKey(reg)
        print "=== Python", version, "is already registered!"
        return
    CloseKey(reg)
    print "*** Unable to register!"
    print "*** You probably have another Python installation!"

if __name__ == "__main__":
    RegisterPy()

Laravel - Eloquent or Fluent random row

Laravel has a built-in method to shuffle the order of the results.

Here is a quote from the documentation:

shuffle()

The shuffle method randomly shuffles the items in the collection:

$collection = collect([1, 2, 3, 4, 5]);

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] - (generated randomly)

You can see the documentation here.

PostgreSQL: days/months/years between two dates

I would like to expand on Riki_tiki_tavi's answer and get the data out there. I have created a datediff function that does almost everything sql server does. So that way we can take into account any unit.

create function datediff(units character varying, start_t timestamp without time zone, end_t timestamp without time zone) returns integer
language plpgsql
 as
 $$
DECLARE
 diff_interval INTERVAL; 
 diff INT = 0;
 years_diff INT = 0;
BEGIN
 IF units IN ('yy', 'yyyy', 'year', 'mm', 'm', 'month') THEN
   years_diff = DATE_PART('year', end_t) - DATE_PART('year', start_t);

   IF units IN ('yy', 'yyyy', 'year') THEN
     -- SQL Server does not count full years passed (only difference between year parts)
     RETURN years_diff;
   ELSE
     -- If end month is less than start month it will subtracted
     RETURN years_diff * 12 + (DATE_PART('month', end_t) - DATE_PART('month', start_t)); 
   END IF;
 END IF;

 -- Minus operator returns interval 'DDD days HH:MI:SS'  
 diff_interval = end_t - start_t;

 diff = diff + DATE_PART('day', diff_interval);

 IF units IN ('wk', 'ww', 'week') THEN
   diff = diff/7;
   RETURN diff;
 END IF;

 IF units IN ('dd', 'd', 'day') THEN
   RETURN diff;
 END IF;

 diff = diff * 24 + DATE_PART('hour', diff_interval); 

 IF units IN ('hh', 'hour') THEN
    RETURN diff;
 END IF;

 diff = diff * 60 + DATE_PART('minute', diff_interval);

 IF units IN ('mi', 'n', 'minute') THEN
    RETURN diff;
 END IF;

 diff = diff * 60 + DATE_PART('second', diff_interval);

 RETURN diff;
END;
$$;

Codeigniter : calling a method of one controller from other

You can do like

$result= file_get_contents(site_url('[ADDRESS TO CONTROLLER FUNCTION]'));

Replace [ADDRESS TO CONTROLLER FUNCTION] by the way we use in site_url();

You need to echo output in controller function instead of return.

Get latest from Git branch

Your modifications are in a different branch than the original branch, which simplifies stuff because you get updates in one branch, and your work is in another branch.

Assuming the original branch is named master, which the case in 99% of git repos, you have to fetch the state of origin, and merge origin/master updates into your local master:

 git fetch origin
 git checkout master
 git merge origin/master

To switch to your branch, just do

 git checkout branch1

m2e error in MavenArchiver.getManifest()

I solved this error in pom.xml by adding the below code

spring-rest-demo org.apache.maven.plugins maven-war-plugin 2.6

Width of input type=text element

I believe that is just how the browser renders their standard input. If you set a border on the input:

<input type="text" style="width: 10px; padding: 2px; border: 1px solid black"/>
<div style="width: 10px; border: solid 1px black; padding: 2px"> </div>

Then both are the same width, at least in FF.

Trusting all certificates with okHttp

Following method is deprecated

sslSocketFactory(SSLSocketFactory sslSocketFactory)

Consider updating it to

sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

Android view layout_width - how to change programmatically?

You can set height and width like this also:

viewinstance.setLayoutParams(new LayoutParams(width, height));

how to rotate text left 90 degree and cell size is adjusted according to text in html

Daniel Imms answer is excellent in regards to applying your CSS rotation to an inner element. However, it is possible to accomplish the end goal in a way that does not require JavaScript and works with longer strings of text.

Typically the whole reason to have vertical text in the first table column is to fit a long line of text in a short horizontal space and to go alongside tall rows of content (as in your example) or multiple rows of content (which I'll use in this example).

enter image description here

By using the ".rotate" class on the parent TD tag, we can not only rotate the inner DIV, but we can also set a few CSS properties on the parent TD tag that will force all of the text to stay on one line and keep the width to 1.5em. Then we can use some negative margins on the inner DIV to make sure that it centers nicely.

_x000D_
_x000D_
td {_x000D_
    border: 1px black solid;_x000D_
    padding: 5px;_x000D_
}_x000D_
.rotate {_x000D_
  text-align: center;_x000D_
  white-space: nowrap;_x000D_
  vertical-align: middle;_x000D_
  width: 1.5em;_x000D_
}_x000D_
.rotate div {_x000D_
     -moz-transform: rotate(-90.0deg);  /* FF3.5+ */_x000D_
       -o-transform: rotate(-90.0deg);  /* Opera 10.5 */_x000D_
  -webkit-transform: rotate(-90.0deg);  /* Saf3.1+, Chrome */_x000D_
             filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083);  /* IE6,IE7 */_x000D_
         -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */_x000D_
         margin-left: -10em;_x000D_
         margin-right: -10em;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>10 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>20 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>30 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
</table>
_x000D_
_x000D_
_x000D_

One thing to keep in mind with this solution is that it does not work well if the height of the row (or spanned rows) is shorter than the vertical text in the first column. It works best if you're spanning multiple rows or you have a lot of content creating tall rows.

Have fun playing around with this on jsFiddle.

OpenCV NoneType object has no attribute shape

I also face the same issue "OpenCV NoneType object has no attribute shape" and i solve this by changing the image location. I also use the PyCharm IDE. Currently my image location and class file in the same folder. enter image description here

How to print something to the console in Xcode?

@Logan said it perfectly. but i would like to add an alternative here,

if you want to view logs from just your application then you can make a custom method that keeps saving the log to a file in documents directory & then you can view that log file from your application.

There is one good advantage for developers of the app after the app has been released & users are downloading it. Because your app will be able to send logs & crash reports to the developers (of course with the permissions of the device user !!!) & it'll be the way to improve your application.

Let me know (To other SO users), if there is another way of doing the same thing. (Like default Apple feature or something)

Let me know if it helps or you want some more idea.

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

Just to add - Safari 2 and earlier definitely didn't support PUT and DELETE. I get the impression 3 did, but I don't have it around to test anymore. Safari 4 definitely does support PUT and DELETE.

How can I use Python to get the system hostname?

What about :

import platform

h = platform.uname()[1]

Actually you may want to have a look to all the result in platform.uname()

Rotating a two-dimensional array in Python

That's a clever bit.

First, as noted in a comment, in Python 3 zip() returns an iterator, so you need to enclose the whole thing in list() to get an actual list back out, so as of 2020 it's actually:

list(zip(*original[::-1]))

Here's the breakdown:

  • [::-1] - makes a shallow copy of the original list in reverse order. Could also use reversed() which would produce a reverse iterator over the list rather than actually copying the list (more memory efficient).
  • * - makes each sublist in the original list a separate argument to zip() (i.e., unpacks the list)
  • zip() - takes one item from each argument and makes a list (well, a tuple) from those, and repeats until all the sublists are exhausted. This is where the transposition actually happens.
  • list() converts the output of zip() to a list.

So assuming you have this:

[ [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9] ]

You first get this (shallow, reversed copy):

[ [7, 8, 9],
  [4, 5, 6],
  [1, 2, 3] ]

Next each of the sublists is passed as an argument to zip:

zip([7, 8, 9], [4, 5, 6], [1, 2, 3])

zip() repeatedly consumes one item from the beginning of each of its arguments and makes a tuple from it, until there are no more items, resulting in (after it's converted to a list):

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

And Bob's your uncle.

To answer @IkeMiguel's question in a comment about rotating it in the other direction, it's pretty straightforward: you just need to reverse both the sequences that go into zip and the result. The first can be achieved by removing the [::-1] and the second can be achieved by throwing a reversed() around the whole thing. Since reversed() returns an iterator over the list, we will need to put list() around that to convert it. With a couple extra list() calls to convert the iterators to an actual list. So:

rotated = list(reversed(list(zip(*original))))

We can simplify that a bit by using the "Martian smiley" slice rather than reversed()... then we don't need the outer list():

rotated = list(zip(*original))[::-1]

Of course, you could also simply rotate the list clockwise three times. :-)

Center a DIV horizontally and vertically

You can compare different methods very well explained on this page: http://blog.themeforest.net/tutorials/vertical-centering-with-css/

The method they recommend is adding a empty floating element before the content you cant centered, and clearing it. It doesn't have the downside you mentioned.

I forked your JSBin to apply it : http://jsbin.com/iquviq/7/edit

HTML

<div id="floater">
</div>

<div id="content">
  Content here
</div>

CSS

#floater {
  float: left; 
  height: 50%; 
  margin-bottom: -300px;
}

#content {
  clear: both; 
  width: 200px;
  height: 600px;
  position: relative; 
  margin: auto;
}

Read String line by line

You can use the stream api and a StringReader wrapped in a BufferedReader which got a lines() stream output in java 8:

import java.util.stream.*;
import java.io.*;
class test {
    public static void main(String... a) {
        String s = "this is a \nmultiline\rstring\r\nusing different newline styles";

        new BufferedReader(new StringReader(s)).lines().forEach(
            (line) -> System.out.println("one line of the string: " + line)
        );
    }
}

Gives

one line of the string: this is a
one line of the string: multiline
one line of the string: string
one line of the string: using different newline styles

Just like in BufferedReader's readLine, the newline character(s) themselves are not included. All kinds of newline separators are supported (in the same string even).

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

If Publishing in Visual Studio 2012 when erroring try unchecking the "Procompile during publishing" option in the Publish wizard.

Un-check "Precompile during publishing"

Determine the process pid listening on a certain port

on windows, the netstat option to get the pid's is -o and -p selects a protocol filter, ex.: netstat -a -p tcp -o

jQuery.post( ) .done( ) and success:

jQuery used to ONLY have the callback functions for success and error and complete.

Then, they decided to support promises with the jqXHR object and that's when they added .done(), .fail(), .always(), etc... in the spirit of the promise API. These new methods serve much the same purpose as the callbacks but in a different form. You can use whichever API style works better for your coding style.

As people get more and more familiar with promises and as more and more async operations use that concept, I suspect that more and more people will move to the promise API over time, but in the meantime jQuery supports both.

The .success() method has been deprecated in favor of the common promise object method names.

From the jQuery doc, you can see how various promise methods relate to the callback types:

jqXHR.done(function( data, textStatus, jqXHR ) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {}); Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

If you want to code in a way that is more compliant with the ES6 Promises standard, then of these four options you would only use .then().

Handling identity columns in an "Insert Into TABLE Values()" statement?

By default, if you have an identity column, you do not need to specify it in the VALUES section. If your table is:

ID    NAME    ADDRESS

Then you can do:

INSERT INTO MyTbl VALUES ('Joe', '123 State Street, Boston, MA')

This will auto-generate the ID for you, and you don't have to think about it at all. If you SET IDENTITY_INSERT MyTbl ON, you can assign a value to the ID column.

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

What does 'public static void' mean in Java?

It means three things.

First public means that any other object can access it.

static means that the class in which it resides doesn't have to be instantiated first before the function can be called.

void means that the function does not return a value.

Since you are just learning, don't worry about the first two too much until you learn about classes, and the third won't matter much until you start writing functions (other than main that is).

Best piece of advice I got when learning to program, and which I pass along to you, is don't worry about the little details you don't understand right away. Get a broad overview of the fundamentals, then go back and worry about the details. The reason is that you have to use some things (like public static void) in your first programs which can't really be explained well without teaching you about a bunch of other stuff first. So, for the moment, just accept that that's the way it's done, and move on. You will understand them shortly.

jQuery check if attr = value

jQuery's attr method returns the value of the attribute:

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

All you need is:

$('html').attr('lang') == 'fr-FR'

However, you might want to do a case-insensitive match:

$('html').attr('lang').toLowerCase() === 'fr-fr'

jQuery's val method returns the value of a form element.

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.

Find length of 2D array Python

Like this:

numrows = len(input)    # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example

Assuming that all the sublists have the same length (that is, it's not a jagged array).

Unable to install packages in latest version of RStudio and R Version.3.1.1

Not 100% certain that you have the same problem, but I found out the hard way that my job blocks each mirror site option that was offered and I was getting errors like this:

Installing package into ‘/usr/lib64/R/library’
(as ‘lib’ is unspecified)
--- Please select a CRAN mirror for use in this session ---
Error in download.file(url, destfile = f, quiet = TRUE) : 
  unsupported URL scheme
Warning: unable to access index for repository https://rweb.crmda.ku.edu/cran/src/contrib
Warning message:
package ‘ggplot2’ is not available (for R version 3.2.2)

Workaround (I am using CentOS)...

install.packages('package_name', dependencies=TRUE, repos='http://cran.rstudio.com/')

I hope this saves someone hours of frustration.

nginx - read custom header from upstream server

Use $http_MY_CUSTOM_HEADER

You can write some-thing like

set my_header $http_MY_CUSTOM_HEADER;
if($my_header != 'some-value') {
#do some thing;
}

Specifying a custom DateTime format when serializing with Json.Net

You could use this approach:

public class DateFormatConverter : IsoDateTimeConverter
{
    public DateFormatConverter(string format)
    {
        DateTimeFormat = format;
    }
}

And use it this way:

class ReturnObjectA 
{
    [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
    public DateTime ReturnDate { get;set;}
}

The DateTimeFormat string uses the .NET format string syntax described here: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

Open Source Javascript PDF viewer

There are some guys at Mozilla working on implementing a PDF reader using HTML5 and JavaScript. It is called pdf.js and one of the developers just made an interesting blog post about the project.

git ahead/behind info between master and branch?

First of all to see how many revisions you are behind locally, you should do a git fetch to make sure you have the latest info from your remote.

The default output of git status tells you how many revisions you are ahead or behind, but usually I find this too verbose:

$ git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 1 different commit each, respectively.
#
nothing to commit (working directory clean)

I prefer git status -sb:

$ git status -sb
## master...origin/master [ahead 2, behind 1]

In fact I alias this to simply git s, and this is the main command I use for checking status.

To see the diff in the "ahead revisions" of master, I can exclude the "behind revisions" from origin/master:

git diff master..origin/master^

To see the diff in the "behind revisions" of origin/master, I can exclude the "ahead revisions" from master:

git diff origin/master..master^^

If there are 5 revisions ahead or behind it might be easier to write like this:

git diff master..origin/master~5
git diff origin/master..master~5

UPDATE

To see the ahead/behind revisions, the branch must be configured to track another branch. For me this is the default behavior when I clone a remote repository, and after I push a branch with git push -u remotename branchname. My version is 1.8.4.3, but it's been working like this as long as I remember.

As of version 1.8, you can set the tracking branch like this:

git branch --track test-branch

As of version 1.7, the syntax was different:

git branch --set-upstream test-branch

Find the differences between 2 Excel worksheets?

The Notepad++ compare plugin works perfectly for this. Just save your sheets as .csv files and compare them in Notepad++. Notepad++ gives you a nice visual diff.

Get index of selected option with jQuery

try this

 alert(document.getElementById("dropDownMenuKategorie").selectedIndex);

Understanding colors on Android (six characters)

An 8-digit hex color value is a representation of ARGB (Alpha, Red, Green, Blue), whereas a 6-digit value just assumes 100% opacity (fully opaque) and defines just the RGB values. So to make this be fully opaque, you can either use #FF555555, or just #555555. Each 2-digit hex value is one byte, representing values from 0-255.

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

Get average color of image via Javascript

This is about "Color Quantization" that has several approachs like MMCQ (Modified Median Cut Quantization) or OQ (Octree Quantization). Different approach use K-Means to obtain clusters of colors.

I have putted all together here, since I was finding a solution for tvOS where there is a subset of XHTML, that has no <canvas/> element:

Generate the Dominant Colors for an RGB image with XMLHttpRequest

How to perform update operations on columns of type JSONB in Postgres 9.4

If you're able to upgrade to Postgresql 9.5, the jsonb_set command is available, as others have mentioned.

In each of the following SQL statements, I've omitted the where clause for brevity; obviously, you'd want to add that back.

Update name:

UPDATE test SET data = jsonb_set(data, '{name}', '"my-other-name"');

Replace the tags (as oppose to adding or removing tags):

UPDATE test SET data = jsonb_set(data, '{tags}', '["tag3", "tag4"]');

Replacing the second tag (0-indexed):

UPDATE test SET data = jsonb_set(data, '{tags,1}', '"tag5"');

Append a tag (this will work as long as there are fewer than 999 tags; changing argument 999 to 1000 or above generates an error. This no longer appears to be the case in Postgres 9.5.3; a much larger index can be used):

UPDATE test SET data = jsonb_set(data, '{tags,999999999}', '"tag6"', true);

Remove the last tag:

UPDATE test SET data = data #- '{tags,-1}'

Complex update (delete the last tag, insert a new tag, and change the name):

UPDATE test SET data = jsonb_set(
    jsonb_set(data #- '{tags,-1}', '{tags,999999999}', '"tag3"', true), 
    '{name}', '"my-other-name"');

It's important to note that in each of these examples, you're not actually updating a single field of the JSON data. Instead, you're creating a temporary, modified version of the data, and assigning that modified version back to the column. In practice, the result should be the same, but keeping this in mind should make complex updates, like the last example, more understandable.

In the complex example, there are three transformations and three temporary versions: First, the last tag is removed. Then, that version is transformed by adding a new tag. Next, the second version is transformed by changing the name field. The value in the data column is replaced with the final version.

Append an empty row in dataframe using pandas

Append "empty" row to data frame and fill selected cells:

Generate empty data frame (no rows just columns a and b):

import pandas as pd    
col_names =  ["a","b"]
df  = pd.DataFrame(columns = col_names)

Append empty row at the end of the data frame:

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

Now fill the empty cell at the end (len(df)-1) of the data frame in column a:

df.loc[[len(df)-1],'a'] = 123

Result:

     a    b
0  123  NaN

And of course one can iterate over the rows and fill cells:

col_names =  ["a","b"]
df  = pd.DataFrame(columns = col_names)
for x in range(0,5):
    df = df.append(pd.Series(), ignore_index = True)
    df.loc[[len(df)-1],'a'] = 123

Result:

     a    b
0  123  NaN
1  123  NaN
2  123  NaN
3  123  NaN
4  123  NaN

How to get object length

This should do it:

Object.keys(a).length

However, Object.keys is not supported in IE8 and below, Opera and FF 3.6 and below.

Live demo: http://jsfiddle.net/simevidas/nN84h/

Git push failed, "Non-fast forward updates were rejected"

I've hade the same problem. I resolved with

git checkout <name branch>
git pull origin <name branch>
git push origin <name branch>

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
{
    @Html.Partial("_partialView", planVM)
}

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
<div>
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>
</div>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
    @Html.EditorForModel()
</div>
}

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

Generating UML from C++ code?

I've developed a tool called Doxygraph which can parse the XML generated by Doxygen and turn it into an interactive UML class diagram which you can view in a web browser or import into any software that can read Graphviz "dot" files.

How can I use a reportviewer control in an asp.net mvc 3 razor view?

You will not only have to use an asp.net page but

If using the Entity Framework or LinqToSql (if using partial classes) move the data into a separate project, the report designer cannot see the classes.

Move the reports to another project/dll, VS10 has bugs were asp.net projects cannot see object datasources in web apps. Then stream the reports from the dll into your mvc projects aspx page.

This applies for mvc and webform projects. Using sql reports in the local mode is not a pleasent development experience. Also watch your webserver memory if exporting large reports. The reportviewer/export is very poorly designed.

Child inside parent with min-height: 100% not inheriting height

The best way to achieve this nowadays is to use display: flex;. However you might run into an issue when trying to support IE11. According to https://caniuse.com using flexbox :

IE 11 does not vertically align items correctly when min-height is used

Internet Explorer compatible solution

The solution is to use display: table; on the parent and display: table-row; on the child both with height: 100%; as a replacement for min-height: 100%;.

Most of the solutions listed here use display: table, table-row and/or table-cell, but they don't replicate the same behaviour as min-height: 100%;, which is:

  • Inherit the computed height of the parent (as opposed to inheriting its height property);
  • Allow the parent's height to exceed its min-height;

While using this solution, the behaviour is the same and the property min-height is not needed which allows to get around the bug.

Explanation

The reason why it works is because, unlike most elements, elements using display: table and table-row will always be as tall as their content. This makes their height property behave similarly to min-height.

Solution in action

_x000D_
_x000D_
html, body {_x000D_
  height: 100px;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#containment {_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  background: pink;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#containment-shadow-left {_x000D_
  display: table-row;_x000D_
  height: 100%;_x000D_
  background: aqua;_x000D_
}_x000D_
_x000D_
#content {_x000D_
  padding: 15px;_x000D_
}_x000D_
_x000D_
#demo {_x000D_
  display: none;_x000D_
  background-color: red;_x000D_
  height: 200px;_x000D_
}_x000D_
_x000D_
#demo-checkbox:checked ~ #demo {_x000D_
  display: block;_x000D_
}
_x000D_
<div id="containment">_x000D_
  <div id="containment-shadow-left">_x000D_
    <div id="content">_x000D_
      <input id="demo-checkbox" type="checkbox">_x000D_
      <label for="demo-checkbox">Click here for overflow demo</label>_x000D_
      <div id="demo">This is taller than #containment</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to initialize a list with constructor?

Using a collection initializer

From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:

var human = new Human(1, "Address", "Name") {
    ContactNumbers = new List<ContactNumber>() {
        new ContactNumber(1),
        new ContactNumber(2),
        new ContactNumber(3)
    }
}

Specializing the Human constructor

You can change the constructor of the Human class to provide a way to populate the ContactNumbers property:

public class Human
{
    public Human(int id, string address, string name, IEnumerable<ContactNumber> contactNumbers) : this(id, address, name)
    {
        ContactNumbers = new List<ContactNumber>(contactNumbers);
    }

    public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
    {
        ContactNumbers = new List<ContactNumber>(contactNumbers);
    }
}

// Using the first constructor:
List<ContactNumber> numbers = List<ContactNumber>() {
    new ContactNumber(1),
    new ContactNumber(2),
    new ContactNumber(3)
};

var human = new Human(1, "Address", "Name", numbers);

// Using the second constructor:
var human = new Human(1, "Address", "Name",
    new ContactNumber(1),
    new ContactNumber(2),
    new ContactNumber(3)
);

Bottom line

Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

import the ReactiveForms Module to your components module

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

Your service must answer an OPTIONS request with headers like these:

Access-Control-Allow-Origin: [the same origin from the request]
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: [the same ACCESS-CONTROL-REQUEST-HEADERS from request]

Here is a good doc: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server

How to view AndroidManifest.xml from APK file?

You can use this command: save to file AndroidManifest.txt

aapt dump xmltree gmail.apk AndroidManifest.xml > AndroidManifest.txt

How to make a TextBox accept only alphabetic characters?

Here is my solution and it works as planned:

string errmsg = "ERROR : Wrong input";
ErrorLbl.Text = errmsg;

if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
{
  ErrorLbl.Text = "ERROR : Wrong input";
}
else ErrorLbl.Text = string.Empty;
if (ErrorLbl.Text == errmsg)
{
  Nametxt.Text = string.Empty;
}

Fatal error: Maximum execution time of 30 seconds exceeded

To extend your max_execution_time you can use either ini_set or set_time_limit.

// Set maximum execution time to 10 seconds this way
ini_set('max_execution_time', 10);
// or this way
set_time_limit(10);

!! But be aware that, both functions restarts also counting of time script has already taken to execute

sleep(2);
ini_set('max_execution_time', 5);

register_shutdown_function(function(){
    var_dump(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']);
});

for(;;);

//
// var_dump outputs float(7.1981489658356)
//

so if you want to set exact maximum amount of time script can run, your command must be very first.

Differences between those two functions are

  • set_time_limit does not return info whether it was successful but it will throw a warning on error.
  • ini_set returns old value on success, or false on failure without any warning/error

Check whether a string matches a regex in JS

try

 /^[a-z\d]{5,}$/.test(str)

_x000D_
_x000D_
console.log( /^[a-z\d]{5,}$/.test("abc123") );_x000D_
_x000D_
console.log( /^[a-z\d]{5,}$/.test("ab12") );
_x000D_
_x000D_
_x000D_

How to save local data in a Swift app?

Swift 5+

None of the answers really cover in detail the default built in local storage capabilities. It can do far more than just strings.

You have the following options straight from the apple documentation for 'getting' data from the defaults.

func object(forKey: String) -> Any?
//Returns the object associated with the specified key.

func url(forKey: String) -> URL?
//Returns the URL associated with the specified key.

func array(forKey: String) -> [Any]?
//Returns the array associated with the specified key.

func dictionary(forKey: String) -> [String : Any]?
//Returns the dictionary object associated with the specified key.

func string(forKey: String) -> String?
//Returns the string associated with the specified key.

func stringArray(forKey: String) -> [String]?
//Returns the array of strings associated with the specified key.

func data(forKey: String) -> Data?
//Returns the data object associated with the specified key.

func bool(forKey: String) -> Bool
//Returns the Boolean value associated with the specified key.

func integer(forKey: String) -> Int
//Returns the integer value associated with the specified key.

func float(forKey: String) -> Float
//Returns the float value associated with the specified key.

func double(forKey: String) -> Double
//Returns the double value associated with the specified key.

func dictionaryRepresentation() -> [String : Any]
//Returns a dictionary that contains a union of all key-value pairs in the domains in the search list.

Here are the options for 'setting'

func set(Any?, forKey: String)
//Sets the value of the specified default key.

func set(Float, forKey: String)
//Sets the value of the specified default key to the specified float value.

func set(Double, forKey: String)
//Sets the value of the specified default key to the double value.

func set(Int, forKey: String)
//Sets the value of the specified default key to the specified integer value.

func set(Bool, forKey: String)
//Sets the value of the specified default key to the specified Boolean value.

func set(URL?, forKey: String)
//Sets the value of the specified default key to the specified URL.

If are storing things like preferences and not a large data set these are perfectly fine options.

Double Example:

Setting:

let defaults = UserDefaults.standard
var someDouble:Double = 0.5
defaults.set(someDouble, forKey: "someDouble")

Getting:

let defaults = UserDefaults.standard
var someDouble:Double = 0.0
someDouble = defaults.double(forKey: "someDouble")

What is interesting about one of the getters is dictionaryRepresentation, this handy getter will take all your data types regardless what they are and put them into a nice dictionary that you can access by it's string name and give the correct corresponding data type when you ask for it back since it's of type 'any'.

You can store your own classes and objects also using the func set(Any?, forKey: String) and func object(forKey: String) -> Any? setter and getter accordingly.

Hope this clarifies more the power of the UserDefaults class for storing local data.

On the note of how much you should store and how often, Hardy_Germany gave a good answer on that on this post, here is a quote from it

As many already mentioned: I'm not aware of any SIZE limitation (except physical memory) to store data in a .plist (e.g. UserDefaults). So it's not a question of HOW MUCH.

The real question should be HOW OFTEN you write new / changed values... And this is related to the battery drain this writes will cause.

IOS has no chance to avoid a physical write to "disk" if a single value changed, just to keep data integrity. Regarding UserDefaults this cause the whole file rewritten to disk.

This powers up the "disk" and keep it powered up for a longer time and prevent IOS to go to low power state.

Something else to note as mentioned by user Mohammad Reza Farahani from this post is the asynchronous and synchronous nature of userDefaults.

When you set a default value, it’s changed synchronously within your process, and asynchronously to persistent storage and other processes.

For example if you save and quickly close the program you may notice it does not save the results, this is because it's persisting asynchronously. You might not notice this all the time so if you plan on saving before quitting the program you may want to account for this by giving it some time to finish.

Maybe someone has some nice solutions for this they can share in the comments?

How to add image background to btn-default twitter-bootstrap button?

Instead of using input type button you can use button and insert the image inside the button content.

<button class="btn btn-default">
     <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook
</button>

The problem with doing this only with CSS is that you cannot set linear-gradient to the background you must use solid color.

.sign-in-facebook {
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }
  .sign-in-facebook:hover {
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }

_x000D_
_x000D_
body {_x000D_
  padding: 30px;_x000D_
}
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style type="text/css">_x000D_
  .sign-in-facebook {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
  .sign-in-facebook:hover {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
_x000D_
<h4>Only with CSS</h4>_x000D_
_x000D_
<input type="button" value="Sign In with Facebook" class="btn btn-default sign-in-facebook" style="margin-top:2px; margin-bottom:2px;">_x000D_
_x000D_
<h4>Only with HTML</h4>_x000D_
_x000D_
<button class="btn btn-default">_x000D_
  <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook_x000D_
</button>
_x000D_
_x000D_
_x000D_

File uploading with Express 4.0: req.files undefined

Just to add to answers above, you can streamline the use of express-fileupload to just a single route that needs it, instead of adding it to the every route.

let fileupload = require("express-fileupload");

...

app.post("/upload", fileupload, function(req, res){

...

});

How to display raw JSON data on a HTML page

JSON in any HTML tag except <script> tag would be a mere text. Thus it's like you add a story to your HTML page.

However, about formatting, that's another matter. I guess you should change the title of your question.

Take a look at this question. Also see this page.

Passing a string array as a parameter to a function java

look at familiar main method which takes string array as param

How to ping a server only once from within a batch file?

if you want to use the name "ping.bat", a small trick is to use this code:

@echo off
cd\ 
ping google.com -t

Just add that "cd\" and you are fine... ;)

How to restart Activity in Android

public void onRestart() {
    super.onRestart();
    Intent intent=new Intent();
    intent.setClass(act, act.getClass());
    finish();
    act.startActivity(intent);
}

try to use this ..

Aren't Python strings immutable? Then why does a + " " + b work?

Python strings are immutable. However, a is not a string: it is a variable with a string value. You can't mutate the string, but can change what value of the variable to a new string.

How to find the privileges and roles granted to a user in Oracle?

always make SQL re-usuable: -:)

-- ===================================================
-- &role_name will be "enter value for 'role_name'".
-- Date:  2015 NOV 11.

-- sample code:   define role_name=&role_name
-- sample code:   where role like '%&&role_name%'
-- ===================================================


define role_name=&role_name

select * from ROLE_ROLE_PRIVS where ROLE = '&&role_name';
select * from ROLE_SYS_PRIVS  where ROLE = '&&role_name';


select role, privilege,count(*)
 from ROLE_TAB_PRIVS
where ROLE = '&&role_name'
group by role, privilege
order by role, privilege asc
;

What is the difference between signed and unsigned variables?

unsigned is used when ur value must be positive, no negative value here, if signed for int range -32768 to +32767 if unsigned for int range 0 to 65535

Angular.js programmatically setting a form field to dirty

A helper function to do the job:

function setDirtyForm(form) {
    angular.forEach(form.$error, function(type) {
        angular.forEach(type, function(field) {
            field.$setDirty();
        });
    });
    return form;
}

How can I start PostgreSQL on Windows?

Remove Postmaster file in "C:\Program Files\PostgreSQL\9.6\data"

and restart the PostgreSQL services

Show pop-ups the most elegant way

  • Create a 'popup' directive and apply it to the container of the popup content
  • In the directive, wrap the content in a absolute position div along with the mask div below it.
  • It is OK to move the 2 divs in the DOM tree as needed from within the directive. Any UI code is OK in the directives, including the code to position the popup in center of screen.
  • Create and bind a boolean flag to controller. This flag will control visibility.
  • Create scope variables that bond to OK / Cancel functions etc.

Editing to add a high level example (non functional)

<div id='popup1-content' popup='showPopup1'>
  ....
  ....
</div>


<div id='popup2-content' popup='showPopup2'>
  ....
  ....
</div>



.directive('popup', function() {
  var p = {
      link : function(scope, iElement, iAttrs){
           //code to wrap the div (iElement) with a abs pos div (parentDiv)
          // code to add a mask layer div behind 
          // if the parent is already there, then skip adding it again.
         //use jquery ui to make it dragable etc.
          scope.watch(showPopup, function(newVal, oldVal){
               if(newVal === true){
                   $(parentDiv).show();
                 } 
              else{
                 $(parentDiv).hide();
                }
          });
      }


   }
  return p;
});

String escape into XML

Another take based on John Skeet's answer that doesn't return the tags:

void Main()
{
    XmlString("Brackets & stuff <> and \"quotes\"").Dump();
}

public string XmlString(string text)
{
    return new XElement("t", text).LastNode.ToString();
} 

This returns just the value passed in, in XML encoded format:

Brackets &amp; stuff &lt;&gt; and "quotes"

What is the difference between Promises and Observables?

Observables and Promises are helping us to work with the asynchronous functionalities in JavaScript/typescript. They are very similar in many cases, however, there are still some differences between them.

enter image description here

How to uncompress a tar.gz in another directory

Extracts myArchive.tar to /destinationDirectory

Commands:

cd /destinationDirectory
pax -rv -f myArchive.tar -s ',^/,,'

How to measure elapsed time

When the game starts:

long tStart = System.currentTimeMillis();

When the game ends:

long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;

Size of Matrix OpenCV

A complete C++ code example, may be helpful for the beginners

#include <iostream>
#include <string>
#include "opencv/highgui.h"

using namespace std;
using namespace cv;

int main()
{
    cv:Mat M(102,201,CV_8UC1);
    int rows = M.rows;
    int cols = M.cols;

    cout<<rows<<" "<<cols<<endl;

    cv::Size sz = M.size();
    rows = sz.height;
    cols = sz.width;

    cout<<rows<<" "<<cols<<endl;
    cout<<sz<<endl;
    return 0;
}

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

Where is a log file with logs from a container?

To see how much space each container's log is taking up, use this:

docker ps -qa | xargs docker inspect --format='{{.LogPath}}' | xargs ls -hl

(you might need a sudo before ls).

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

I tried to change target sdk to 13 but does not works!! then when I changed compileSdkVersion 13 to compileSdkVersion 14 is compiled successfully :)

NOTE: I Work with Android Studio not Eclipse

How to change Angular CLI favicon

Since you have replaced the favicon.ico file physically, there must be a caching issue somewhere. There is a cache in your browser. Force it to get flushed by pressing Ctrl+F5.

If the default icon is still displayed, try another browser with a clean cache (i.e. you haven't visited the page with that browser yet).

Clear Cache Shortcuts: (Source)

Windows
IE:Ctrl+R; Firefox:Ctrl+Shift+R; Chrome:Ctrl+R, or Ctrl+F5, or Shift+F5.

Mac
Safari:?+R; Firefox/Chrome:?+Shift+R.

How do I check particular attributes exist or not in XML?

You can use the GetNamedItem method to check and see if the attribute is available. If null is returned, then it isn't available. Here is your code with that check in place:

foreach (XmlNode xNode in nodeListName)
{
    if(xNode.ParentNode.Attributes.GetNamedItem("split") != null )
    {
        if(xNode.ParentNode.Attributes["split"].Value != "")
        {
            parentSplit = xNode.ParentNode.Attributes["split"].Value;
        }
    }  
}

Postgresql: password authentication failed for user "postgres"

This happens due to caching.

When you run, php artisan config:cache, it will cache the configuration files. Whenever things get change, you need to keep running it to update the cache files. But, it won't cache if you never run that command.

This is OK for production, since config don't change that often. But during staging or dev, you can just disable caching by clearing the cache and don't run the cache command

So, just run php artisan config:clear, and don't run the command previously to avoid caching.

Check original post

Password authentication failed error on running laravel migration

Chart.js v2 - hiding grid lines

If you want them gone by default, you can set:

Chart.defaults.scale.gridLines.display = false;

ERROR 2006 (HY000): MySQL server has gone away

For Drupal 8 users looking for solution for DB import failure:

At end of sql dump file there can commands inserting data to "webprofiler" table. That's I guess some debug log file and is not really important for site to work so all this can be removed. I deleted all those inserts including LOCK TABLES and UNLOCK TABLES (and everything between). It's at very bottom of the sql file. Issue is described here:

https://www.drupal.org/project/devel/issues/2723437

But there is no solution for it beside truncating that table.

BTW I tried all solutions from answers above and nothing else helped.

Mail not sending with PHPMailer over SSL using SMTP

$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]";
$mail->Password = "**********";
$mail->Port = "465";

That is a working configuration.

try to replace what you have

Run Jquery function on window events: load, resize, and scroll?

You can use the following. They all wrap the window object into a jQuery object.

Load:

$(window).load(function () {
    topInViewport($("#mydivname"))
});

Resize:

$(window).resize(function () {
   topInViewport($("#mydivname"))
});

Scroll

$(window).scroll(function () {
    topInViewport($("#mydivname"))
});

Or bind to them all using on:

$(window).on("load resize scroll",function(e){
    topInViewport($("#mydivname"))
});

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

How to open a new window on form submit

I found a solution to this also. This page helped me today so, I am re-posting here too.

/** This is the script that will redraw current screen and submit to paypal. */
echo '<script>'."\n" ;
echo 'function serverNotifySelected()'."\n" ;
echo '{'."\n" ;
echo '    window.open(\'\', \'PayPalPayment\');'."\n" ;
echo '    document.forms[\'paypal_form\'].submit();'."\n" ;
echo '    document.forms[\'server_responder\'].submit();'."\n" ;
echo '}'."\n" ;
echo '</script>'."\n" ;

/** This form will be opened in a new window called PayPalPayment. */
echo '<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" name="paypal_form" method="post" target="PayPalPayment">'."\n" ;
echo '<input type="hidden" name="cmd" value="_s-xclick">'."\n" ;
echo '<input type="hidden" name="custom" value="'.$transaction_start.'">'."\n" ;
echo '<input type="hidden" name="hosted_button_id" value="'.$single_product->hosted_button_id.'">'."\n" ;
echo '<table>'."\n" ;
echo '    <tr>'."\n";
echo '        <td><input type="hidden" name="'.$single_product->hide_name_a.'" value="'.$single_product->hide_value_a.'">Local</td>'."\n" ;
echo '    </tr>'."\n" ;
echo '    <tr>'."\n" ;
echo '        <td>'."\n" ;
echo '        <input type="hidden" name="'.$single_product->hide_name_b.'" value="'.$single_product->hide_value_b.'" />'.$single_product->short_desc.' $'.$adj_price.' USD'."\n" ;
                // <select name="os0">
                //     <option value="1 Day">1 Day $1.55 USD</option>
                //     <option value="All Day">All Day $7.50 USD</option>
                //     <option value="3 Day">3 Day $23.00 USD</option>
                //     <option value="31 Day">31 Day $107.00 USD</option>
                // </select>
echo '        </td>'."\n" ;
echo '    </tr>'."\n" ;
echo '</table>'."\n" ;
echo '<input type="hidden" name="currency_code" value="USD">'."\n" ;
echo '</form>'."\n" ;

/** This form will redraw the current page for approval. */
echo '<form action="ProductApprove.php" name="server_responder" method="post" target="_top">'."\n" ;
echo '<input type="hidden" name="trans" value="'.$transaction_start.'">'."\n" ;
echo '<input type="hidden" name="prod_id" value="'.$this->product_id.'">'."\n" ;
echo '</form>'."\n" ;

/** No form here just an input and a button.  onClick will handle all the forms */
echo '<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" alt="PayPal - The safer, easier way to pay online!" onclick="serverNotifySelected()">'."\n" ;
echo '<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">'."\n" ;

The above code is the code for one button. You press the button and it will redraw the current screen from purchase to pre-approval. At the same time it opens a new window and hands that new window over to PayPal.

Automatic creation date for Django model form objects?

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

Programmatically getting the MAC of an Android device

Getting the MAC address through WifiInfo.getMacAddress() won't work on Marshmallow and above, it has been disabled and will return the constant value of 02:00:00:00:00:00.

Convert HTML Character Back to Text Using Java Standard Library

Or you can use unescapeHtml4:

    String miCadena="GU&#205;A TELEF&#211;NICA";
    System.out.println(StringEscapeUtils.unescapeHtml4(miCadena));

This code print the line: GUÍA TELEFÓNICA

How to instantiate a File object in JavaScript?

According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.

So to create a empty file do:

var f = new File([""], "filename");
  • The first argument is the data provided as an array of lines of text;
  • The second argument is the filename ;
  • The third argument looks like:

    var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
    

It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.

How to update array value javascript?

How about;

function keyValue(key, value){
    this.Key = key;
    this.Value = value;
};
keyValue.prototype.updateTo = function(newKey, newValue) {
    this.Key = newKey;
    this.Value = newValue;  
};

array[1].updateTo("xxx", "999");   

Convert double to BigDecimal and set BigDecimal Precision

Why not :

b = b.setScale(2, RoundingMode.HALF_UP);

When should I use UNSIGNED and SIGNED INT in MySQL?

Use UNSIGNED for non-negative integers.

HTTP client timeout and server timeout

According to https://bugzilla.mozilla.org/show_bug.cgi?id=592284, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.

How to fix 'Microsoft Excel cannot open or save any more documents'

Right click on the file with file explorer, choose Properties, then General tab and click on the Unblock button. This error message is very misleading.

Exit codes in Python

From the documentation for sys.exit:

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. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.

One example where exit codes are used are in shell scripts. In Bash you can check the special variable $? for the last exit status:

me@mini:~$ python -c ""; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(0)"; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(43)"; echo $?
43

Personally I try to use the exit codes I find in /usr/include/asm-generic/errno.h (on a Linux system), but I don't know if this is the right thing to do.

Get all LI elements in array

After some years have passed, you can do that now with ES6 Array.from (or spread syntax):

_x000D_
_x000D_
const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));_x000D_
console.log('Get first: ', navbar[0].textContent);_x000D_
_x000D_
// If you need to iterate once over all these nodes, you can use the callback function:_x000D_
console.log('Iterate with Array.from callback argument:');_x000D_
Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))_x000D_
_x000D_
// ... or a for...of loop:_x000D_
console.log('Iterate with for...of:');_x000D_
for (const li of document.querySelectorAll('#navbar>ul>li')) {_x000D_
    console.log(li.textContent);_x000D_
}
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<div id="navbar">_x000D_
  <ul>_x000D_
    <li id="navbar-One">One</li>_x000D_
    <li id="navbar-Two">Two</li>_x000D_
    <li id="navbar-Three">Three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Char to int conversion in C

Since you're only converting one character, the function atoi() is overkill. atoi() is useful if you are converting string representations of numbers. The other posts have given examples of this. If I read your post correctly, you are only converting one numeric character. So, you are only going to convert a character that is the range 0 to 9. In the case of only converting one numeric character, your suggestion to subtract '0' will give you the result you want. The reason why this works is because ASCII values are consecutive (like you said). So, subtracting the ASCII value of 0 (ASCII value 48 - see ASCII Table for values) from a numeric character will give the value of the number. So, your example of c = c - '0' where c = '5', what is really happening is 53 (the ASCII value of 5) - 48 (the ASCII value of 0) = 5.

When I first posted this answer, I didn't take into consideration your comment about being 100% portable between different character sets. I did some further looking around around and it seems like your answer is still mostly correct. The problem is that you are using a char which is an 8-bit data type. Which wouldn't work with all character types. Read this article by Joel Spolsky on Unicode for a lot more information on Unicode. In this article, he says that he uses wchar_t for characters. This has worked well for him and he publishes his web site in 29 languages. So, you would need to change your char to a wchar_t. Other than that, he says that the character under value 127 and below are basically the same. This would include characters that represent numbers. This means the basic math you proposed should work for what you were trying to achieve.

TypeError: not all arguments converted during string formatting python

For me, This error was caused when I was attempting to pass in a tuple into the string format method.

I found the solution from this question/answer

Copying and pasting the correct answer from the link (NOT MY WORK):

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.

Getting error "No such module" using Xcode, but the framework is there

This error can also be caused by the framework lacking a module map. If the framework you are trying to import is yours, check for compiler warnings on the framework itself. In my case my framework was building and in place, but there was a build warning:

warning: no umbrella header found for target 'MyFramework', module map will not be generated

By resolving this warning (which related to the framework header not matching the module name), I was able to import the framework.

How does paintComponent work?

The internals of the GUI system call that method, and they pass in the Graphics parameter as a graphics context onto which you can draw.

How do I declare a global variable in VBA?

If this function is in a module/class, you could just write them outside of the function, so it has Global Scope. Global Scope means the variable can be accessed by another function in the same module/class (if you use dim as declaration statement, use public if you want the variables can be accessed by all function in all modules) :

Dim iRaw As Integer
Dim iColumn As Integer

Function find_results_idle()
    iRaw = 1
    iColumn = 1
End Function

Function this_can_access_global()
    iRaw = 2
    iColumn = 2
End Function

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

T-SQL Cast versus Convert

CAST uses ANSI standard. In case of portability, this will work on other platforms. CONVERT is specific to sql server. But is very strong function. You can specify different styles for dates

How to update parent's state in React?

I found the following working solution to pass onClick function argument from child to the parent component with param:

parent class :

class Parent extends React.Component {
constructor(props) {
    super(props)

    // Bind the this context to the handler function
    this.handler = this.handler.bind(this);

    // Set some state
    this.state = {
        messageShown: false
    };
}

// This method will be sent to the child component
handler(param1) {
console.log(param1);
    this.setState({
        messageShown: true
    });
}

// Render the child component and set the action property with the handler as value
render() {
    return <Child action={this.handler} />
}}

child class :

class Child extends React.Component {
render() {
    return (
        <div>
            {/* The button will execute the handler function set by the parent component */}
            <Button onClick={this.props.action.bind(this,param1)} />
        </div>
    )
} }

How do I remove diacritics (accents) from a string in .NET?

In case anyone's interested, here is the java equivalent:

import java.text.Normalizer;

public class MyClass
{
    public static String removeDiacritics(String input)
    {
        String nrml = Normalizer.normalize(input, Normalizer.Form.NFD);
        StringBuilder stripped = new StringBuilder();
        for (int i=0;i<nrml.length();++i)
        {
            if (Character.getType(nrml.charAt(i)) != Character.NON_SPACING_MARK)
            {
                stripped.append(nrml.charAt(i));
            }
        }
        return stripped.toString();
    }
}

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

Python 3.8 with boto3 v1.16v - 2020 December

For configuring routes, you have to configure API Gateway to accept routes. otherwise other than the base route everything else will end up in a {missing auth token} or something other...

Once you configured API Gateway to accept routes, make sure that you enabled lambda proxy, so that things will work better,

to access routes,

new_route = event['path'] # /{some_url}

to access query parameter

query_param = event['queryStringParameters'][{query_key}]

Error Code: 1005. Can't create table '...' (errno: 150)

My problem was not listed, it was something so silly ..... The table that has the FK as PK was a composite PK that was declared like this: primary key (CNPJ, CEP) I wanted the CEP field to be FK in another table and I was stuck in this error, the moral of the story just inverted the code above for Primary key (CEP, CNPJ) and it worked. Get tip their friends.

Nginx fails to load css files

I also face this issue, I tried a lot of solutions, but none really worked for me

Here's how I solved it;

A. Grant ownership of the domain document root directory (say my root directory is/var/www/nginx-demo) to the Nginx user (www-data) to avoid any permission issues:

sudo chown -R www-data: /var/www/nginx-demo

B. Confirm that your virtual host server block conforms to this standard (say I am using localhost as my server_name and my root as /var/www/nginx-demo/website)

server {
   listen 80;
   listen [::]:80;

   server_name localhost;

   root /var/www/nginx-demo/website;
   index index.html;

   location / {
            try_files $uri $uri/ =404;
   }
}

C. Test the Nginx configuration for correct syntax:

sudo nginx -t

If there are no errors in the configuration syntax the output will look like this:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

D. Restart the Nginx service for the changes to take effect:

sudo systemctl restart nginx

E. Hard refresh your website in your browser to avoid cached files with incorrect headers using the keyboard keys Ctrl + F5 or Ctrl + Fn + F5.

That's all.

I hope this helps.

JQuery Event for user pressing enter in a textbox?

Another subtle variation. I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:

(function($) { $.fn.catchEnter = function(sel) {  
    return this.each(function() { 
        $(this).on('keyup',sel,function(e){
            if(e.keyCode == 13)
              $(this).trigger("enterkey");
        })
    });  
};
})(jQuery);

And then in use:

$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });

This variation allows you to use event delegation (to bind to elements you haven't created yet).

$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });

SQL Switch/Case in 'where' clause

The problem with this is that when the SQL engine goes to evaluate the expression, it checks the FROM portion to pull the proper tables, and then the WHERE portion to provide some base criteria, so it cannot properly evaluate a dynamic condition on which column to check against.

You can use a WHERE clause when you're checking the WHERE criteria in the predicate, such as

WHERE account_location = CASE @locationType
                              WHEN 'business' THEN 45
                              WHEN 'area' THEN 52
                         END

so in your particular case, you're going to need put the query into a stored procedure or create three separate queries.

Try/catch does not seem to have an effect

I was able to duplicate your result when trying to run a remote WMI query. The exception thrown is not caught by the Try/Catch, nor will a Trap catch it, since it is not a "terminating error". In PowerShell, there are terminating errors and non-terminating errors . It appears that Try/Catch/Finally and Trap only works with terminating errors.

It is logged to the $error automatic variable and you can test for these type of non-terminating errors by looking at the $? automatic variable, which will let you know if the last operation succeeded ($true) or failed ($false).

From the appearance of the error generated, it appears that the error is returned and not wrapped in a catchable exception. Below is a trace of the error generated.

PS C:\scripts\PowerShell> Trace-Command -Name errorrecord  -Expression {Get-WmiObject win32_bios -ComputerName HostThatIsNotThere}  -PSHost
DEBUG: InternalCommand Information: 0 :  Constructor Enter Ctor
Microsoft.PowerShell.Commands.GetWmiObjectCommand: 25857563
DEBUG: InternalCommand Information: 0 :  Constructor Leave Ctor
Microsoft.PowerShell.Commands.GetWmiObjectCommand: 25857563
DEBUG: ErrorRecord Information: 0 :  Constructor Enter Ctor
System.Management.Automation.ErrorRecord: 19621801 exception =
System.Runtime.InteropServices.COMException (0x800706BA): The RPC
server is unavailable. (Exception from HRESULT: 0x800706BA)
   at
System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Management.ManagementScope.InitializeGuts(Object o)
   at System.Management.ManagementScope.Initialize()
   at System.Management.ManagementObjectSearcher.Initialize()
   at System.Management.ManagementObjectSearcher.Get()
   at Microsoft.PowerShell.Commands.GetWmiObjectCommand.BeginProcessing()
errorId = GetWMICOMException errorCategory = InvalidOperation
targetObject =
DEBUG: ErrorRecord Information: 0 :  Constructor Leave Ctor
System.Management.Automation.ErrorRecord: 19621801

A work around for your code could be:

try
{
    $colItems = get-wmiobject -class "Win32_PhysicalMemory" -namespace "root\CIMV2" -computername $strComputerName -Credential $credentials
    if ($?)
    {
      foreach ($objItem in $colItems) 
      {
          write-host "Bank Label: " $objItem.BankLabel
          write-host "Capacity: " ($objItem.Capacity / 1024 / 1024)
          write-host "Caption: " $objItem.Caption
          write-host "Creation Class Name: " $objItem.CreationClassName      
          write-host
      }
    }
    else
    {
       throw $error[0].Exception
    }

Converting std::__cxx11::string to std::string

In my case, I was having a similar problem:

/usr/bin/ld: Bank.cpp:(.text+0x19c): undefined reference to 'Account::SetBank(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)' collect2: error: ld returned 1 exit status

After some researches, I realized that the problem was being generated by the way that Visual Studio Code was compiling the Bank.cpp file. So, to solve that, I just prompted the follow command in order to compile the c++ file sucessful:

g++ Bank.cpp Account.cpp -o Bank

With the command above, It was able to linkage correctly the Header, Implementations and Main c++ files.

OBS: My g++ version: 9.3.0 on Ubuntu 20.04

How to search in a List of Java object

Using Java 8

With Java 8 you can simply convert your list to a stream allowing you to write:

import java.util.List;
import java.util.stream.Collectors;

List<Sample> list = new ArrayList<Sample>();
List<Sample> result = list.stream()
    .filter(a -> Objects.equals(a.value3, "three"))
    .collect(Collectors.toList());

Note that

  • a -> Objects.equals(a.value3, "three") is a lambda expression
  • result is a List with a Sample type
  • It's very fast, no cast at every iteration
  • If your filter logic gets heavier, you can do list.parallelStream() instead of list.stream() (read this)


Apache Commons

If you can't use Java 8, you can use Apache Commons library and write:

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

Collection result = CollectionUtils.select(list, new Predicate() {
     public boolean evaluate(Object a) {
         return Objects.equals(((Sample) a).value3, "three");
     }
 });

// If you need the results as a typed array:
Sample[] resultTyped = (Sample[]) result.toArray(new Sample[result.size()]);

Note that:

  • There is a cast from Object to Sample at each iteration
  • If you need your results to be typed as Sample[], you need extra code (as shown in my sample)



Bonus: A nice blog article talking about how to find element in list.

Make HTML5 video poster be same size as video itself

height:500px;
min-width:100%;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size:100% 100%;
object-fit:cover;

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size:cover;

Match whitespace but not newlines

Perl versions 5.10 and later support subsidiary vertical and horizontal character classes, \v and \h, as well as the generic whitespace character class \s

The cleanest solution is to use the horizontal whitespace character class \h. This will match tab and space from the ASCII set, non-breaking space from extended ASCII, or any of these Unicode characters

U+0009 CHARACTER TABULATION
U+0020 SPACE
U+00A0 NO-BREAK SPACE (not matched by \s)

U+1680 OGHAM SPACE MARK
U+2000 EN QUAD
U+2001 EM QUAD
U+2002 EN SPACE
U+2003 EM SPACE
U+2004 THREE-PER-EM SPACE
U+2005 FOUR-PER-EM SPACE
U+2006 SIX-PER-EM SPACE
U+2007 FIGURE SPACE
U+2008 PUNCTUATION SPACE
U+2009 THIN SPACE
U+200A HAIR SPACE
U+202F NARROW NO-BREAK SPACE
U+205F MEDIUM MATHEMATICAL SPACE
U+3000 IDEOGRAPHIC SPACE

The vertical space pattern \v is less useful, but matches these characters

U+000A LINE FEED
U+000B LINE TABULATION
U+000C FORM FEED
U+000D CARRIAGE RETURN
U+0085 NEXT LINE (not matched by \s)

U+2028 LINE SEPARATOR
U+2029 PARAGRAPH SEPARATOR

There are seven vertical whitespace characters which match \v and eighteen horizontal ones which match \h. \s matches twenty-three characters

All whitespace characters are either vertical or horizontal with no overlap, but they are not proper subsets because \h also matches U+00A0 NO-BREAK SPACE, and \v also matches U+0085 NEXT LINE, neither of which are matched by \s

Automated Python to Java translation

Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc

In fact, this is probably pretty easy to knock up in Python.

I worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.

Here's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.

How can strip whitespaces in PHP's variable?

You can use trim function from php to trim both sides (left and right)

 trim($yourinputdata," ");

Or

trim($yourinputdata);

You can also use

ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a string

System: PHP 4,5,7
Docs: http://php.net/manual/en/function.trim.php

Purpose of installing Twitter Bootstrap through npm?

  1. Use npm/bower to install bootstrap if you want to recompile it/change less files/test. With grunt it would be easier to do this, as shown on http://getbootstrap.com/getting-started/#grunt. If you only want to add precompiled libraries feel free to manually include files to project.

  2. No, you have to do this by yourself or use separate grunt tool. For example 'grunt-contrib-concat' How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

How can I disable all views inside the layout?

You can have whichever children that you want to have the same state as the parents include android:duplicateParentState="true".  Then if you disable the parent, whatever children you have that set on will follow suit.  

This will allow you to dynamically control all states at once from the parent view.

<LinearLayout
    android:id="@+id/some_parent_something"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
     <Button 
        android:id="@+id/backbutton"
        android:text="Back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:duplicateParentState="true"/>
    <LinearLayout
        android:id="@+id/my_layout"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:duplicateParentState="true">
        <TextView
            android:id="@+id/my_text_view"
            android:text="First Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:duplicateParentState="true" />
        <EditText
            android:id="@+id/my_edit_view"
            android:width="100px"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:duplicateParentState="true" /> 
        <View .../>
        <View .../>
        ...
           <View .../>
    </LinearLayout>

</LinearLayout>

ASP.NET strange compilation error

In IIS Manager, in the advanced settings of the Application Pool, make sure "Process Model ? Load User Profile" is set to "True". In my case it worked.

Clear the entire history stack and start a new activity on Android

In API level 11 a new Intent Flag was added just for this: Intent.FLAG_ACTIVITY_CLEAR_TASK

Just to clarify, use this:

Java

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

Kotlin

intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

Unfortunately for API lvl <= 10, I haven't yet found a clean solution to this. The "DontHackAndroidLikeThis" solution is indeed pure hackery. You should not do that. :)

Edit: As per @Ben Pearson's comment, for API <=10 now one can use IntentCompat class for the same. One can use IntentCompat.FLAG_ACTIVITY_CLEAR_TASK flag to clear task. So you can support pre API level 11 as well.

How to format a float in javascript?

There is a problem with all those solutions floating around using multipliers. Both kkyy and Christoph's solutions are wrong unfortunately.

Please test your code for number 551.175 with 2 decimal places - it will round to 551.17 while it should be 551.18 ! But if you test for ex. 451.175 it will be ok - 451.18. So it's difficult to spot this error at a first glance.

The problem is with multiplying: try 551.175 * 100 = 55117.49999999999 (ups!)

So my idea is to treat it with toFixed() before using Math.round();

function roundFix(number, precision)
{
    var multi = Math.pow(10, precision);
    return Math.round( (number * multi).toFixed(precision + 1) ) / multi;
}

Atom menu is missing. How do I re-enable

Open atom editor and then press Alt and menu bar will appear. Now click on View tab and then click on Toggle Menu Bar as seen on this screenshot.

JPanel setBackground(Color.BLACK) does nothing

setOpaque(false); 

CHANGED to

setOpaque(true);

Correct format specifier for double in printf

Given the C99 standard (namely, the N1256 draft), the rules depend on the function kind: fprintf (printf, sprintf, ...) or scanf.

Here are relevant parts extracted:

Foreword

This second edition cancels and replaces the first edition, ISO/IEC 9899:1990, as amended and corrected by ISO/IEC 9899/COR1:1994, ISO/IEC 9899/AMD1:1995, and ISO/IEC 9899/COR2:1996. Major changes from the previous edition include:

  • %lf conversion specifier allowed in printf

7.19.6.1 The fprintf function

7 The length modifiers and their meanings are:

l (ell) Specifies that (...) has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument.

The same rules specified for fprintf apply for printf, sprintf and similar functions.

7.19.6.2 The fscanf function

11 The length modifiers and their meanings are:

l (ell) Specifies that (...) that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double;

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to long double.

12 The conversion specifiers and their meanings are: a,e,f,g Matches an optionally signed floating-point number, (...)

14 The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.

The long story short, for fprintf the following specifiers and corresponding types are specified:

  • %f -> double
  • %Lf -> long double.

and for fscanf it is:

  • %f -> float
  • %lf -> double
  • %Lf -> long double.

Can I grep only the first n lines of a file?

grep "pattern" <(head -n 10 filename)

Retrieve data from a ReadableStream object?

Note that you can only read a stream once, so in some cases, you may need to clone the response in order to repeatedly read it:

fetch('example.json')
  .then(res=>res.clone().json())
  .then( json => console.log(json))

fetch('url_that_returns_text')
  .then(res=>res.clone().text())
  .then( text => console.log(text))