Programs & Examples On #Browsable

no module named urllib.parse (How should I install it?)

python3 supports urllib.parse and python2 supports urlparse

If you want both compatible then the following code can help.

import sys

if ((3, 0) <= sys.version_info <= (3, 9)):
    from urllib.parse import urlparse
elif ((2, 0) <= sys.version_info <= (2, 9)):
    from urlparse import urlparse

Update: Change if condition to support higher versions if (3, 0) <= sys.version_info:.

How to hide column of DataGridView when using custom DataSource?

Set that particular column's Visible property = false

dataGridView[ColumnName or Index].Visible = false;

Edit sorry missed the Columns Property dataGridView.Columns[ColumnName or Index].Visible = false;

Make a link in the Android browser start up my app?

I also faced this issue and see many absurd pages. I've learned that to make your app browsable, change the order of the XML elements, this this:

<activity
    android:name="com.example.MianActivityName"
    android:label="@string/title_activity_launcher">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>                
        <data android:scheme="http" />     
        <!-- or you can use deep linking like  -->               

        <data android:scheme="http" android:host="xyz.abc.com"/>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <category android:name="android.intent.category.DEFAULT"/>

    </intent-filter>
</activity>

This worked for me and might help you.

How do I do pagination in ASP.NET MVC?

I had the same problem and found a very elegant solution for a Pager Class from

http://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/

In your controller the call looks like:

return View(partnerList.ToPagedList(currentPageIndex, pageSize));

and in your view:

<div class="pager">
    Seite: <%= Html.Pager(ViewData.Model.PageSize, 
                          ViewData.Model.PageNumber,
                          ViewData.Model.TotalItemCount)%>
</div>

Most Useful Attributes

[System.Security.Permissions.PermissionSetAttribute] allows security actions for a PermissionSet to be applied to code using declarative security.

// usage:
public class FullConditionUITypeEditor : UITypeEditor
{
    // The immediate caller is required to have been granted the FullTrust permission.
    [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
    public FullConditionUITypeEditor() { }
}

Hidden Features of C#?

With reference to the post w/ perma link "Hidden Features of C#?", there is another way to accomplish the same - indentation / line breaks. Check this out..

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.NewLineOnAttributes = true;
xmlWriterSettings.Indent = true;


XmlWriter xml = XmlWriter.Create(@"C:\file.xml", xmlWriterSettings);

// Start writing the data using xml.WriteStartElement(), xml.WriteElementString(...), xml.WriteEndElement() etc

I am not sure whether this is an unknown feature though!

better way to drop nan rows in pandas

Just in case commands in previous answers doesn't work, Try this: dat.dropna(subset=['x'], inplace = True)

What is a reasonable length limit on person "Name" fields?

In the UK, there are a few government standards which deal successfully with the bulk of the UK population -- the Passport Office, the Driver & Vehicle Licensing Agency, the Deed Poll office, and the NHS. They use different standards, obviously.

Changing your name by Deed Poll allows 300 characters;

There is no legal limit on the length of your name, but we impose a limit of 300 characters (including spaces) for your full name.

The NHS uses 70 characters for patient names

PATIENT NAME
Format/length: max an70

The Passport Office allows 30+30 first/last and Driving Licenses (DVLA) is 30 total.

Note that other organisations will have their own restrictions about what they will show on the documents they produce — for HM Passport Office the limit is 30 characters each for your forename and your surname, and for the DVLA the limit is 30 characters in total for your full name.

$.widget is not a function

Maybe placing the jquery.ui.widget.js as second after jquery.ui.core.js.

What is the MySQL VARCHAR max size?

As per the online docs, there is a 64K row limit and you can work out the row size by using:

row length = 1
             + (sum of column lengths)
             + (number of NULL columns + delete_flag + 7)/8
             + (number of variable-length columns)

You need to keep in mind that the column lengths aren't a one-to-one mapping of their size. For example, CHAR(10) CHARACTER SET utf8 requires three bytes for each of the ten characters since that particular encoding has to account for the three-bytes-per-character property of utf8 (that's MySQL's utf8 encoding rather than "real" UTF-8, which can have up to four bytes).

But, if your row size is approaching 64K, you may want to examine the schema of your database. It's a rare table that needs to be that wide in a properly set up (3NF) database - it's possible, just not very common.

If you want to use more than that, you can use the BLOB or TEXT types. These do not count against the 64K limit of the row (other than a small administrative footprint) but you need to be aware of other problems that come from their use, such as not being able to sort using the entire text block beyond a certain number of characters (though this can be configured upwards), forcing temporary tables to be on disk rather than in memory, or having to configure client and server comms buffers to handle the sizes efficiently.

The sizes allowed are:

TINYTEXT          255 (+1 byte  overhead)
TEXT          64K - 1 (+2 bytes overhead)
MEDIUMTEXT    16M - 1 (+3 bytes overhead)
LONGTEXT      4G  - 1 (+4 bytes overhead)

You still have the byte/character mismatch (so that a MEDIUMTEXT utf8 column can store "only" about half a million characters, (16M-1)/3 = 5,592,405) but it still greatly expands your range.

JavaScript: changing the value of onclick with or without jQuery

Note that following gnarf's idea you can also do:

var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;

That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).

How to monitor the memory usage of Node.js?

The built-in process module has a method memoryUsage that offers insight in the memory usage of the current Node.js process. Here is an example from in Node v0.12.2 on a 64-bit system:

$ node --expose-gc
> process.memoryUsage();  // Initial usage
{ rss: 19853312, heapTotal: 9751808, heapUsed: 4535648 }
> gc();                   // Force a GC for the baseline.
undefined
> process.memoryUsage();  // Baseline memory usage.
{ rss: 22269952, heapTotal: 11803648, heapUsed: 4530208 }
> var a = new Array(1e7); // Allocate memory for 10m items in an array
undefined
> process.memoryUsage();  // Memory after allocating so many items
{ rss: 102535168, heapTotal: 91823104, heapUsed: 85246576 }
> a = null;               // Allow the array to be garbage-collected
null
> gc();                   // Force GC (requires node --expose-gc)
undefined
> process.memoryUsage();  // Memory usage after GC
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4528072 }
> process.memoryUsage();  // Memory usage after idling
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4753376 }

In this simple example, you can see that allocating an array of 10M elements consumers approximately 80MB (take a look at heapUsed).
If you look at V8's source code (Array::New, Heap::AllocateRawFixedArray, FixedArray::SizeFor), then you'll see that the memory used by an array is a fixed value plus the length multiplied by the size of a pointer. The latter is 8 bytes on a 64-bit system, which confirms that observed memory difference of 8 x 10 = 80MB makes sense.

Using :before CSS pseudo element to add image to modal

Content and before are both highly unreliable across browsers. I would suggest sticking with jQuery to accomplish this. I'm not sure what you're doing to figure out if this carrot needs to be added or not, but you should get the overall idea:

$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");

How to find out the MySQL root password

Unless the package manager requests you to type the root password during installation, the default root password is the empty string. To connect to freshly installed server, type:

shell> mysql -u root --password=
mysql>

To change the password, get back the unix shell and type:

shell> mysqladmin -u root --password= password root

The new password is 'root'. Now connect to the server:

shell> mysql -u root --password=
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Oops, the password has changed. Use the new one, root:

shell> mysql -u root --password=root
...
blah, blah, blah : mysql welcome banner
...
mysql> 

Bingo! New do something interesting

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

Maurycy

For Restful API, can GET method use json data?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).

I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1&param2=val2) or JSON (parsed by your API upon receipt)

How can I clear event subscriptions in C#?

Remove all events, assume the event is an "Action" type:

Delegate[] dary = TermCheckScore.GetInvocationList();

if ( dary != null )
{
    foreach ( Delegate del in dary )
    {
        TermCheckScore -= ( Action ) del;
    }
}

How can I search an array in VB.NET?

In case you were looking for an older version of .NET then use:

Module Module1

    Sub Main()
        Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
        Dim result As New List(Of Integer)
        For i As Integer = 0 To arr.Length
            If arr(i).Contains("ra") Then result.Add(i)
        Next
    End Sub

End Module

Setting up MySQL and importing dump within Dockerfile

The latest version of the official mysql docker image allows you to import data on startup. Here is my docker-compose.yml

data:
  build: docker/data/.
mysql:
  image: mysql
  ports:
    - "3307:3306"
  environment:
    MYSQL_ROOT_PASSWORD: 1234
  volumes:
    - ./docker/data:/docker-entrypoint-initdb.d
  volumes_from:
    - data

Here, I have my data-dump.sql under docker/data which is relative to the folder the docker-compose is running from. I am mounting that sql file into this directory /docker-entrypoint-initdb.d on the container.

If you are interested to see how this works, have a look at their docker-entrypoint.sh in GitHub. They have added this block to allow importing data

    echo
    for f in /docker-entrypoint-initdb.d/*; do
        case "$f" in
            *.sh)  echo "$0: running $f"; . "$f" ;;
            *.sql) echo "$0: running $f"; "${mysql[@]}" < "$f" && echo ;;
            *)     echo "$0: ignoring $f" ;;
        esac
        echo
    done

An additional note, if you want the data to be persisted even after the mysql container is stopped and removed, you need to have a separate data container as you see in the docker-compose.yml. The contents of the data container Dockerfile are very simple.

FROM n3ziniuka5/ubuntu-oracle-jdk:14.04-JDK8

VOLUME /var/lib/mysql

CMD ["true"]

The data container doesn't even have to be in start state for persistence.

Is there a sleep function in JavaScript?

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.

Configure Log4net to write to multiple files

Use below XML configuration to configure logs into two or more files:

<log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log.txt" />         
      <appendToFile value="true" /> 
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">           
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
     <appender name="RollingLogFileAppender2" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log1.txt" />         
      <appendToFile value="true" /> 
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">        
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="All" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
     <logger additivity="false" name="RollingLogFileAppender2">
    <level value="All"/>
    <appender-ref ref="RollingLogFileAppender2" />
    </logger>
  </log4net>

Above XML configuration logs into two different files. To get specific instance of logger programmatically:

ILog logger = log4net.LogManager.GetLogger ("RollingLogFileAppender2");

You can append two or more appender elements inside log4net root element for logging into multiples files.

More info about above XML configuration structure or which appender is best for your application, read details from below links:

https://logging.apache.org/log4net/release/manual/configuration.html https://logging.apache.org/log4net/release/sdk/index.html

Shortcut key for commenting out lines of Python code in Spyder

on Windows F9 to run single line

Select the lines which you want to run on console and press F9 button for multi line

How do I access the $scope variable in browser's console using AngularJS?

If you have installed Batarang

Then you can just write:

$scope

when you have the element selected in the elements view in chrome. Ref - https://github.com/angular/angularjs-batarang#console

How to programmatically empty browser cache?

Imagine the .js files are placed in /my-site/some/path/ui/js/myfile.js

So normally the script tag would look like:

<script src="/my-site/some/path/ui/js/myfile.js"></script>

Now change that to:

<script src="/my-site/some/path/ui-1111111111/js/myfile.js"></script>

Now of course that will not work. To make it work you need to add one or a few lines to your .htaccess The important line is: (entire .htaccess at the bottom)

RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]

So what this does is, it kind of removes the 1111111111 from the path and links to the correct path.

So now if you make changes you just have to change the number 1111111111 to whatever number you want. And however you include your files you can set that number via a timestamp when the js-file has last been modified. So cache will work normally if the number does not change. If it changes it will serve the new file (YES ALWAYS) because the browser get's a complete new URL and just believes that file is so new he must go get it.

You can use this for CSS, favicons and what ever gets cached. For CSS just use like so

<link href="http://my-domain.com/my-site/some/path/ui-1492513798/css/page.css" type="text/css" rel="stylesheet">

And it will work! Simple to update, simple to maintain.

The promised full .htaccess

If you have no .htaccess yet this is the minimum you need to have there:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]
</IfModule>

How do I reverse a commit in git?

I think you need to push a revert commit. So pull from github again, including the commit you want to revert, then use git revert and push the result.

If you don't care about other people's clones of your github repository being broken, you can also delete and recreate the master branch on github after your reset: git push origin :master.

How to convert buffered image to image and vice-versa?

BufferedImage is a(n) Image, so the implicit cast that you're doing in the second line is able to be compiled directly. If you knew an Image was really a BufferedImage, you would have to cast it explicitly like so:

Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;

Because BufferedImage extends Image, it can fit in an Image container. However, any Image can fit there, including ones that are not a BufferedImage, and as such you may get a ClassCastException at runtime if the type does not match, because a BufferedImage cannot hold any other type unless it extends BufferedImage.

Catching "Maximum request length exceeded"

After tag

<security>
     <requestFiltering>
         <requestLimits maxAllowedContentLength="4500000" />
     </requestFiltering>
</security>

add the following tag

 <httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" subStatusCode="13" />
  <error statusCode="404" subStatusCode="13" prefixLanguageFilePath="" path="http://localhost/ErrorPage.aspx" responseMode="Redirect" />
</httpErrors>

you can add the Url to the error page...

What is the difference between XAMPP or WAMP Server & IIS?

In addition to the above, WAMP supports 64 bit PHP on Windows systems while XAMPP only offers 32 bit versions. This actually made me switch to WAMP on my Windows machine since you need 64 bit PHP 7 to get bigint numbers correctly from MySQL

How do I check in SQLite whether a table exists?

Use:

PRAGMA table_info(your_table_name)

If the resulting table is empty then your_table_name doesn't exist.

Documentation:

PRAGMA schema.table_info(table-name);

This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column. The "pk" column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.

The table named in the table_info pragma can also be a view.

Example output:

cid|name|type|notnull|dflt_value|pk
0|id|INTEGER|0||1
1|json|JSON|0||0
2|name|TEXT|0||0

How to hide a div from code (c#)

In code behind:

{
    yourDiv.Visible = false;
}

Is it better to use path() or url() in urls.py for django 2.0?

Path is a new feature of Django 2.0. Explained here : https://docs.djangoproject.com/en/2.0/releases/2.0/#whats-new-2-0

Look like more pythonic way, and enable to not use regular expression in argument you pass to view... you can ue int() function for exemple.

Swipe ListView item From right to left show delete button

I had created a demo on my github which includes on swiping from right to left a delete button will appear and you can then delete your item from the ListView and update your ListView.

How to do one-liner if else statement?

As the others mentioned, Go does not support ternary one-liners. However, I wrote a utility function that could help you achieve what you want.

// IfThenElse evaluates a condition, if true returns the first parameter otherwise the second
func IfThenElse(condition bool, a interface{}, b interface{}) interface{} {
    if condition {
        return a
    }
    return b
}

Here are some test cases to show how you can use it

func TestIfThenElse(t *testing.T) {
    assert.Equal(t, IfThenElse(1 == 1, "Yes", false), "Yes")
    assert.Equal(t, IfThenElse(1 != 1, nil, 1), 1)
    assert.Equal(t, IfThenElse(1 < 2, nil, "No"), nil)
}

For fun, I wrote more useful utility functions such as:

IfThen(1 == 1, "Yes") // "Yes"
IfThen(1 != 1, "Woo") // nil
IfThen(1 < 2, "Less") // "Less"

IfThenElse(1 == 1, "Yes", false) // "Yes"
IfThenElse(1 != 1, nil, 1)       // 1
IfThenElse(1 < 2, nil, "No")     // nil

DefaultIfNil(nil, nil)  // nil
DefaultIfNil(nil, "")   // ""
DefaultIfNil("A", "B")  // "A"
DefaultIfNil(true, "B") // true
DefaultIfNil(1, false)  // 1

FirstNonNil(nil, nil)                // nil
FirstNonNil(nil, "")                 // ""
FirstNonNil("A", "B")                // "A"
FirstNonNil(true, "B")               // true
FirstNonNil(1, false)                // 1
FirstNonNil(nil, nil, nil, 10)       // 10
FirstNonNil(nil, nil, nil, nil, nil) // nil
FirstNonNil()                        // nil

If you would like to use any of these, you can find them here https://github.com/shomali11/util

How do I generate a random number between two variables that I have stored?

If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:

//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);

That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...

Hope this helps - Luke

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

The query you are after will be

SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%'

Update one MySQL table with values from another

UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id

That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read

As for running slow, how large are the tables? You should have indexes on tobeupdated.value and original.value

EDIT: we can also simplify the query

UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id

USING is shorthand when both tables of a join have an identical named key such as id. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join

How to create a QR code reader in a HTML5 website?

The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

This page didn't load Google Maps correctly. See the JavaScript console for technical details

The fix is really simple: just replace YOUR_API_KEY on the last line of your code with your actual API key!

If you don't have one, you can get it for free on the Google Developers Website.

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

add the below with URL Suffix

/override-http-headers-default-settings-x-frame-options

Auto-increment on partial primary key with Entity Framework Core

First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:

make sure you have correclty set the keys

modelBuilder.Entity<Foo>()
            .HasKey(p => new { p.Name, p.Id });
modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

OR you can achieve it using data annotation as well

public class Foo
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key, Column(Order = 0)]
    public int Id { get; set; }

    [Key, Column(Order = 1)]
    public string Name{ get; set; }
}

Slicing a dictionary

the dictionary

d = {1:2, 3:4, 5:6, 7:8}

the subset of keys I'm interested in

l = (1,5)

answer

{key: d[key] for key in l}

How can I expose more than 1 port with Docker?

If you are creating a container from an image and like to expose multiple ports (not publish) you can use the following command:

docker create --name `container name` --expose 7000 --expose 7001 `image name`

Now, when you start this container using the docker start command, the configured ports above will be exposed.

Use CSS to remove the space between images

I prefer do like this

img { float: left; }

to remove the space between images

Get value from hashmap based on key to JSTL

could you please try below code

<c:forEach var="hash" items="${map['key']}">
        <option><c:out value="${hash}"/></option>
  </c:forEach>

Spring application context external properties?

<context:property-placeholder location="file:/apps/tomcat/ath/ath_conf/pcr.application.properties" />

This works for me. Local development machine path is C:\apps\tomcat\ath\ath_conf and in server /apps/tomcat/ath/ath_conf

Both works for me

What's your most controversial programming opinion?

Inversion of control does not eliminate dependencies, but it sure does a great job of hiding them.

How to set an button align-right with Bootstrap?

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

How to remove a package from Laravel using composer?

In case the given answers still don't help you remove that, try this:

  • Manually delete the line in require from composer.json

  • Run composer update

CALL command vs. START with /WAIT option

This is an old thread, but I have just encountered this situation and discovered a neat way around it. I was trying to run a setup.exe, but the focus was returning to the next line of the script without waiting for the setup.exe to finish. I tried the above solutions with no luck.

In the end, piping the command through more did the trick.

setup.exe {arguments} | more

How to use multiple conditions (With AND) in IIF expressions in ssrs

Could you try this out?

=IIF((Fields!OpeningStock.Value=0) AND (Fields!GrossDispatched.Value=0) AND 
(Fields!TransferOutToMW.Value=0) AND (Fields!TransferOutToDW.Value=0) AND 
(Fields!TransferOutToOW.Value=0) AND (Fields!NetDispatched.Value=0) AND (Fields!QtySold.Value=0) 
AND (Fields!StockAdjustment.Value=0) AND (Fields!ClosingStock.Value=0),True,False)

Note: Setting Hidden to False will make the row visible

How to get current time with jQuery

Try

_x000D_
_x000D_
console.log(_x000D_
  new Date().toLocaleString().slice(9, -3)_x000D_
  , new Date().toString().slice(16, -15)_x000D_
);
_x000D_
_x000D_
_x000D_

Insert all data of a datagridview to database at once

Please see if below can help you

Class Post_Sales

Public Shared Sub Post_sales()

    Dim ITM_ID As Integer

    Dim SLS_QTY As Integer

    Dim SLS_PRC As Double

    Dim SLS_AMT As Double

    Dim DSPL_RCT As String

    Dim TAX_CODE As Integer


    'Format the current  date and send it to a textbox
    Form1.TextBox6.Text = System.DateTime.Now.ToString((" yyyy-MM-dd"))

    'Open Connection

    Dim con As New SqlConnection("Initial Catalog=Your Database here;Data source=.;Network Library=DBMSSOCN;User ID=sa;Password=")

    con.Open()

    'Insert Records into the database


    For Each rw As DataGridViewRow In Form1.DataGridView1.Rows

        ITM_ID = rw.Cells("Column1").Value
        DSPL_RCT = rw.Cells("Column2").Value
        SLS_QTY = rw.Cells("Column3").Value
        SLS_PRC = rw.Cells("Column4").Value
        SLS_AMT = rw.Cells("Column5").Value
        TAX_CODE = rw.Cells("Column6").Value

        Dim cmd As New SqlCommand("INSERT INTO DAY_PLUSALES (DT,ITM_ID,DSPL_RCT,SLS_QTY,SLS_PRC,SLS_AMT,TAX_CODE) values ('" & Form1.TextBox6.Text & "','" & ITM_ID & "','" & DSPL_RCT & "','" & SLS_QTY & "','" & SLS_PRC & "','" & SLS_AMT & "','" & TAX_CODE & "')", con)

        cmd.ExecuteNonQuery()

    Next

    con.Close()

    MessageBox.Show("Records Added to the SQL Database successfully!", "Records Updated ")

End Sub

End Class

SQL Developer is returning only the date, not the time. How do I fix this?

From Tools > Preferences > Database > NLS Parameter and set Date Format as

DD-MON-RR HH:MI:SS

Write to file, but overwrite it if it exists

If you have output that can have errors, you may want to use an ampersand and a greater than, as follows:

my_task &> 'Users/Name/Desktop/task_output.log' this will redirect both stderr and stdout to the log file (instead of stdout only).

Why calling react setState method doesn't mutate the state immediately?

Simply putting - this.setState({data: value}) is asynchronous in nature that means it moves out of the Call Stack and only comes back to the Call Stack unless it is resolved.

Please read about Event Loop to have a clear picture about Asynchronous nature in JS and why it takes time to update -

https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4

Hence -

    this.setState({data:value});
    console.log(this.state.data); // will give undefined or unupdated value

as it takes time to update. To achieve the above process -

    this.setState({data:value},function () {
     console.log(this.state.data);
    });

Svn switch from trunk to branch

In my case, I wanted to check out a new branch that has cut recently but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network

so I copped the previous branch that I already checked in

I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help)

svn switch ^/branches/newBranchName

go check svn info again you can see it is becoming the newBranchName go ahead and svn up

and this how I got the new branch easily, quickly with minimum data transmitting over the internet

hope sharing my case helps and speeds up your work

How to edit log message already committed in Subversion?

svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt

Liquibase lock - reasons?

In postgres 12 I needed to use this command:

UPDATE DATABASECHANGELOGLOCK SET LOCKED=false, LOCKGRANTED=null, LOCKEDBY=null where ID=1;

Difference between two dates in Python

Try this:

data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)


m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()




m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()

Doing HTTP requests FROM Laravel to an external API

Updated on March 21 2019

Add GuzzleHttp package using composer require guzzlehttp/guzzle:~6.3.3

Or you can specify Guzzle as a dependency in your project's composer.json

{
   "require": {
      "guzzlehttp/guzzle": "~6.3.3"
   }
}

Include below line in the top of the class where you are calling the API

use GuzzleHttp\Client;

Add below code for making the request

$client = new Client();

$res = $client->request('POST', 'http://www.exmple.com/mydetails', [
    'form_params' => [
        'name' => 'george',
    ]
]);

if ($res->getStatusCode() == 200) { // 200 OK
    $response_data = $res->getBody()->getContents();
}

Bootstrap 3 dropdown select

I'd like to extend the paulalexandru's answer and put here complete solution that works generally with bootstrap dropdowns and updating main button's content and also the value from selected option.

The bootstrap dropdown is defined this way:

<div class="btn-group" role="group">
  <button type="button" data-toggle="dropdown" value="1" class="btn btn-default btn-sm dropdown-toggle">
    Option 1 <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li><a href="#" data-value="1">Option 1</a></li>
    <li><a href="#" data-value="2">Option 2</a></li>
    <li><a href="#" data-value="3">Option 3</a></li>
  </ul>
</div> 

Additional to standard bootstrap dropdown code, there is data-value attribute for storing the values in every dropdown option (in <a> element).

Now the JS code. I crated function that handle the dropdowns:

function dropdownToggle() {
    // select the main dropdown button element
    var dropdown = $(this).parent().parent().prev();

    // change the CONTENT of the button based on the content of selected option
    dropdown.html($(this).html() + '&nbsp;</i><span class="caret"></span>');

    // change the VALUE of the button based on the data-value property of selected option
    dropdown.val($(this).prop('data-value'));
}

And of course we need to add event listener:

$(document).ready(function(){
    $('.dropdown-menu a').on('click', dropdownToggle);
}

Getting the last revision number in SVN?

The simplest and clean way to do that (actually svn 1.9, released 2015) is using:

svn info --show-item revision [--no-newline] [SVNURL/SVNPATH] 

The output is the number of the last revision (joungest) for the SVNURL, or the number of the current revision of the working copy of SVNPATH. The --no-newline is optional, instructs svn not to emit a cosmetic newline (\n) after the value, if you need minimal output (only the revision number).

See: https://subversion.apache.org/docs/release-notes/1.9.html#svn-info-item

Why can't I use Docker CMD multiple times to run multiple services?

While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...

To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).

Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."

Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop.

Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage

It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.

Good to know:

How to sum up elements of a C++ vector?

Actually there are quite a few methods.

int sum_of_elems = 0;

C++03

  1. Classic for loop:

    for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
        sum_of_elems += *it;
    
  2. Using a standard algorithm:

    #include <numeric>
    
    sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);
    

    Important Note: The last argument's type is used not just for the initial value, but for the type of the result as well. If you put an int there, it will accumulate ints even if the vector has float. If you are summing floating-point numbers, change 0 to 0.0 or 0.0f (thanks to nneonneo). See also the C++11 solution below.

C++11 and higher

  1. b. Automatically keeping track of the vector type even in case of future changes:

    #include <numeric>
    
    sum_of_elems = std::accumulate(vector.begin(), vector.end(),
                                   decltype(vector)::value_type(0));
    
  2. Using std::for_each:

    std::for_each(vector.begin(), vector.end(), [&] (int n) {
        sum_of_elems += n;
    });
    
  3. Using a range-based for loop (thanks to Roger Pate):

    for (auto& n : vector)
        sum_of_elems += n;
    

Postgresql : syntax error at or near "-"

Wrap it in double quotes

alter user "dell-sys" with password 'Pass@133';

Notice that you will have to use the same case you used when you created the user using double quotes. Say you created "Dell-Sys" then you will have to issue exact the same whenever you refer to that user.

I think the best you do is to drop that user and recreate without illegal identifier characters and without double quotes so you can later refer to it in any case you want.

How to get a pixel's x,y coordinate color from an image?

Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:

getPixel from HTML Canvas?

Some code that would serve you specifically as well:

var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

for (var i = 0, n = pix.length; i < n; i += 4) {
  console.log pix[i+3]
}

This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.

Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:

$('el').click(function(e){
   console.log(e.clientX, e.clientY)
}

Those should grab your x and y values.

Google Play Services Missing in Emulator (Android 4.4.2)

http://developer.android.com/google/play-services/setup.html

Quoting docs

If you want to test your app on the emulator, expand the directory for Android 4.2.2 (API 17) or a higher version, select Google APIs, and install it. Then create a new AVD with Google APIs as the platform target.

Needs Emulator of Google API"S

See the target in the snap

Snap

enter image description here

I prefer testing on a real device which has google play services installed

How to list active connections on PostgreSQL?

Following will give you active connections/ queries in postgres DB-

SELECT 
    pid
    ,datname
    ,usename
    ,application_name
    ,client_hostname
    ,client_port
    ,backend_start
    ,query_start
    ,query
    ,state
FROM pg_stat_activity
WHERE state = 'active';

You may use 'idle' instead of active to get already executed connections/queries.

How can I detect whether an iframe is loaded?

I imagine this like that:

<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
   frame_loaded = 1;
   alert("Iframe is loaded");
}
$('#click').click(function(){
   if(frame_loaded == 1)
    console.log('iframe loaded')
   } else {
    console.log('iframe not loaded')
   }
})
</script>
</head>
<button id='click'>click me</button>

<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>

Return file in ASP.Net Core Web API

If this is ASP.net-Core then you are mixing web API versions. Have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model.

[Route("api/[controller]")]
public class DownloadController : Controller {
    //GET api/download/12345abc
    [HttpGet("{id}"]
    public async Task<IActionResult> Download(string id) {
        Stream stream = await {{__get_stream_based_on_id_here__}}

        if(stream == null)
            return NotFound(); // returns a NotFoundResult with Status404NotFound response.

        return File(stream, "application/octet-stream"); // returns a FileStreamResult
    }    
}

refresh div with jquery

I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this

_x000D_
_x000D_
$("#panel").toggle().toggle();
_x000D_
_x000D_
_x000D_

it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.

How to SELECT based on value of another SELECT

If you want to SELECT based on the value of another SELECT, then you probably want a "subselect":

http://beginner-sql-tutorial.com/sql-subquery.htm

For example, (from the link above):

  1. You want the first and last names from table "student_details" ...

  2. But you only want this information for those students in "science" class:

     SELECT id, first_name
     FROM student_details
     WHERE first_name IN (SELECT first_name
     FROM student_details
     WHERE subject= 'Science'); 
    

Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...

IMHO...

How to select bottom most rows?

"Tom H" answer above is correct and it works for me in getting Bottom 5 rows.

SELECT [KeyCol1], [KeyCol2], [Col3]
FROM
(SELECT TOP 5 [KeyCol1],
       [KeyCol2],
       [Col3]
  FROM [dbo].[table_name]
  ORDER BY [KeyCol1],[KeyCol2] DESC) SOME_ALAIS
  ORDER BY [KeyCol1],[KeyCol2] ASC

Thanks.

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

For Single valued associations, i.e.-One-to-One and Many-to-One:-
Default Lazy=proxy
Proxy lazy loading:- This implies a proxy object of your associated entity is loaded. This means that only the id connecting the two entities is loaded for the proxy object of associated entity.
Eg: A and B are two entities with Many to one association. ie: There may be multiple A's for every B. Every object of A will contain a reference of B.
`

public class A{
    int aid;
    //some other A parameters;
    B b;
}
public class B{
    int bid;
     //some other B parameters;
}

`
The relation A will contain columns(aid,bid,...other columns of entity A).
The relation B will contain columns(bid,...other columns of entity B)

Proxy implies when A is fetched, only id is fetched for B and stored into a proxy object of B which contains only id. Proxy object of B is a an object of a proxy-class which is a subclass of B with only minimal fields. Since bid is already part of relation A, it is not necessary to fire a query to get bid from the relation B. Other attributes of entity B are lazily loaded only when a field other than bid is accessed.

For Collections, i.e.-Many-to-Many and One-to-Many:-
Default Lazy=true


Please also note that the fetch strategy(select,join etc) can override lazy. ie: If lazy='true' and fetch='join', fetching of A will also fetch B or Bs(In case of collections). You can get the reason if you think about it.
Default fetch for single valued association is "join".
Default fetch for collections is "select". Please verify the last two lines. I have deduced that logically.

Can't import database through phpmyadmin file size too large

Use command line :

mysql.exe -u USERNAME -p PASSWORD DATABASENAME < MYDATABASE.sql

where MYDATABASE.sql is your sql file.

Removing Data From ElasticSearch

If you ever need to delete all the indexes, this may come in handy:

curl -X DELETE 'http://localhost:9200/_all'

Powershell:

Invoke-WebRequest -method DELETE http://localhost:9200/_all

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

You simply need to upgrade your Tomcat version, to Tomcat 8.0.xx. Java8 <-> Tomcat8

This is the configuration that I have been using and it has always worked out well JDK version Tomcat versions

Convert Rows to columns using 'Pivot' in SQL Server

I'm writing an sp that could be useful for this purpose, basically this sp pivot any table and return a new table pivoted or return just the set of data, this is the way to execute it:

Exec dbo.rs_pivot_table @schema=dbo,@table=table_name,@column=column_to_pivot,@agg='sum([column_to_agg]),avg([another_column_to_agg]),',
        @sel_cols='column_to_select1,column_to_select2,column_to_select1',@new_table=returned_table_pivoted;

please note that in the parameter @agg the column names must be with '[' and the parameter must end with a comma ','

SP

Create Procedure [dbo].[rs_pivot_table]
    @schema sysname=dbo,
    @table sysname,
    @column sysname,
    @agg nvarchar(max),
    @sel_cols varchar(max),
    @new_table sysname,
    @add_to_col_name sysname=null
As
--Exec dbo.rs_pivot_table dbo,##TEMPORAL1,tip_liq,'sum([val_liq]),sum([can_liq]),','cod_emp,cod_con,tip_liq',##TEMPORAL1PVT,'hola';
Begin

    Declare @query varchar(max)='';
    Declare @aggDet varchar(100);
    Declare @opp_agg varchar(5);
    Declare @col_agg varchar(100);
    Declare @pivot_col sysname;
    Declare @query_col_pvt varchar(max)='';
    Declare @full_query_pivot varchar(max)='';
    Declare @ind_tmpTbl int; --Indicador de tabla temporal 1=tabla temporal global 0=Tabla fisica

    Create Table #pvt_column(
        pivot_col varchar(100)
    );

    Declare @column_agg table(
        opp_agg varchar(5),
        col_agg varchar(100)
    );

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@table) AND type in (N'U'))
        Set @ind_tmpTbl=0;
    ELSE IF OBJECT_ID('tempdb..'+ltrim(rtrim(@table))) IS NOT NULL
        Set @ind_tmpTbl=1;

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@new_table) AND type in (N'U')) OR 
        OBJECT_ID('tempdb..'+ltrim(rtrim(@new_table))) IS NOT NULL
    Begin
        Set @query='DROP TABLE '+@new_table+'';
        Exec (@query);
    End;

    Select @query='Select distinct '+@column+' From '+(case when @ind_tmpTbl=1 then 'tempdb.' else '' end)+@schema+'.'+@table+' where '+@column+' is not null;';
    Print @query;

    Insert into #pvt_column(pivot_col)
    Exec (@query)

    While charindex(',',@agg,1)>0
    Begin
        Select @aggDet=Substring(@agg,1,charindex(',',@agg,1)-1);

        Insert Into @column_agg(opp_agg,col_agg)
        Values(substring(@aggDet,1,charindex('(',@aggDet,1)-1),ltrim(rtrim(replace(substring(@aggDet,charindex('[',@aggDet,1),charindex(']',@aggDet,1)-4),')',''))));

        Set @agg=Substring(@agg,charindex(',',@agg,1)+1,len(@agg))

    End

    Declare cur_agg cursor read_only forward_only local static for
    Select 
        opp_agg,col_agg
    from @column_agg;

    Open cur_agg;

    Fetch Next From cur_agg
    Into @opp_agg,@col_agg;

    While @@fetch_status=0
    Begin

        Declare cur_col cursor read_only forward_only local static for
        Select 
            pivot_col 
        From #pvt_column;

        Open cur_col;

        Fetch Next From cur_col
        Into @pivot_col;

        While @@fetch_status=0
        Begin

            Select @query_col_pvt='isnull('+@opp_agg+'(case when '+@column+'='+quotename(@pivot_col,char(39))+' then '+@col_agg+
            ' else null end),0) as ['+lower(Replace(Replace(@opp_agg+'_'+convert(varchar(100),@pivot_col)+'_'+replace(replace(@col_agg,'[',''),']',''),' ',''),'&',''))+
                (case when @add_to_col_name is null then space(0) else '_'+isnull(ltrim(rtrim(@add_to_col_name)),'') end)+']'
            print @query_col_pvt
            Select @full_query_pivot=@full_query_pivot+@query_col_pvt+', '

            --print @full_query_pivot

            Fetch Next From cur_col
            Into @pivot_col;        

        End     

        Close cur_col;
        Deallocate cur_col;

        Fetch Next From cur_agg
        Into @opp_agg,@col_agg; 
    End

    Close cur_agg;
    Deallocate cur_agg;

    Select @full_query_pivot=substring(@full_query_pivot,1,len(@full_query_pivot)-1);

    Select @query='Select '+@sel_cols+','+@full_query_pivot+' into '+@new_table+' From '+(case when @ind_tmpTbl=1 then 'tempdb.' else '' end)+
    @schema+'.'+@table+' Group by '+@sel_cols+';';

    print @query;
    Exec (@query);

End;
GO

This is an example of execution:

Exec dbo.rs_pivot_table @schema=dbo,@table=##TEMPORAL1,@column=tip_liq,@agg='sum([val_liq]),avg([can_liq]),',@sel_cols='cod_emp,cod_con,tip_liq',@new_table=##TEMPORAL1PVT;

then Select * From ##TEMPORAL1PVT would return:

enter image description here

Android - Spacing between CheckBox and text

Simple solution, add this line in the CheckBox properties, replace 10dp with your desired spacing value

android:paddingLeft="10dp"

Checkbox value true/false

If I understand the question, you want to change the value of the checkbox depending if it is checked or not.

Here is one solution:

_x000D_
_x000D_
$('#checkbox-value').text($('#checkbox1').val());_x000D_
_x000D_
$("#checkbox1").on('change', function() {_x000D_
  if ($(this).is(':checked')) {_x000D_
    $(this).attr('value', 'true');_x000D_
  } else {_x000D_
    $(this).attr('value', 'false');_x000D_
  }_x000D_
  _x000D_
  $('#checkbox-value').text($('#checkbox1').val());_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false">_x000D_
_x000D_
<div id="checkbox-value"></div>
_x000D_
_x000D_
_x000D_

How can I copy a file on Unix using C?

sprintf( cmd, "/bin/cp -p \'%s\' \'%s\'", old, new);

system( cmd);

Add some error checks...

Otherwise, open both and loop on read/write, but probably not what you want.

...

UPDATE to address valid security concerns:

Rather than using "system()", do a fork/wait, and call execv() or execl() in the child.

execl( "/bin/cp", "-p", old, new);

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

this worked for me:

ProxyRequests     Off
ProxyPreserveHost On
RewriteEngine On

<Proxy http://localhost:8123>
Order deny,allow
Allow from all
</Proxy>

ProxyPass         /node  http://localhost:8123  
ProxyPassReverse  /node  http://localhost:8123

javascript: using a condition in switch case

See dmp's answer below. I'd delete this answer if I could, but it was accepted so this is the next best thing :)

You can't. JS Interpreters require you to compare against the switch statement (e.g. there is no "case when" statement). If you really want to do this, you can just make if(){ .. } else if(){ .. } blocks.

How to create global variables accessible in all views using Express / Node.JS?

You can do this by adding them to the locals object in a general middleware.

app.use(function (req, res, next) {
   res.locals = {
     siteTitle: "My Website's Title",
     pageTitle: "The Home Page",
     author: "Cory Gross",
     description: "My app's description",
   };
   next();
});

Locals is also a function which will extend the locals object rather than overwriting it. So the following works as well

res.locals({
  siteTitle: "My Website's Title",
  pageTitle: "The Home Page",
  author: "Cory Gross",
  description: "My app's description",
});

Full example

var app = express();

var middleware = {

    render: function (view) {
        return function (req, res, next) {
            res.render(view);
        }
    },

    globalLocals: function (req, res, next) {
        res.locals({ 
            siteTitle: "My Website's Title",
            pageTitle: "The Root Splash Page",
            author: "Cory Gross",
            description: "My app's description",
        });
        next();
    },

    index: function (req, res, next) {
        res.locals({
            indexSpecificData: someData
        });
        next();
    }

};


app.use(middleware.globalLocals);
app.get('/', middleware.index, middleware.render('home'));
app.get('/products', middleware.products, middleware.render('products'));

I also added a generic render middleware. This way you don't have to add res.render to each route which means you have better code reuse. Once you go down the reusable middleware route you'll notice you will have lots of building blocks which will speed up development tremendously.

Is it possible to use argsort in descending order?

An elegant way could be as follows -

ids = np.flip(np.argsort(avgDists))

This will give you indices of elements sorted in descending order. Now you can use regular slicing...

top_n = ids[:n]

insert datetime value in sql database with c#

using (SqlConnection conn = new SqlConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = "INSERT INTO <table> (<date_column>) VALUES ('2010-01-01 12:00')";
    cmd.ExecuteNonQuery();
}

It's been awhile since I wrote this stuff, so this may not be perfect. but the general idea is there.

WARNING: this is unsanitized. You should use parameters to avoid injection attacks.

EDIT: Since Jon insists.

Spring CORS No 'Access-Control-Allow-Origin' header is present

public class TrackingSystemApplication {

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

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:4200").allowedMethods("PUT", "DELETE",
                        "GET", "POST");
            }
        };
    }

}

Converting integer to string in Python

If you need unary numeral system, you can convert an integer like this:

>> n = 6
>> '1' * n
'111111'

If you need a support of negative ints you can just write like that:

>> n = -6
>> '1' * n if n >= 0 else '-' + '1' * (-n)
'-111111'

Zero is special case which takes an empty string in this case, which is correct.

>> n = 0
>> '1' * n if n >= 0 else '-' + '1' * (-n)
''

CSS3 background image transition

I was struggling with this for a bit, I first used a stack of images on top of each other and every three seconds, I was trying to animate to the next image in the stack and throwing the current image to the bottom of the stack. At the same time I was using animations as shown above. I couldn't get it to work for the life of me.

You can use this library which allows for **dynamically-resized, slideshow-capable background image ** using jquery-backstretch.

https://github.com/jquery-backstretch/jquery-backstretch

Dictionary with list of strings as value

Just create a new array in your dictionary

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));

OnclientClick and OnClick is not working at the same time?

What if you don't immediately set the button to disabled, but delay that through setTimeout? Your 'disable' function would return and the submit would continue.

Remove spacing between table cells and rows

I had a similar problem and I solved it by (inline)styling the td element as follows :

<td style="display: block;"> 

This will work although its not the best practice. In my case I was working on a old template that had been styled using HTML tables.

LINQ: Select an object and change some properties without creating a new object

If you want to update items with a Where clause, using a .Where(...) will truncate your results if you do:

mylist = mylist.Where(n => n.Id == ID).Select(n => { n.Property = ""; return n; }).ToList();

You can do updates to specific item(s) in the list like so:

mylist = mylist.Select(n => { if (n.Id == ID) { n.Property = ""; } return n; }).ToList();

Always return item even if you don't make any changes. This way it will be kept in the list.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:

xhr.send(null);
if (xhr.status == 204) 
    Reload();
else 
    dropdown.innerHTML = xhr.responseText;

Here is the Reload() function:

function Reload() {
    var oForm = document.createElement("form");
    document.body.appendChild(oForm);
    oForm.submit();
    }

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

overlay opaque div over youtube iframe

Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/

Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.

EDIT: Youtube renders the object and embed with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:


a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements

b) Find a way for youtube to specify those.


Finding the layers and layer sizes for each Docker image

They have a very good answer here: https://stackoverflow.com/a/32455275/165865

Just run below images:

docker run --rm -v /var/run/docker.sock:/var/run/docker.sock nate/dockviz images -t

How to scroll to top of a div using jQuery?

Use the following function

window.scrollTo(xpos, ypos)

Here xpos is Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels

ypos is also Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

How to set input type date's default value to today?

Since there's no default method of setting the value to today's date, I would say this should be dependent upon it's application. If you're looking to maximize your audience's exposure to the date picker, then use a server-side script (PHP, ASP, etc.) to set the default value.

However, if it's for the administration console of the CMS, and you know that the user will always have JS on or your site trusted, then you can safely use JS to fill the default value, as per jlbruno.

How to filter a data frame

You are missing a comma in your statement.

Try this:

data[data[, "Var1"]>10, ]

Or:

data[data$Var1>10, ]

Or:

subset(data, Var1>10)

As an example, try it on the built-in dataset, mtcars

data(mtcars)

mtcars[mtcars[, "mpg"]>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2


mtcars[mtcars$mpg>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

subset(mtcars, mpg>25)

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

Is __init__.py not required for packages in Python 3.3+

If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.

Packages are only recognized if they include an __init__.py file

UPD: If you want to use implicit namespace packages without __init__.py you just have to use find_namespace_packages() instead

Docs

How to fix ReferenceError: primordials is not defined in node

I was also getting error on Node 12/13 with Gulp 3, moving to Node 11 worked.

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

JPA Query.getResultList() - use in a generic way

The above query returns the list of Object[]. So if you want to get the u.name and s.something from the list then you need to iterate and cast that values for the corresponding classes.

PHP Fatal error: Using $this when not in object context

Just use the Class method using this foobar->foobarfunc();

catching stdout in realtime from subprocess

You cannot get stdout to print unbuffered to a pipe (unless you can rewrite the program that prints to stdout), so here is my solution:

Redirect stdout to sterr, which is not buffered. '<cmd> 1>&2' should do it. Open the process as follows: myproc = subprocess.Popen('<cmd> 1>&2', stderr=subprocess.PIPE)
You cannot distinguish from stdout or stderr, but you get all output immediately.

Hope this helps anyone tackling this problem.

Add an index (numeric ID) column to large data frame

You can add a sequence of numbers very easily with

data$ID <- seq.int(nrow(data))

If you are already using library(tidyverse), you can use

data <- tibble::rowid_to_column(data, "ID")

How to format a number 0..9 to display with 2 digits (it's NOT a date)

If you need to print the number you can use printf

System.out.printf("%02d", num);

You can use

String.format("%02d", num);

or

(num < 10 ? "0" : "") + num;

or

(""+(100+num)).substring(1);

Calculating the sum of two variables in a batch script

@ECHO OFF
ECHO Welcome to my calculator!
ECHO What is the number you want to insert to find the sum?
SET /P Num1=
ECHO What is the second number? 
SET /P Num2=
SET /A Ans=%Num1%+%Num2%
ECHO The sum is: %Ans%
PAUSE>NUL

Session 'app': Error Installing APK

Try to remove the .idea folder and .gradle folder, then click Sync Project with Gradle Files, when the process finished, try to run app again.

Hope it works.

How do I redirect users after submit button click?

It would be

window.location="login.php";

Git: can't undo local changes (error: path ... is unmerged)

You did it the wrong way around. You are meant to reset first, to unstage the file, then checkout, to revert local changes.

Try this:

$ git reset foo/bar.txt
$ git checkout foo/bar.txt

jQuery: value.attr is not a function

You can also use jQuery('.class-name').attr("href"), in my case it works better.

Here more information: "jQuery(...)" instead of "$(...)"

Unstaged changes left after git reset --hard

Git won't reset files that aren't on repository. So, you can:

$ git add .
$ git reset --hard

This will stage all changes, which will cause Git to be aware of those files, and then reset them.

If this does not work, you can try to stash and drop your changes:

$ git stash
$ git stash drop

How to make an HTTP request + basic auth in Swift

my solution works as follows:

import UIKit


class LoginViewController: UIViewController, NSURLConnectionDataDelegate {

  @IBOutlet var usernameTextField: UITextField
  @IBOutlet var passwordTextField: UITextField

  @IBAction func login(sender: AnyObject) {
    var url = NSURL(string: "YOUR_URL")
    var request = NSURLRequest(URL: url)
    var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)

  }

  func connection(connection:NSURLConnection!, willSendRequestForAuthenticationChallenge challenge:NSURLAuthenticationChallenge!) {

    if challenge.previousFailureCount > 1 {

    } else {
        let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
        challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)

    }

}

  func connection(connection:NSURLConnection!, didReceiveResponse response: NSURLResponse) {
    let status = (response as NSHTTPURLResponse).statusCode
    println("status code is \(status)")
    // 200? Yeah authentication was successful
  }


  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

  }  
}

You can use this class as the implementation of a ViewController. Connect your fields to the IBOutlet annotated vars and your Button to the IBAction annotated function.

Explanation: In function login you create your request with NSURL, NSURLRequest and NSURLConnection. Essential here is the delegate which references to this class (self). For receiving the delegates calls you need to

  • Add the protocol NSURLConnectionDataDelegate to the class
  • Implement the protocols' function "connection:willSendRequestForAuthenticationChallenge" This is used for adding the credentials to the request
  • Implement the protocols' function "connection:didReceiveResponse" This will check the http response status code

Can CSS detect the number of children an element has?

If you are going to do it in pure CSS (using scss) but you have different elements/classes inside the same parent class you can use this version!!

  &:first-of-type:nth-last-of-type(1) {
    max-width: 100%;
  }

  @for $i from 2 through 10 {
    &:first-of-type:nth-last-of-type(#{$i}),
    &:first-of-type:nth-last-of-type(#{$i}) ~ & {
      max-width: (100% / #{$i});
    }
  }

Save current directory in variable using Bash?

One more variant:

export PATH=$PATH:\`pwd`:/foo/bar

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

How to iterate through a String

Using Guava (r07) you can do this:

for(char c : Lists.charactersOf(someString)) { ... }

This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf returns a view of the string as a List.

Ring Buffer in Java

A very interesting project is disruptor. It has a ringbuffer and is used from what I know in financial applications.

See here: code of ringbuffer

I checked both Guava's EvictingQueue and ArrayDeque.

ArrayDeque does not limit growth if it's full it will double size and hence is not precisely acting like a ringbuffer.

EvictingQueue does what it promises but internally uses a Deque to store things and just bounds memory.

Hence, if you care about memory being bounded ArrayDeque is not fullfilling your promise. If you care about object count EvictingQueue uses internal composition (bigger object size).

A simple and memory efficient one can be stolen from jmonkeyengine. verbatim copy

import java.util.Iterator;
import java.util.NoSuchElementException;

public class RingBuffer<T> implements Iterable<T> {

  private T[] buffer;          // queue elements
  private int count = 0;          // number of elements on queue
  private int indexOut = 0;       // index of first element of queue
  private int indexIn = 0;       // index of next available slot

  // cast needed since no generic array creation in Java
  public RingBuffer(int capacity) {
    buffer = (T[]) new Object[capacity];
  }

  public boolean isEmpty() {
    return count == 0;
  }

  public int size() {
    return count;
  }

  public void push(T item) {
    if (count == buffer.length) {
        throw new RuntimeException("Ring buffer overflow");
    }
    buffer[indexIn] = item;
    indexIn = (indexIn + 1) % buffer.length;     // wrap-around
    count++;
  }

  public T pop() {
    if (isEmpty()) {
        throw new RuntimeException("Ring buffer underflow");
    }
    T item = buffer[indexOut];
    buffer[indexOut] = null;                  // to help with garbage collection
    count--;
    indexOut = (indexOut + 1) % buffer.length; // wrap-around
    return item;
  }

  public Iterator<T> iterator() {
    return new RingBufferIterator();
  }

  // an iterator, doesn't implement remove() since it's optional
  private class RingBufferIterator implements Iterator<T> {

    private int i = 0;

    public boolean hasNext() {
        return i < count;
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }

    public T next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return buffer[i++];
    }
  }
}

AngularJS : Initialize service with asynchronous data

Based on Martin Atkins' solution, here is a complete, concise pure-Angular solution:

(function() {
  var initInjector = angular.injector(['ng']);
  var $http = initInjector.get('$http');
  $http.get('/config.json').then(
    function (response) {
      angular.module('config', []).constant('CONFIG', response.data);

      angular.element(document).ready(function() {
          angular.bootstrap(document, ['myApp']);
        });
    }
  );
})();

This solution uses a self-executing anonymous function to get the $http service, request the config, and inject it into a constant called CONFIG when it becomes available.

Once completely, we wait until the document is ready and then bootstrap the Angular app.

This is a slight enhancement over Martin's solution, which deferred fetching the config until after the document is ready. As far as I know, there is no reason to delay the $http call for that.

Unit Testing

Note: I have discovered this solution does not work well when unit-testing when the code is included in your app.js file. The reason for this is that the above code runs immediately when the JS file is loaded. This means the test framework (Jasmine in my case) doesn't have a chance to provide a mock implementation of $http.

My solution, which I'm not completely satisfied with, was to move this code to our index.html file, so the Grunt/Karma/Jasmine unit test infrastructure does not see it.

How to get MAC address of your machine using a C program?

netlink socket is possible

man netlink(7) netlink(3) rtnetlink(7) rtnetlink(3)

#include <assert.h>
#include <stdio.h>
#include <linux/if.h>
#include <linux/rtnetlink.h>
#include <unistd.h>

#define SZ 8192

int main(){

  // Send
  typedef struct {
    struct nlmsghdr nh;
    struct ifinfomsg ifi;
  } Req_getlink;
  assert(NLMSG_LENGTH(sizeof(struct ifinfomsg))==sizeof(Req_getlink));
  int fd=-1;
  fd=socket(AF_NETLINK,SOCK_RAW,NETLINK_ROUTE);
  assert(0==bind(fd,(struct sockaddr*)(&(struct sockaddr_nl){
    .nl_family=AF_NETLINK,
    .nl_pad=0,
    .nl_pid=getpid(),
    .nl_groups=0
  }),sizeof(struct sockaddr_nl)));
  assert(sizeof(Req_getlink)==send(fd,&(Req_getlink){
    .nh={
      .nlmsg_len=NLMSG_LENGTH(sizeof(struct ifinfomsg)),
      .nlmsg_type=RTM_GETLINK,
      .nlmsg_flags=NLM_F_REQUEST|NLM_F_ROOT,
      .nlmsg_seq=0,
      .nlmsg_pid=0
    },
    .ifi={
      .ifi_family=AF_UNSPEC,
      // .ifi_family=AF_INET,
      .ifi_type=0,
      .ifi_index=0,
      .ifi_flags=0,
      .ifi_change=0,
    }
  },sizeof(Req_getlink),0));

  // Receive
  char recvbuf[SZ]={};
  int len=0;
  for(char *p=recvbuf;;){
    const int seglen=recv(fd,p,sizeof(recvbuf)-len,0);
    assert(seglen>=1);
    len += seglen;
    if(((struct nlmsghdr*)p)->nlmsg_type==NLMSG_DONE||((struct nlmsghdr*)p)->nlmsg_type==NLMSG_ERROR)
      break;
    p += seglen;
  }

  struct nlmsghdr *nh=(struct nlmsghdr*)recvbuf;
  for(;NLMSG_OK(nh,len);nh=NLMSG_NEXT(nh,len)){
    if(nh->nlmsg_type==NLMSG_DONE)
      break;

    struct ifinfomsg *ifm=(struct ifinfomsg*)NLMSG_DATA(nh);

    printf("#%d ",ifm->ifi_index);
    #ifdef _NET_IF_H
    #pragma GCC error "include <linux/if.h> instead of <net/if.h>"
    #endif

    // Part 3 rtattr
    struct rtattr *rta=IFLA_RTA(ifm); // /usr/include/linux/if_link.h
    int rtl=RTM_PAYLOAD(nh);

    for(;RTA_OK(rta,rtl);rta=RTA_NEXT(rta,rtl))switch(rta->rta_type){
    case IFLA_IFNAME:printf("%s ",(const char*)RTA_DATA(rta));break;
    case IFLA_ADDRESS:
      printf("hwaddr ");
      for(int i=0;i<5;++i)
        printf("%02X:",*((unsigned char*)RTA_DATA(rta)+i));
      printf("%02X ",*((unsigned char*)RTA_DATA(rta)+5));
      break;
    case IFLA_BROADCAST:
      printf("bcast ");
      for(int i=0;i<5;++i)
        printf("%02X:",*((unsigned char*)RTA_DATA(rta)+i));
      printf("%02X ",*((unsigned char*)RTA_DATA(rta)+5));
      break;
    case IFLA_PERM_ADDRESS:
      printf("perm ");
      for(int i=0;i<5;++i)
        printf("%02X:",*((unsigned char*)RTA_DATA(rta)+i));
      printf("%02X ",*((unsigned char*)RTA_DATA(rta)+5));
      break;
    }

    printf("\n");

  }

  close(fd);
  fd=-1;
  return 0;

}

Example

#1 lo hwaddr 00:00:00:00:00:00 bcast 00:00:00:00:00:00
#2 eth0 hwaddr 57:da:52:45:5b:1a bcast ff:ff:ff:ff:ff:ff perm 57:da:52:45:5b:1a
#3 wlan0 hwaddr 3c:7f:46:47:58:c2 bcast ff:ff:ff:ff:ff:ff perm 3c:7f:46:47:58:c2

Printing an array in C++?

There are declared arrays and arrays that are not declared, but otherwise created, particularly using new:

int *p = new int[3];

That array with 3 elements is created dynamically (and that 3 could have been calculated at runtime, too), and a pointer to it which has the size erased from its type is assigned to p. You cannot get the size anymore to print that array. A function that only receives the pointer to it can thus not print that array.

Printing declared arrays is easy. You can use sizeof to get their size and pass that size along to the function including a pointer to that array's elements. But you can also create a template that accepts the array, and deduces its size from its declared type:

template<typename Type, int Size>
void print(Type const(& array)[Size]) {
  for(int i=0; i<Size; i++)
    std::cout << array[i] << std::endl;
}

The problem with this is that it won't accept pointers (obviously). The easiest solution, I think, is to use std::vector. It is a dynamic, resizable "array" (with the semantics you would expect from a real one), which has a size member function:

void print(std::vector<int> const &v) {
  std::vector<int>::size_type i;
  for(i = 0; i<v.size(); i++)
    std::cout << v[i] << std::endl;
}

You can, of course, also make this a template to accept vectors of other types.

How can I color Python logging output?

Look at the following solution. The stream handler should be the thing doing the colouring, then you have the option of colouring words rather than just the whole line (with the Formatter).

http://plumberjack.blogspot.com/2010/12/colorizing-logging-output-in-terminals.html

round() doesn't seem to be rounding properly

I am doing:

int(round( x , 0))

In this case, we first round properly at the unit level, then we convert to integer to avoid printing a float.

so

>>> int(round(5.59,0))
6

I think this answer works better than formating the string, and it also makes more sens to me to use the round function.

Java SSLException: hostname in certificate didn't match

Updating the java version from 1.8.0_40 to 1.8.0_181 resolved the issue.

How to use jQuery to get the current value of a file input field

You need to use val rather than value.

$("#fileinput").val();

How do I update pip itself from inside my virtual environment?

pip is just a PyPI package like any other; you could use it to upgrade itself the same way you would upgrade any package:

pip install --upgrade pip

On Windows the recommended command is:

python -m pip install --upgrade pip

How to use the addr2line command in Linux?

You can also use gdb instead of addr2line to examine memory address. Load executable file in gdb and print the name of a symbol which is stored at the address. 16 Examining the Symbol Table.

(gdb) info symbol 0x4005BDC 

How can I check if some text exist or not in the page using Selenium?

With XPath, it's not that hard. Simply search for all elements containing the given text:

List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assert.assertTrue("Text not found!", list.size() > 0);

The official documentation is not very supportive with tasks like this, but it is the basic tool nonetheless.

The JavaDocs are greater, but it takes some time to get through everything useful and unuseful.

To learn XPath, just follow the internet. The spec is also a surprisingly good read.


EDIT:

Or, if you don't want your Implicit Wait to make the above code wait for the text to appear, you can do something in the way of this:

String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

Just put the

Response.End();

within a finally block instead of within the try block.

This has worked for me!!!.

I had the following problematic (with the Exception) code structure

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);
   Response.End();

   return;

 } 

 some_more_code...

 Reponse.Write(...);
 Response.End();

}
catch(Exception){
}
finally{}

and it throws the exception. I suspect the Exception is thrown where there is code / work to execute after response.End(); . In my case the extra code was just the return itself.

When I just moved the response.End(); to the finally block (and left the return in its place - which causes skipping the rest of code in the try block and jumping to the finally block (not just exiting the containing function) ) the Exception ceased to take place.

The following works OK:

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);

   return;

 } 

 some_more_code...

 Reponse.Write(...);

}
catch(Exception){
}
finally{
    Response.End();
}

Jquery Ajax Loading image

Its a bit late but if you don't want to use a div specifically, I usually do it like this...

var ajax_image = "<img src='/images/Loading.gif' alt='Loading...' />";
$('#ReplaceDiv').html(ajax_image);

ReplaceDiv is the div that the Ajax inserts too. So when it arrives, the image is replaced.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

Edit elasticsearch.yml and add the following line

http.host: 0.0.0.0

network.host: 0.0.0.0 didn't work for

Get last field using awk substr

It should be a comment to the basename answer but I haven't enough point.

If you do not use double quotes, basename will not work with path where there is space character:

$ basename /home/foo/bar foo/bar.png
bar

ok with quotes " "

$ basename "/home/foo/bar foo/bar.png"
bar.png

file example

$ cat a
/home/parent/child 1/child 2/child 3/filename1
/home/parent/child 1/child2/filename2
/home/parent/child1/filename3

$ while read b ; do basename "$b" ; done < a
filename1
filename2
filename3

Javascript parse float is ignoring the decimals after my comma

It is better to use this syntax to replace all the commas in a case of a million 1,234,567

var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, ""); 
var number = parseFloat(string);
console.log(number)

The g means to remove all commas.

Check the Jsfiddle demo here.

How can I shrink the drawable on a button?

Use a ScaleDrawable as Abhinav suggested.

The problem is that the drawable doesn't show then - it's some sort of bug in ScaleDrawables. you'll need to change the "level" programmatically. This should work for every button:

// Fix level of existing drawables
Drawable[] drawables = myButton.getCompoundDrawables();
for (Drawable d : drawables) if (d != null && d instanceof ScaleDrawable) d.setLevel(1);
myButton.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]);

When would you use the Builder Pattern?

You use it when you have lots of options to deal with. Think about things like jmock:

m.expects(once())
    .method("testMethod")
    .with(eq(1), eq(2))
    .returns("someResponse");

It feels a lot more natural and is...possible.

There's also xml building, string building and many other things. Imagine if java.util.Map had put as a builder. You could do stuff like this:

Map<String, Integer> m = new HashMap<String, Integer>()
    .put("a", 1)
    .put("b", 2)
    .put("c", 3);

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

The onunload event is not called in all browsers. Worse, you cannot check the return value of onbeforeunload event. That prevents us from actually preforming a logout function.

However, you can hack around this.

Call logout first thing in the onbeforeunload event. then prompt the user. If the user cancels their logout, automatically login them back in, by using the onfocus event. Kinda backwards, but I think it should work.

'use strict';

var reconnect = false;

window.onfocus = function () {
  if (reconnect) {
    reconnect = false;
    alert("Perform an auto-login here!");
  }
};

window.onbeforeunload = function () {
  //logout();
  var msg = "Are you sure you want to leave?";
  reconnect = true;
  return msg;
};

event.preventDefault() vs. return false

return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object.

e.preventDefault() will prevent the default event from occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

Source: John Resig

Any benefit to using event.preventDefault() over "return false" to cancel out an href click?

How to send 500 Internal Server Error error from a PHP script

You can just put:

header("HTTP/1.0 500 Internal Server Error");

inside your conditions like:

if (that happened) {
    header("HTTP/1.0 500 Internal Server Error");
}

As for the database query, you can just do that like this:

$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");

You should remember that you have to put this code before any html tag (or output).

Call a function from another file?

in my case i named my file helper.scrap.py and couldn't make it work until i changed to helper.py

I want to calculate the distance between two points in Java

Based on the @trashgod's comment, this is the simpliest way to calculate >distance:

double distance = Math.hypot(x1-x2, y1-y2); From documentation of Math.hypot:

Returns: sqrt(x²+ y²) without intermediate overflow or underflow.

Bob

Below Bob's approved comment he said he couldn't explain what the

Math.hypot(x1-x2, y1-y2);

did. To explain a triangle has three sides. With two points you can find the length of those points based on the x,y of each. Xa=0, Ya=0 If thinking in Cartesian coordinates that is (0,0) and then Xb=5, Yb=9 Again, cartesian coordinates is (5,9). So if you were to plot those on a grid, the distance from from x to another x assuming they are on the same y axis is +5. and the distance along the Y axis from one to another assuming they are on the same x-axis is +9. (think number line) Thus one side of the triangle's length is 5, another side is 9. A hypotenuse is

 (x^2) + (y^2) = Hypotenuse^2

which is the length of the remaining side of a triangle. Thus being quite the same as a standard distance formula where

 Sqrt of (x1-x2)^2 + (y1-y2)^2 = distance 

because if you do away with the sqrt on the lefthand side of the operation and instead make distance^2 then you still have to get the sqrt from the distance. So the distance formula is the Pythagorean theorem but in a way that teachers can call it something different to confuse people.

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

C# does not support this. Hejlsberg has described the reasons for not implementing the feature in an interview with Bruce Eckel:

And it's not clear that the added complexity is worth the small yield that you get. If something you want to do is not directly supported in the constraint system, you can do it with a factory pattern. You could have a Matrix<T>, for example, and in that Matrix you would like to define a dot product method. That of course that means you ultimately need to understand how to multiply two Ts, but you can't say that as a constraint, at least not if T is int, double, or float. But what you could do is have your Matrix take as an argument a Calculator<T>, and in Calculator<T>, have a method called multiply. You go implement that and you pass it to the Matrix.

However, this leads to fairly convoluted code, where the user has to supply their own Calculator<T> implementation, for each T that they want to use. As long as it doesn’t have to be extensible, i.e. if you just want to support a fixed number of types, such as int and double, you can get away with a relatively simple interface:

var mat = new Matrix<int>(w, h);

(Minimal implementation in a GitHub Gist.)

However, as soon as you want the user to be able to supply their own, custom types, you need to open up this implementation so that the user can supply their own Calculator instances. For instance, to instantiate a matrix that uses a custom decimal floating point implementation, DFP, you’d have to write this code:

var mat = new Matrix<DFP>(DfpCalculator.Instance, w, h);

… and implement all the members for DfpCalculator : ICalculator<DFP>.

An alternative, which unfortunately shares the same limitations, is to work with policy classes, as discussed in Sergey Shandar’s answer.

Need to make a clickable <div> button

There are two solutions posted on that page. The one with lower votes I would recommend if possible.

If you are using HTML5 then it is perfectly valid to put a div inside of a. As long as the div doesn't also contain some other specific elements like other link tags.

<a href="Music.html">
  <div id="music" class="nav">
    Music I Like
  </div>
</a>

The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index at all from that example.

div { position: relative; }
.hyperspan {
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
}

<div id="music" class="nav">Music I Like 
    <a href="http://www.google.com"> 
        <span class="hyperspan"></span>
    </a>   
</div>

http://jsfiddle.net/rBKXM/9

When you give absolute positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative to the parent div you tell the span to only be as big as that.

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

To understand pid files, refer this DOC

Some times there are certain applications that require additional support of extra plugins and utilities. So it keeps track of these utilities and plugin process running ids using this pid file for reference.

That is why whenever you restart an application all necessary plugins and dependant apps must be restarted since the pid file will become stale.

How to display a list of images in a ListView in Android?

 package studRecords.one;

 import java.util.List;
 import java.util.Vector;

 import android.app.Activity;
 import android.app.ListActivity;
 import android.content.Context;
 import android.content.Intent;
 import android.net.ParseException;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.TextView;



public class studRecords extends ListActivity 
{
static String listName = "";
static String listUsn = "";
static Integer images;
private LayoutInflater layoutx;
private Vector<RowData> listValue;
RowData rd;

static final String[] names = new String[]
{
      "Name (Stud1)", "Name (Stud2)",   
      "Name (Stud3)","Name (Stud4)" 
};

static final String[] usn = new String[]
{
      "1PI08CS016","1PI08CS007","1PI08CS017","1PI08CS047"
};

private Integer[] imgid = 
{
  R.drawable.stud1,R.drawable.stud2,R.drawable.stud3,
  R.drawable.stud4
};

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainlist);

    layoutx = (LayoutInflater) getSystemService(
    Activity.LAYOUT_INFLATER_SERVICE);
    listValue = new Vector<RowData>();
    for(int i=0;i<names.length;i++)
    {
        try
        {
            rd = new RowData(names[i],usn[i],i);
        } 
        catch (ParseException e) 
        {
            e.printStackTrace();
        }
        listValue.add(rd);
    }


   CustomAdapter adapter = new CustomAdapter(this, R.layout.list,
                                     R.id.detail, listValue);
   setListAdapter(adapter);
   getListView().setTextFilterEnabled(true);
}
   public void onListItemClick(ListView parent, View v, int position,long id)
   {            


       listName = names[position];
       listUsn = usn[position];
       images = imgid[position];




       Intent myIntent = new Intent();
       Intent setClassName = myIntent.setClassName("studRecords.one","studRecords.one.nextList");
       startActivity(myIntent);

   }
   private class RowData
   {

       protected String mNames;
       protected String mUsn;
       protected int mId;
       RowData(String title,String detail,int id){
       mId=id;
       mNames = title;
       mUsn = detail;
    }
       @Override
    public String toString()
       {
               return mNames+" "+mUsn+" "+mId;
       }
  }

              private class CustomAdapter extends ArrayAdapter<RowData> 
          {
      public CustomAdapter(Context context, int resource,
      int textViewResourceId, List<RowData> objects)
      {               
            super(context, resource, textViewResourceId, objects);
      }
      @Override
      public View getView(int position, View convertView, ViewGroup parent)
      {   
           ViewHolder holder = null;
           TextView title = null;
           TextView detail = null;
           ImageView i11=null;
           RowData rowData= getItem(position);
           if(null == convertView)
           {
                convertView = layoutx.inflate(R.layout.list, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
           }
         holder = (ViewHolder) convertView.getTag();
         i11=holder.getImage();
         i11.setImageResource(imgid[rowData.mId]);
         title = holder.gettitle();
         title.setText(rowData.mNames);
         detail = holder.getdetail();
         detail.setText(rowData.mUsn);                                                     

         return convertView;
      }

        private class ViewHolder 
        {
            private View mRow;
            private TextView title = null;
            private TextView detail = null;
            private ImageView i11=null; 
            public ViewHolder(View row)
            {
                    mRow = row;
            }
            public TextView gettitle()
            {
                 if(null == title)
                 {
                     title = (TextView) mRow.findViewById(R.id.title);
                 }
                 return title;
            }     
            public TextView getdetail()
            {
                if(null == detail)
                {
                    detail = (TextView) mRow.findViewById(R.id.detail);
                }
                return detail;
            }
            public ImageView getImage()
            {
                    if(null == i11)
                    {
                        i11 = (ImageView) mRow.findViewById(R.id.img);
                    }
                    return i11;
            }   
        }
   } 
 }

//mainlist.xml

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

Blur or dim background when Android PopupWindow active

Another trick is to use 2 popup windows instead of one. The 1st popup window will simply be a dummy view with translucent background which provides the dim effect. The 2nd popup window is your intended popup window.

Sequence while creating pop up windows: Show the dummy pop up window 1st and then the intended popup window.

Sequence while destroying: Dismiss the intended pop up window and then the dummy pop up window.

The best way to link these two is to add an OnDismissListener and override the onDismiss() method of the intended to dimiss the dummy popup window from their.

Code for the dummy popup window:

fadepopup.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:id="@+id/fadePopup"
    android:background="#AA000000">
</LinearLayout>

Show fade popup to dim the background

private PopupWindow dimBackground() {

    LayoutInflater inflater = (LayoutInflater) EPGGRIDActivity.this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View layout = inflater.inflate(R.layout.fadepopup,
            (ViewGroup) findViewById(R.id.fadePopup));
    PopupWindow fadePopup = new PopupWindow(layout, windowWidth, windowHeight, false);
    fadePopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
    return fadePopup;
}

Insert into ... values ( SELECT ... FROM ... )

This is another example using values with select:

INSERT INTO table1(desc, id, email) 
SELECT "Hello World", 3, email FROM table2 WHERE ...

How to set value to form control in Reactive Forms in Angular

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.

patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.

In this scenario, we will want to use patchValue, since we are only updating user and questioning:

this.qService.editQue([params["id"]]).subscribe(res => {
  this.question = res;
  this.editqueForm.patchValue({
    user: this.question.user,
    questioning: this.question.questioning
  });
});

EDIT: If you feel like doing some of ES6's Object Destructuring, you may be interested to do this instead

const { user, questioning } = this.question;

this.editqueForm.patchValue({
  user,
  questioning
});

Ta-dah!

How to properly and completely close/reset a TcpClient connection?

You have to close the stream before closing the connection:

tcpClient.GetStream().Close();
tcpClient.Close();

Closing the client does not close the stream.

How do I make CMake output into a 'bin' dir?

cat CMakeLists.txt
project (hello)
set(CMAKE_BINARY_DIR "/bin")
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
add_executable (hello hello.c)

C# string reference type?

If we have to answer the question: String is a reference type and it behaves as a reference. We pass a parameter that holds a reference to, not the actual string. The problem is in the function:

public static void TestI(string test)
{
    test = "after passing";
}

The parameter test holds a reference to the string but it is a copy. We have two variables pointing to the string. And because any operations with strings actually create a new object, we make our local copy to point to the new string. But the original test variable is not changed.

The suggested solutions to put ref in the function declaration and in the invocation work because we will not pass the value of the test variable but will pass just a reference to it. Thus any changes inside the function will reflect the original variable.

I want to repeat at the end: String is a reference type but since its immutable the line test = "after passing"; actually creates a new object and our copy of the variable test is changed to point to the new string.

Reading Space separated input in python

the_string = raw_input()
name, age = the_string.split()

Android, getting resource ID from string?

Simple method to get resource ID:

public int getDrawableName(Context ctx,String str){
    return ctx.getResources().getIdentifier(str,"drawable",ctx.getPackageName());
}

Add st, nd, rd and th (ordinal) suffix to a number

Old one I made for my stuff...

function convertToOrdinal(number){
    if (number !=1){
        var numberastext = number.ToString();
        var endchar = numberastext.Substring(numberastext.Length - 1);
        if (number>9){
            var secondfromendchar = numberastext.Substring(numberastext.Length - 1);
            secondfromendchar = numberastext.Remove(numberastext.Length - 1);
        }
        var suffix = "th";
        var digit = int.Parse(endchar);
        switch (digit){
            case 3:
                if(secondfromendchar != "1"){
                    suffix = "rd";
                    break;
                }
            case 2:
                if(secondfromendchar != "1"){
                    suffix = "nd";
                    break;
                }
            case 1:
                if(secondfromendchar != "1"){
                    suffix = "st";
                    break;
                }
            default:
                suffix = "th";
                break;
         }
            return number+suffix+" ";
     } else {
            return;
     }
}

How to enable NSZombie in Xcode?

Product > Profile will launch Instruments and then you there should be a "Trace Template" named "Zombies". However this trace template is only available if the current build destination is the simulator - it will not be available if you have the destination set to your iOS device.

Also another thing to note is that there is no actual Zombies instrument in the instrument library. The zombies trace template actually consists of the Allocations instrument with the "Enable NSZombie detection" launch configuration set.

Do sessions really violate RESTfulness?

  1. Sessions are not RESTless
  2. Do you mean that REST service for http-use only or I got smth wrong? Cookie-based session must be used only for own(!) http-based services! (It could be a problem to work with cookie, e.g. from Mobile/Console/Desktop/etc.)
  3. if you provide RESTful service for 3d party developers, never use cookie-based session, use tokens instead to avoid the problems with security.

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

I use it for two reasons:

  1. I can force a refresh of the icon by adding a query parameter for example ?v=2. like this: <link rel="icon" href="/favicon.ico?v=2" type="image/x-icon" />

  2. In case I need to specify the path.

java.lang.OutOfMemoryError: Java heap space

If you want to increase your heap space, you can use java -Xms<initial heap size> -Xmx<maximum heap size> on the command line. By default, the values are based on the JRE version and system configuration. You can find out more about the VM options on the Java website.

However, I would recommend profiling your application to find out why your heap size is being eaten. NetBeans has a very good profiler included with it. I believe it uses the jvisualvm under the hood. With a profiler, you can try to find where many objects are being created, when objects get garbage collected, and more.

Bash script to cd to directory with spaces in pathname

When working under Linux the syntax below is right:

cd ~/My\ Code

However when you're executing your file, use the syntax below:

$ . cdcode

(just '.' and not './')

How to run a C# application at Windows startup?

Code is here (Win form app):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace RunAtStartup
{
    public partial class frmStartup : Form
    {
        // The path to the key where Windows looks for startup applications
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        public frmStartup()
        {
            InitializeComponent();
            // Check to see the current state (running at startup or not)
            if (rkApp.GetValue("MyApp") == null)
            {
                // The value doesn't exist, the application is not set to run at startup
                chkRun.Checked = false;
            }
            else
            {
                // The value exists, the application is set to run at startup
                chkRun.Checked = true;
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (chkRun.Checked)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue("MyApp", Application.ExecutablePath);
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue("MyApp", false);
            }
        }
    }
}

How to properly validate input values with React.JS?

First, here is an example of what I'll mention below: http://jsbin.com/rixido/2/edit

How to properly validate input values with React.JS?

However you want. React is for rendering a data model. The data model should know what is valid or not. You can use Backbone models, JSON data, or anything you want to represent the data and it's error state.

More specifically:

React is generally agnostic towards your data. It's for rendering and dealing with events.

The rules to follow are:

  1. elements can change their state.
  2. they cannot change props.
  3. they can invoke a callback that will change top level props.

How to decide if something should be a prop or a state? Consider this: would ANY part of your app other than the text field want to know that the value entered is bad? If no, make it a state. If yes, it should be a prop.

For example, if you wanted a separate view to render "You have 2 errors on this page." then your error would have to be known to a toplevel data model.

Where should that error live?
If your app was rendering Backbone models (for example), the model itself would have a validate() method and validateError property you could use. You could render other smart objects that could do the same. React also says try to keep props to a minimum and generate the rest of the data. so if you had a validator (e.g. https://github.com/flatiron/revalidator) then your validations could trickle down and any component could check props with it's matching validation to see if it's valid.

It's largely up to you.

(I am personally using Backbone models and rendering them in React. I have a toplevel error alert that I show if there is an error anywhere, describing the error.)

Failed to open/create the internal network Vagrant on Windows10

If the accepted https://stackoverflow.com/a/33733454/8520387 doesn't work for you, then disable other enabled Ethernet Cards. After this try to run your vagrant script again and it will create a new Network Card for you. For me it was #3

enter image description here

Disable browsers vertical and horizontal scrollbars

In case you also need support for Internet Explorer 6, just overflow the html

$("html").css("overflow", "hidden");

and

$("html").css("overflow", "auto");

svn over HTTP proxy

If you're using the standard SVN installation the svn:// connection will work on tcpip port 3690 and so it's basically impossible to connect unless you change your network configuration (you said only Http traffic is allowed) or you install the http module and Apache on the server hosting your SVN server.

Regular Expression - 2 letters and 2 numbers in C#

Just for fun, here's a non-regex (more readable/maintainable for simpletons like me) solution:

string myString = "AB12";

if( Char.IsLetter(myString, 0) && 
    Char.IsLetter(myString, 1) && 
    Char.IsNumber(myString, 2) &&
    Char.IsNumber(myString, 3)) {
    // First two are letters, second two are numbers
}
else {
    // Validation failed
}

EDIT

It seems that I've misunderstood the requirements. The code below will ensure that the first two characters and last two characters of a string validate (so long as the length of the string is > 3)

string myString = "AB12";

if(myString.Length > 3) {    
    if( Char.IsLetter(myString, 0) && 
        Char.IsLetter(myString, 1) && 
        Char.IsNumber(myString, (myString.Length - 2)) &&
        Char.IsNumber(myString, (myString.Length - 1))) {
        // First two are letters, second two are numbers
      }
      else {
        // Validation failed
    }
}
else {
   // Validation failed
}

How do you migrate an IIS 7 site to another server?

use appcmd to export one or all the sites out then reimport into the new server. It could be iis7.0 or 7.5 When you export out using appcmd, the passwords are decrypted, then reimport and they will reencrypt.

AngularJS ng-class if-else expression

You can try this method:

</p><br /><br />
<p>ng-class="{test: obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}<br /><br /><br />

ng-class="{test: obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}

You can get complete details from here.

How do I get data from a table?

This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row. This should give you an idea

//gets table
var oTable = document.getElementById('myTable');

//gets rows of table
var rowLength = oTable.rows.length;

//loops through rows    
for (i = 0; i < rowLength; i++){

   //gets cells of current row
   var oCells = oTable.rows.item(i).cells;

   //gets amount of cells of current row
   var cellLength = oCells.length;

   //loops through each cell in current row
   for(var j = 0; j < cellLength; j++){
      /* get your cell info here */
      /* var cellVal = oCells.item(j).innerHTML; */
   }
}

UPDATED - TESTED SCRIPT

<table id="myTable">
    <tr>
        <td>A1</td>
        <td>A2</td>
        <td>A3</td>
    </tr>
    <tr>
        <td>B1</td>
        <td>B2</td>
        <td>B3</td>
    </tr>
</table>
<script>
    //gets table
    var oTable = document.getElementById('myTable');

    //gets rows of table
    var rowLength = oTable.rows.length;

    //loops through rows    
    for (i = 0; i < rowLength; i++){

      //gets cells of current row  
       var oCells = oTable.rows.item(i).cells;

       //gets amount of cells of current row
       var cellLength = oCells.length;

       //loops through each cell in current row
       for(var j = 0; j < cellLength; j++){

              // get your cell info here

              var cellVal = oCells.item(j).innerHTML;
              alert(cellVal);
           }
    }
</script>

What does Maven do, in theory and in practice? When is it worth to use it?

From the Sonatype doc:

The answer to this question depends on your own perspective. The great majority of Maven users are going to call Maven a “build tool”: a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool. What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team.

I'd strongly recommend looking at the Sonatype doc and spending some time looking at the available plugins to understand the power of Maven.

Very briefly, it operates at a higher conceptual level than (say) Ant. With Ant, you'd specify the set of files and resources that you want to build, then specify how you want them jarred together, and specify the order that should occur in (clean/compile/jar). With Maven this is all implicit. Maven expects to find your files in particular places, and will work automatically with that. Consequently setting up a project with Maven can be a lot simpler, but you have to play by Maven's rules!

Generating an MD5 checksum of a file

There is a way that's pretty memory inefficient.

single file:

import hashlib
def file_as_bytes(file):
    with file:
        return file.read()

print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest()

list of files:

[(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]

Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead:

[(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]

If you only want 128 bits worth of digest you can do .digest()[:16].

This will give you a list of tuples, each tuple containing the name of its file and its hash.

Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard.

Here is a way that is more complex, but memory efficient:

import hashlib

def hash_bytestr_iter(bytesiter, hasher, ashexstr=False):
    for block in bytesiter:
        hasher.update(block)
    return hasher.hexdigest() if ashexstr else hasher.digest()

def file_as_blockiter(afile, blocksize=65536):
    with afile:
        block = afile.read(blocksize)
        while len(block) > 0:
            yield block
            block = afile.read(blocksize)


[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5()))
    for fname in fnamelst]

And, again, since MD5 is broken and should not really ever be used anymore:

[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256()))
    for fname in fnamelst]

Again, you can put [:16] after the call to hash_bytestr_iter(...) if you only want 128 bits worth of digest.

Where is my .vimrc file?

Open Vim, and in normal mode type:

:echo $VIM

Is it possible to use jQuery to read meta tags

jQuery now supports .data();, so if you have

<div id='author' data-content='stuff!'>

use

var author = $('#author').data("content"); // author = 'stuff!'

Trouble setting up git with my GitHub Account error: could not lock config file

You can also try issuing the command while in your home directory.

C# How to determine if a number is a multiple of another?

there are some syntax errors to your program heres a working code;

#include<stdio.h>
int main()
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0){
printf("this is  multiple number");
}
else if (b%a==0){
printf("this is multiple number");
}
else{
printf("this is not multiple number");
return 0;
}

}

How to use Apple's new .p8 certificate for APNs in firebase console

Firebase console is now accepting .p8 file, in fact, it's recommending to upload .p8 file.

You can see in below-attached screenshot

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

Just for others (like me) who might have faced the above error. The solution in simple terms.

You might have missed to register your Interface and class (which implements that inteface) registration in your code.

e.g if the error is
"The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?"

Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. using code like below

 container.RegisterType<Imyinterfacename, myinterfaceimplclassname>();

Advantages of std::for_each over for loop

The for_each loop is meant to hide the iterators (detail of how a loop is implemented) from the user code and define clear semantics on the operation: each element will be iterated exactly once.

The problem with readability in the current standard is that it requires a functor as the last argument instead of a block of code, so in many cases you must write specific functor type for it. That turns into less readable code as functor objects cannot be defined in-place (local classes defined within a function cannot be used as template arguments) and the implementation of the loop must be moved away from the actual loop.

struct myfunctor {
   void operator()( int arg1 ) { code }
};
void apply( std::vector<int> const & v ) {
   // code
   std::for_each( v.begin(), v.end(), myfunctor() );
   // more code
}

Note that if you want to perform an specific operation on each object, you can use std::mem_fn, or boost::bind (std::bind in the next standard), or boost::lambda (lambdas in the next standard) to make it simpler:

void function( int value );
void apply( std::vector<X> const & v ) {
   // code
   std::for_each( v.begin(), v.end(), boost::bind( function, _1 ) );
   // code
}

Which is not less readable and more compact than the hand rolled version if you do have function/method to call in place. The implementation could provide other implementations of the for_each loop (think parallel processing).

The upcoming standard takes care of some of the shortcomings in different ways, it will allow for locally defined classes as arguments to templates:

void apply( std::vector<int> const & v ) {
   // code
   struct myfunctor {
      void operator()( int ) { code }
   };
   std::for_each( v.begin(), v.end(), myfunctor() );
   // code
}

Improving the locality of code: when you browse you see what it is doing right there. As a matter of fact, you don't even need to use the class syntax to define the functor, but use a lambda right there:

void apply( std::vector<int> const & v ) {
   // code
   std::for_each( v.begin(), v.end(), 
      []( int ) { // code } );
   // code
}

Even if for the case of for_each there will be an specific construct that will make it more natural:

void apply( std::vector<int> const & v ) {
   // code
   for ( int i : v ) {
      // code
   }
   // code
}

I tend to mix the for_each construct with hand rolled loops. When only a call to an existing function or method is what I need (for_each( v.begin(), v.end(), boost::bind( &Type::update, _1 ) )) I go for the for_each construct that takes away from the code a lot of boiler plate iterator stuff. When I need something more complex and I cannot implement a functor just a couple of lines above the actual use, I roll my own loop (keeps the operation in place). In non-critical sections of code I might go with BOOST_FOREACH (a co-worker got me into it)

Jinja2 shorthand conditional

Alternative way (but it's not python style. It's JS style)

{{ files and 'Update' or 'Continue' }}

Learning Regular Expressions

The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.

If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.

Start simple

Conceptually, the simplest regular expressions are literal characters. The pattern N matches the character 'N'.

Regular expressions next to each other match sequences. For example, the pattern Nick matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.

If you've ever used grep on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re in grep refers to regular expressions.)

Order from the menu

Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c] matches either 'a' or 'b' or 'c'.

The pattern . is special: rather than matching a literal dot only, it matches any character. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...].

Think of character classes as menus: pick just one.

Helpful shortcuts

Using . can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]. Digits are a frequent match target, so you could instead use the shortcut \d. Others are \s (whitespace) and \w (word characters: alphanumerics or underscore).

The uppercased variants are their complements, so \S matches any non-whitespace character, for example.

Once is not enough

From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c matches 'abc' or 'ac' because the ? quantifier makes the subpattern it modifies optional. Other quantifiers are

  • * (zero or more times)
  • + (one or more times)
  • {n} (exactly n times)
  • {n,} (at least n times)
  • {n,m} (at least n times but no more than m times)

Putting some of these blocks together, the pattern [Nn]*ick matches all of

  • ick
  • Nick
  • nick
  • Nnick
  • nNick
  • nnick
  • (and so on)

The first match demonstrates an important lesson: * always succeeds! Any pattern can match zero times.

A few other useful examples:

  • [0-9]+ (and its equivalent \d+) matches any non-negative integer
  • \d{4}-\d{2}-\d{2} matches dates formatted like 2019-01-01

Grouping

A quantifier modifies the pattern to its immediate left. You might expect 0abc+0 to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c. This means 0abc+0 matches '0abc0', '0abcc0', '0abccc0', and so on.

To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr.

Alternation

Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |, e.g., (Nick|nick).

For another example, you could equivalently write [a-c] as a|b|c, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.

Escaping

Although some characters match themselves, others have special meanings. The pattern \d+ doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+. A backslash removes the special meaning from the following character.

Greediness

Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.

For example, say the input is

"Hello," she said, "How are you?"

You might expect ".+" to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.

To switch from greedy to what you might think of as cautious, add an extra ? to the quantifier. Now you understand how \((.+?)\), the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.

If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.

(As to your confusion, I don't know of any regular-expression dialect where ((.+?)) would do the same thing. I suspect something got lost in transmission somewhere along the way.)

Anchors

Use the special pattern ^ to match only at the beginning of your input and $ to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.

Say you want to match comments of the form

-- This is a comment --

you'd write ^--\s+(.+)\s+--$.

Build your own

Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.

Tools for writing and debugging regexes:

Books

Free resources

Footnote

†: The statement above that . matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n", but in practice you rarely expect a pattern such as .+ to cross a newline boundary. Perl regexes have a /s switch and Java Pattern.DOTALL, for example, to make . match any character at all. For languages that don't have such a feature, you can use something like [\s\S] to match "any whitespace or any non-whitespace", in other words anything.

How to make Firefox headless programmatically in Selenium with Python?

Just a note for people who may have found this later (and want java way of achieving this); FirefoxOptions is also capable of enabling the headless mode:

FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setHeadless(true);

How to catch a click event on a button?

Taken from: http://developer.android.com/guide/topics/ui/ui-events.html

// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
    public void onClick(View v) {
      // do something when the button is clicked
    }
};

protected void onCreate(Bundle savedValues) {
    ...
    // Capture our button from layout
    Button button = (Button)findViewById(R.id.corky);
    // Register the onClick listener with the implementation above
    button.setOnClickListener(mCorkyListener);
    ...
}

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.

  2. Is git saving every repository locally (in the user's machine) and in GitHub?

    If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.

  4. How does Git compare to a backup system such as Time Machine?

    Git is specifically designed and optimized for source code.

  5. Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?

    Exactly.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    See #4.

How to Disable GUI Button in Java

You create the frame with button enable, do some test to see if btn1Cliked is true, and that's all.

Then you have the actionPerformed method that does nothing with your button. So, if you don't have any action related, your button status will never be evaluated again.

When would you use the different git merge strategies?

As the answers above are not showing all strategy details. For example, some answer is missing the details about the import resolve option and the recursive which has many sub options as ours, theirs, patience, renormalize, etc.

Therefore, I would recommend to visit the official git documentation which explains all the possible features features:

https://git-scm.com/docs/merge-strategies

How to submit an HTML form on loading the page?

You can do it by using simple one line JavaScript code and also be careful that if JavaScript is turned off it will not work. The below code will do it's job if JavaScript is turned off.

Turn off JavaScript and run the code on you own file to know it's full function.(If you turn off JavaScript here, the below Code Snippet will not work)

_x000D_
_x000D_
.noscript-error {_x000D_
  color: red;_x000D_
}
_x000D_
<body onload="document.getElementById('payment-form').submit();">_x000D_
_x000D_
  <div align="center">_x000D_
    <h1>_x000D_
      Please Waite... You Will be Redirected Shortly<br/>_x000D_
      Don't Refresh or Press Back _x000D_
    </h1>_x000D_
  </div>_x000D_
_x000D_
  <form method='post' action='acction.php' id='payment-form'>_x000D_
    <input type='hidden' name='field-name' value='field-value'>_x000D_
     <input type='hidden' name='field-name2' value='field-value2'>_x000D_
    <noscript>_x000D_
      <div align="center" class="noscript-error">Sorry, your browser does not support JavaScript!._x000D_
        <br>Kindly submit it manually_x000D_
        <input type='submit' value='Submit Now' />_x000D_
      </div>_x000D_
    </noscript>_x000D_
  </form>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

Log.INFO vs. Log.DEBUG

Also remember that all info(), error(), and debug() logging calls provide internal documentation within any application.

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

Execute curl command within a Python script

Use this tool (hosted here for free) to convert your curl command to equivalent Python requests code:

Example: This,

curl 'https://www.example.com/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Origin: https://www.example.com' -H 'Accept-Encoding: gzip, deflate, br' -H 'Cookie: SESSID=ABCDEF' --data-binary 'Pathfinder' --compressed

Gets converted neatly to:

import requests

cookies = {
    'SESSID': 'ABCDEF',
}

headers = {
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'Origin': 'https://www.example.com',
    'Accept-Encoding': 'gzip, deflate, br',
}

data = 'Pathfinder'

response = requests.post('https://www.example.com/', headers=headers, cookies=cookies, data=data)

Get list of databases from SQL Server

To exclude system databases:

SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 6

Edited : 2:36 PM 2/5/2013

Updated with accurate database_id, It should be greater than 4, to skip listing system databases which are having database id between 1 and 4.

SELECT * 
FROM sys.databases d
WHERE d.database_id > 4

Check if array is empty or null

I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.

In the isEmptyObject doc, it mentions:

The argument should always be a plain JavaScript Object

which you can determine by $.isPlainObject. The return of $.isPlainObject([]) is false.

Java Try and Catch IOException Problem

Your countLines(String filename) method throws IOException.

You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.

Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.

Try this to just throw the IOException from main

public class MyClass {
  private int lineCount;
  public static void main(String[] args) throws IOException {
    lineCount = LineCounter.countLines(sFileName);
  }
}

or this to handle it and wrap it in an unchecked IllegalArgumentException:

public class MyClass {
  private int lineCount;
  private String sFileName  = "myfile";
  public static void main(String[] args) throws IOException {
    try {
      lineCount = LineCounter.countLines(sFileName);
     } catch (IOException e) {
       throw new IllegalArgumentException("Unable to load " + sFileName, e);
     }
  }
}

Convert blob URL to normal URL

For those who came here looking for a way to download a blob url video / audio, this answer worked for me. In short, you would need to find an *.m3u8 file on the desired web page through Chrome -> Network tab and paste it into a VLC player.

Another guide shows you how to save a stream with the VLC Player.

How to convert NSDate into unix timestamp iphone sdk?

 [NSString stringWithFormat: @"first unixtime is %ld",message,(long)[[NSDate date] timeIntervalSince1970]];

 [NSString stringWithFormat: @"second unixtime is %ld",message,[[NSDate date] timeIntervalSince1970]];

 [NSString stringWithFormat: @"third unixtime is %.0f",message,[[NSDate date] timeIntervalSince1970]]; 

first unixtime 1532278070

second unixtime 1532278070.461380

third unixtime 1532278070

Retrieving Android API version programmatically

Like this:

String versionRelease = BuildConfig.VERSION_NAME;

versionRelease :- 2.1.17

Please make sure your import package is correct ( import package your_application_package_name, otherwise it will not work properly).

No module named _sqlite3

  1. Install the sqlite-devel package:

    yum install sqlite-devel -y

  2. Recompile python from the source:

    ./configure
    make
    make altinstall
    

Copy file from source directory to binary directory using CMake

if you want to copy folder from currant directory to binary (build folder) folder

file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/yourFolder/ DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yourFolder/)

then the syntexe is :

file(COPY pathSource DESTINATION pathDistination)

How to set environment variables in PyCharm?

This is what you can do to source an .env (and .flaskenv) file in the pycharm flask/django console. It would also work for a normal python console of course.

  1. Do pip install python-dotenv in your environment (the same as being pointed to by pycharm).

  2. Go to: Settings > Build ,Execution, Deployment > Console > Flask/django Console

  3. In "starting script" include something like this near the top:

    from dotenv import load_dotenv load_dotenv(verbose=True)

The .env file can look like this: export KEY=VALUE

It doesn't matter if one includes export or not for dotenv to read it.

As an alternative you could also source the .env file in the activate shell script for the respective virtual environement.

Visual Studio 2015 is very slow

I found that the Windows Defender Antimalware is causing huge delays. Go to Update & Security -> Settings -> Windows Defender. Open the Defender and in the Settings selection, choose Exclusions and add the "devenv.exe' process. It worked for me

Sorting dictionary keys in python

[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]

PHP code to remove everything but numbers

Try this:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.

Converting PKCS#12 certificate into PEM using OpenSSL

You just need to supply a password. You can do it within the same command line with the following syntax:

openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password]

You will then be prompted for a password to encrypt the private key in your output file. Include the "nodes" option in the line above if you want to export the private key unencrypted (plaintext):

openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password] -nodes

More info: http://www.openssl.org/docs/apps/pkcs12.html