Programs & Examples On #Crtp

The curiously recurring template pattern (CRTP) is a C++ idiom in which a class X derives from a class template instantiation using X itself as template argument.

invalid use of incomplete type

You need to use a pointer or a reference as the proper type is not known at this time the compiler can not instantiate it.

Instead try:

void action(const typename Subclass::mytype &var) {
            (static_cast<Subclass*>(this))->do_action();
    }

How can I convert this foreach code to Parallel.ForEach?

These lines Worked for me.

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(lines , options, (item) =>
{
 //My Stuff
});

Query Mongodb on month, day, year... of a datetime

You can find record by month, day, year etc of dates by Date Aggregation Operators, like $dayOfYear, $dayOfWeek, $month, $year etc.

As an example if you want all the orders which are created in April 2016 you can use below query.

db.getCollection('orders').aggregate(
   [
     {
       $project:
         {
           doc: "$$ROOT",
           year: { $year: "$created" },
           month: { $month: "$created" },
           day: { $dayOfMonth: "$created" }
         }
     },
     { $match : { "month" : 4, "year": 2016 } }
   ]
)

Here created is a date type field in documents, and $$ROOT we used to pass all other field to project in next stage, and give us all the detail of documents.

You can optimize above query as per your need, it is just to give an example. To know more about Date Aggregation Operators, visit the link.

html <input type="text" /> onchange event not working

Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.

For static and dynamic inputs:

$(document).on('input', '.my-class', function(){
    alert('Input changed');
});

For static inputs only:

$('.my-class').on('input', function(){
    alert('Input changed');
});

JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/

Cross domain POST request is not sending cookie Ajax Jquery

Please note this doesn't solve the cookie sharing process, as in general this is bad practice.

You need to be using JSONP as your type:

From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

$.ajax(
    { 
      type: "POST",
      url: "http://example.com/api/getlist.json",
      dataType: 'jsonp',
      xhrFields: {
           withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
            xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
      },
      success: function(){
           alert('success');
      },
      error: function (xhr) {
             alert(xhr.responseText);
      }
    }
);

Databinding an enum property to a ComboBox in WPF

If you are using a MVVM, based on @rudigrobler answer you can do the following:

Add the following property to the ViewModel class

public Array ExampleEnumValues => Enum.GetValues(typeof(ExampleEnum));

Then in the XAML do the following:

<ComboBox ItemsSource="{Binding ExampleEnumValues}" ... />

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

For people working on PyCharm, and for forcing CPU, you can add the following line in the Run/Debug configuration, under Environment variables:

<OTHER_ENVIRONMENT_VARIABLES>;CUDA_VISIBLE_DEVICES=-1

Division in Python 2.7. and 3.3

In Python 2.x, make sure to have at least one operand of your division in float. Multiple ways you may achieve this as the following examples:

20. / 15
20 / float(15)

Cannot open local file - Chrome: Not allowed to load local resource

You just need to replace all image network paths to byte strings in stored Encoded HTML string. For this you required HtmlAgilityPack to convert Html string to Html document. https://www.nuget.org/packages/HtmlAgilityPack

Find Below code to convert each image src network path(or local path) to byte sting. It will definitely display all images with network path(or local path) in IE,chrome and firefox.

string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString();

// Decode the encoded string.
StringWriter myWriter = new StringWriter();
HttpUtility.HtmlDecode(encodedHtmlString, myWriter);
string DecodedHtmlString = myWriter.ToString();

//find and replace each img src with byte string
HtmlDocument document = new HtmlDocument();
document.LoadHtml(DecodedHtmlString);
document.DocumentNode.Descendants("img")
    .Where(e =>
    {
        string src = e.GetAttributeValue("src", null) ?? "";
        return !string.IsNullOrEmpty(src);//&& src.StartsWith("data:image");
    })
    .ToList()
    .ForEach(x =>
        {
        string currentSrcValue = x.GetAttributeValue("src", null);                                
        string filePath = Path.GetDirectoryName(currentSrcValue) + "\\";
        string filename = Path.GetFileName(currentSrcValue);
        string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
        FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();
        x.SetAttributeValue("src", "data:" + contenttype + ";base64," + Convert.ToBase64String(bytes));                                
    });

string result = document.DocumentNode.OuterHtml;
//Encode HTML string
string myEncodedString = HttpUtility.HtmlEncode(result);

Emailmodel.DtEmailFields.Rows[0]["Body"] = myEncodedString;

The response content cannot be parsed because the Internet Explorer engine is not available, or

I have had this issue also, and while -UseBasicParsing will work for some, if you actually need to interact with the dom it wont work. Try using a a group policy to stop the initial configuration window from ever appearing and powershell won't stop you anymore. See here https://wahlnetwork.com/2015/11/17/solving-the-first-launch-configuration-error-with-powershells-invoke-webrequest-cmdlet/

Took me just a few minutes once I found this page, once the GP is set, powershell will allow you through.

Multiple queries executed in java in single statement

I was wondering if it is possible to execute something like this using JDBC.

"SELECT FROM * TABLE;INSERT INTO TABLE;"

Yes it is possible. There are two ways, as far as I know. They are

  1. By setting database connection property to allow multiple queries, separated by a semi-colon by default.
  2. By calling a stored procedure that returns cursors implicit.

Following examples demonstrate the above two possibilities.

Example 1: ( To allow multiple queries ):

While sending a connection request, you need to append a connection property allowMultiQueries=true to the database url. This is additional connection property to those if already exists some, like autoReConnect=true, etc.. Acceptable values for allowMultiQueries property are true, false, yes, and no. Any other value is rejected at runtime with an SQLException.

String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";  

Unless such instruction is passed, an SQLException is thrown.

You have to use execute( String sql ) or its other variants to fetch results of the query execution.

boolean hasMoreResultSets = stmt.execute( multiQuerySqlString );

To iterate through and process results you require following steps:

READING_QUERY_RESULTS: // label  
    while ( hasMoreResultSets || stmt.getUpdateCount() != -1 ) {  
        if ( hasMoreResultSets ) {  
            Resultset rs = stmt.getResultSet();
            // handle your rs here
        } // if has rs
        else { // if ddl/dml/...
            int queryResult = stmt.getUpdateCount();  
            if ( queryResult == -1 ) { // no more queries processed  
                break READING_QUERY_RESULTS;  
            } // no more queries processed  
            // handle success, failure, generated keys, etc here
        } // if ddl/dml/...

        // check to continue in the loop  
        hasMoreResultSets = stmt.getMoreResults();  
    } // while results

Example 2: Steps to follow:

  1. Create a procedure with one or more select, and DML queries.
  2. Call it from java using CallableStatement.
  3. You can capture multiple ResultSets executed in procedure.
    DML results can't be captured but can issue another select
    to find how the rows are affected in the table.

Sample table and procedure:

mysql> create table tbl_mq( i int not null auto_increment, name varchar(10), primary key (i) );
Query OK, 0 rows affected (0.16 sec)

mysql> delimiter //
mysql> create procedure multi_query()
    -> begin
    ->  select count(*) as name_count from tbl_mq;
    ->  insert into tbl_mq( names ) values ( 'ravi' );
    ->  select last_insert_id();
    ->  select * from tbl_mq;
    -> end;
    -> //
Query OK, 0 rows affected (0.02 sec)
mysql> delimiter ;
mysql> call multi_query();
+------------+
| name_count |
+------------+
|          0 |
+------------+
1 row in set (0.00 sec)

+------------------+
| last_insert_id() |
+------------------+
|                3 |
+------------------+
1 row in set (0.00 sec)

+---+------+
| i | name |
+---+------+
| 1 | ravi |
+---+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Call Procedure from Java:

CallableStatement cstmt = con.prepareCall( "call multi_query()" );  
boolean hasMoreResultSets = cstmt.execute();  
READING_QUERY_RESULTS:  
    while ( hasMoreResultSets ) {  
        Resultset rs = stmt.getResultSet();
        // handle your rs here
    } // while has more rs

get UTC time in PHP

Using gmdate will always return a GMT date. Syntax is same as for date.

How to get controls in WPF to fill available space?

Each control deriving from Panel implements distinct layout logic performed in Measure() and Arrange():

  • Measure() determines the size of the panel and each of its children
  • Arrange() determines the rectangle where each control renders

The last child of the DockPanel fills the remaining space. You can disable this behavior by setting the LastChild property to false.

The StackPanel asks each child for its desired size and then stacks them. The stack panel calls Measure() on each child, with an available size of Infinity and then uses the child's desired size.

A Grid occupies all available space, however, it will set each child to their desired size and then center them in the cell.

You can implement your own layout logic by deriving from Panel and then overriding MeasureOverride() and ArrangeOverride().

See this article for a simple example.

Difference between logical addresses, and physical addresses?

I found a article about Logical vs Physical Address in Operating System, which clearly explains about this.

Logical Address is generated by CPU while a program is running. The logical address is virtual address as it does not exist physically therefore it is also known as Virtual Address. This address is used as a reference to access the physical memory location by CPU. The term Logical Address Space is used for the set of all logical addresses generated by a programs perspective. The hardware device called Memory-Management Unit is used for mapping logical address to its corresponding physical address.

Physical Address identifies a physical location of required data in a memory. The user never directly deals with the physical address but can access by its corresponding logical address. The user program generates the logical address and thinks that the program is running in this logical address but the program needs physical memory for its execution therefore the logical address must be mapped to the physical address bu MMU before they are used. The term Physical Address Space is used for all physical addresses corresponding to the logical addresses in a Logical address space.

Logical and Physical Address comparision

Source: www.geeksforgeeks.org

Refresh Part of Page (div)

Use Ajax for this.

Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.

Relevant function:

http://api.jquery.com/load/

e.g.

$('#thisdiv').load(document.URL +  ' #thisdiv');

Note, load automatically replaces content. Be sure to include a space before the id selector.

CAST to DECIMAL in MySQL

DECIMAL has two parts: Precision and Scale. So part of your query will look like this:

CAST((COUNT(*) * 1.5) AS DECIMAL(8,2))

Precision represents the number of significant digits that are stored for values.
Scale represents the number of digits that can be stored following the decimal point.

"Object doesn't support this property or method" error in IE11

We were also facing this issue when using IE version 11 to access our React app (create-react-app with react version 16.0.0 with jQuery v3.1.1) on the enterprise intranet. To solve it, i simply followed the directions at this url which are also listed below:

  1. Make sure to set the DOCTYPE to standards mode by making sure the first line of the master file is: <!DOCTYPE html>

  2. Force IE 11 to use the latest internal version by including the following meta tag in the head tag: <meta http-equiv="X-UA-Compatible" content="IE=edge;" />

NOTE: I did not face the problem when using IE to access the app in development mode on my local machine (localhost:3000). The problem occurred only when accessing the app deployed to the DEV server on the company Intranet, probably because of some company wide Windows OS policy settings and/or IE Internet Options.

How can I extract embedded fonts from a PDF as valid font files?

Eventually found the FontForge Windows installer package and opened the PDF through the installed program. Worked a treat, so happy.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

Another simple way to exclude the auto configuration classes,

Add below similar configuration to your application.yml file,

---
spring:
  profiles: test
  autoconfigure.exclude: org.springframework.boot.autoconfigure.session.SessionAutoConfiguration

How to set maximum fullscreen in vmware?

It sounds to me as if you actually mean "linux guests" and not "linux hosts".

But in any case, I suspect you did not install the VMWare Tools: doubleclick on that icon on the Desktop that can be seen on your screenshot. It will install some drivers that communicate with VMWare that, among other things, allow to adjust the screen resolution dynamically.

When the installation process is finished, you'll most likely have to reboot the VM.

How do I get a plist as a Dictionary in Swift?

This answer uses Swift native objects rather than NSDictionary.

Swift 3.0

//get the path of the plist file
guard let plistPath = Bundle.main.path(forResource: "level1", ofType: "plist") else { return }
//load the plist as data in memory
guard let plistData = FileManager.default.contents(atPath: plistPath) else { return }
//use the format of a property list (xml)
var format = PropertyListSerialization.PropertyListFormat.xml
//convert the plist data to a Swift Dictionary
guard let  plistDict = try! PropertyListSerialization.propertyList(from: plistData, options: .mutableContainersAndLeaves, format: &format) as? [String : AnyObject] else { return }
//access the values in the dictionary 
if let value = plistDict["aKey"] as? String {
  //do something with your value
  print(value)
}
//you can also use the coalesce operator to handle possible nil values
var myValue = plistDict["aKey"] ?? ""

Can I scale a div's height proportionally to its width using CSS?

If you want vertical sizing proportional to a width set in pixels on an enclosing div, I believe you need an extra element, like so:

#html

<div class="ptest">
    <div class="ptest-wrap">
        <div class="ptest-inner">
            Put content here
        </div>
    </div>
</div>

#css
.ptest {
  width: 200px;
  position: relative;
}

.ptest-wrap {
    padding-top: 60%;
}
.ptest-inner {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #333;
}

Here's the 2 div solution that doesn't work. Note the 60% vertical padding is proportional to the window width, not the div.ptest width:

http://jsfiddle.net/d85FM/

Here's the example with the code above, which does work:

http://jsfiddle.net/mmq29/

How can I represent a range in Java?

You could use java.time.temporal.ValueRange which accepts long and would also work with int:

int a = 2147;

//Use java 8 java.time.temporal.ValueRange. The range defined
//is inclusive of both min and max 
ValueRange range = ValueRange.of(0, 2147483647);

if(range.isValidValue(a)) {
    System.out.println("in range");
}else {
    System.out.println("not in range");
}

How to limit file upload type file size in PHP?

If you are looking for a hard limit across all uploads on the site, you can limit these in php.ini by setting the following:

`upload_max_filesize = 2M` `post_max_size = 2M`

that will set the maximum upload limit to 2 MB

How to make html table vertically scrollable

I fought with this one for a while. My goal was to have a table with headers where the widths of the each header column was the the same as the corresponding body column and was the minimum size necessary to fit the data. also the body data was scrollable underneath header.

I solved this by using divs and not tables. Each "table" was a div with the header being a div of divs and the body being a div of divs. I used the style as indicated by @sushil above. I added a bit of javascript/jQuery to balance the columns. Maybe 20-30 lines.

Unfortunately I lost the code and have to rebuild it. I know this is a bit old, but maybe it will help someone else.

WCF service maxReceivedMessageSize basicHttpBinding issue

Is the name of your service class really IService (on the Service namespace)? What you probably had originally was a mismatch in the name of the service class in the name attribute of the <service> element.

What is a .NET developer?

CLR, BCL and C#/VB.Net, ADO.NET, WinForms and/or ASP.NET. Most of the places that require additional .Net technologies, like WPF or WCF will call it out explicitly.

Export SQL query data to Excel

If you're just needing to export to excel, you can use the export data wizard. Right click the database, Tasks->Export data.

$(document).ready(function() is not working

If you have a js file that references the jquery, it could be because the js file is in the body and not in the head section (that was my problem). You should move your js file to the head section AFTER the jquery.js reference.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
    <script src="myfile.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>

How to specify in crontab by what user to run script?

Instead of creating a crontab to run as the root user, create a crontab for the user that you want to run the script. In your case, crontab -u www-data -e will edit the crontab for the www-data user. Just put your full command in there and remove it from the root user's crontab.

ToString() function in Go

Attach a String() string method to any named type and enjoy any custom "ToString" functionality:

package main

import "fmt"

type bin int

func (b bin) String() string {
        return fmt.Sprintf("%b", b)
}

func main() {
        fmt.Println(bin(42))
}

Playground: http://play.golang.org/p/Azql7_pDAA


Output

101010

Toggle show/hide on click with jQuery

You can use this code for toggle your element var ele = jQuery("yourelementid"); ele.slideToggle('slow'); this will work for you :)

Why can't I call a public method in another class?

It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.

MyClass myClass = new MyClass();

once you've added that line you can then call your method

myClass.myMethod();

Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.

Jquery UI tooltip does not support html content

Html Markup

Tool-tip Control with class ".why", and Tool-tip Content Area with class ".customTolltip"

$(function () {
                $('.why').attr('title', function () {
                    return $(this).next('.customTolltip').remove().html();
                });
                $(document).tooltip();
            });

Why does the 'int' object is not callable error occur when using the sum() function?

In the interpreter its easy to restart it and fix such problems. If you don't want to restart the interpreter, there is another way to fix it:

Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3]
>>> sum(l)
6
>>> sum = 0 # oops! shadowed a builtin!
>>> sum(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> import sys
>>> sum = sys.modules['__builtin__'].sum # -- fixing sum
>>> sum(l)
6

This also comes in handy if you happened to assign a value to any other builtin, like dict or list

How to Get a Sublist in C#

Would it be as easy as running a LINQ query on your List?

List<string> mylist = new List<string>{ "hello","world","foo","bar"};
List<string> listContainingLetterO = mylist.Where(x=>x.Contains("o")).ToList();

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

What Are The Best Width Ranges for Media Queries

You can take a look here for a longer list of screen sizes and respective media queries.

Or go for Bootstrap media queries:

/* Large desktop */
@media (min-width: 1200px) { ... }

/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }

/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }

/* Landscape phones and down */
@media (max-width: 480px) { ... }

Additionally you might wanty to take a look at Foundation's media queries with the following default settings:

// Media Queries

$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;

Restore a postgres backup file using the command line?

You might need to be logged in as postgres in order to have full privileges on databases.

su - postgres
psql -l                      # will list all databases on Postgres cluster

pg_dump/pg_restore

  pg_dump -U username -f backup.dump database_name -Fc 

switch -F specify format of backup file:

  • c will use custom PostgreSQL format which is compressed and results in smallest backup file size
  • d for directory where each file is one table
  • t for TAR archive (bigger than custom format)
  • -h/--host Specifies the host name of the machine on which the server is running
  • -W/--password Force pg_dump to prompt for a password before connecting to a database

restore backup:

   pg_restore -d database_name -U username -C backup.dump

Parameter -C should create database before importing data. If it doesn't work you can always create database eg. with command (as user postgres or other account that has rights to create databases) createdb db_name -O owner

pg_dump/psql

In case that you didn't specify the argument -F default plain text SQL format was used (or with -F p). Then you can't use pg_restore. You can import data with psql.

backup:

pg_dump -U username -f backup.sql database_name

restore:

psql -d database_name -f backup.sql

need to test if sql query was successful

This has proven the safest mechanism for me to test for failure on insert or update:

$result = $db->query(' ... ');
if ((gettype($result) == "object" && $result->num_rows == 0) || !$result) {
   failure 
}

How to tell bash that the line continues on the next line

\ does the job. @Guillaume's answer and @George's comment clearly answer this question. Here I explains why The backslash has to be the very last character before the end of line character. Consider this command:

   mysql -uroot \
   -hlocalhost      

If there is a space after \, the line continuation will not work. The reason is that \ removes the special meaning for the next character which is a space not the invisible line feed character. The line feed character is after the space not \ in this example.

How to send SMS in Java

There is an API called SMSLib, it's really awesome. http://smslib.org/

Now you have a lot of Saas providers that can give you this service using their APIs

Ex: mailchimp, esendex, Twilio, ...

Mercurial stuck "waiting for lock"

If the locked repo was the original, I can't imagine it was modifying it to clone it, so it was only preventing you from changing it in the middle and messing up the clone. It should be fine after removing the lock.

The new cloned copy (if it was a local clone) could be in any sort of malformed state, though, so you should throw it out and start it over. (If it was a remote clone, I would hope it failed and already threw out the incomplete copy.)

How to create a cron job using Bash automatically without the interactive editor?

Thanks everybody for your help. Piecing together what I found here and elsewhere I came up with this:

The Code

command="php $INSTALL/indefero/scripts/gitcron.php"
job="0 0 * * 0 $command"
cat <(fgrep -i -v "$command" <(crontab -l)) <(echo "$job") | crontab -

I couldn't figure out how to eliminate the need for the two variables without repeating myself.

command is obviously the command I want to schedule. job takes $command and adds the scheduling data. I needed both variables separately in the line of code that does the work.

Details

  1. Credit to duckyflip, I use this little redirect thingy (<(*command*)) to turn the output of crontab -l into input for the fgrep command.
  2. fgrep then filters out any matches of $command (-v option), case-insensitive (-i option).
  3. Again, the little redirect thingy (<(*command*)) is used to turn the result back into input for the cat command.
  4. The cat command also receives echo "$job" (self explanatory), again, through use of the redirect thingy (<(*command*)).
  5. So the filtered output from crontab -l and the simple echo "$job", combined, are piped ('|') over to crontab - to finally be written.
  6. And they all lived happily ever after!

In a nutshell:

This line of code filters out any cron jobs that match the command, then writes out the remaining cron jobs with the new one, effectively acting like an "add" or "update" function. To use this, all you have to do is swap out the values for the command and job variables.

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

How to clear the entire array?

For deleting a dynamic array in VBA use the instruction Erase.

Example:

Dim ArrayDin() As Integer    
ReDim ArrayDin(10)    'Dynamic allocation 
Erase ArrayDin        'Erasing the Array   

Hope this help!

Checkbox Check Event Listener

Short answer: Use the change event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.

Single checkbox

Using querySelector.

_x000D_
_x000D_
var checkbox = document.querySelector("input[name=checkbox]");

checkbox.addEventListener('change', function() {
  if (this.checked) {
    console.log("Checkbox is checked..");
  } else {
    console.log("Checkbox is not checked..");
  }
});
_x000D_
<input type="checkbox" name="checkbox" />
_x000D_
_x000D_
_x000D_

Single checkbox with jQuery

_x000D_
_x000D_
$('input[name=checkbox]').change(function() {
  if ($(this).is(':checked')) {
    console.log("Checkbox is checked..")
  } else {
    console.log("Checkbox is not checked..")
  }
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="checkbox" />
_x000D_
_x000D_
_x000D_

Multiple checkboxes

Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll instead of querySelector. Then use Array.filter and Array.map to extract checked values.

_x000D_
_x000D_
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []

/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/

// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
  checkbox.addEventListener('change', function() {
    enabledSettings = 
      Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
      .filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
      .map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
      
    console.log(enabledSettings)
  })
});
_x000D_
<label>
   <input type="checkbox" name="settings" value="forcefield">
   Enable forcefield
</label>
<label>
  <input type="checkbox" name="settings" value="invisibilitycloak">
  Enable invisibility cloak
</label>
<label>
  <input type="checkbox" name="settings" value="warpspeed">
  Enable warp speed
</label>
_x000D_
_x000D_
_x000D_

Multiple checkboxes with jQuery

_x000D_
_x000D_
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];

// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
  enabledSettings = checkboxes
    .filter(":checked") // Filter out unchecked boxes.
    .map(function() { // Extract values using jQuery map.
      return this.value;
    }) 
    .get() // Get array.
    
  console.log(enabledSettings);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
   <input type="checkbox" name="settings" value="forcefield">
   Enable forcefield
</label>
<label>
  <input type="checkbox" name="settings" value="invisibilitycloak">
  Enable invisibility cloak
</label>
<label>
  <input type="checkbox" name="settings" value="warpspeed">
  Enable warp speed
</label>
_x000D_
_x000D_
_x000D_

What is difference between Lightsail and EC2?

In lightsail a virtual machine, SSD-based storage, data transfer, DNS management, and a static IP are all offered as a package. Whereas in normal case you provision an EC2 instance and then setup the rest of these things.Also Bandwidth included in the price, no security groups to set up, no need to worry about EBS volumes sizing.

How can I change the font size using seaborn FacetGrid?

You can scale up the fonts in your call to sns.set().

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.1))

enter image description here

sns.set(font_scale=5)  # crazy big
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='big')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.3))

enter image description here

How can I extract substrings from a string in Perl?

String 1:

$input =~ /'^\S+'/;
$s1 = $&;

String 2:

$input =~ /\(.*\)/;
$s2 = $&;

String 3:

$input =~ /\*?$/;
$s3 = $&;

Get type name without full namespace

typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name

MySQL: Curdate() vs Now()

CURDATE() will give current date while NOW() will give full date time.

Run the queries, and you will find out whats the difference between them.

SELECT NOW();     -- You will get 2010-12-09 17:10:18
SELECT CURDATE(); -- You will get 2010-12-09

rails generate model

The error shows you either didn't create the rails project yet or you're not in the rails project directory.

Suppose if you're working on myapp project. You've to move to that project directory on your command line and then generate the model. Here are some steps you can refer.

Example: Assuming you didn't create the Rails app yet:

$> rails new myapp
$> cd myapp

Now generate the model from your commandline.

$> rails generate model your_model_name 

How to execute a query in ms-access in VBA code?

Take a look at this tutorial for how to use SQL inside VBA:

http://www.ehow.com/how_7148832_access-vba-query-results.html

For a query that won't return results, use (reference here):

DoCmd.RunSQL

For one that will, use (reference here):

Dim dBase As Database
dBase.OpenRecordset

List of strings to one string

If you use .net 4.0 you can use a sorter way:

String.Join<string>(String.Empty, los);

How to create a List with a dynamic object type

Just use dynamic as the argument:

var list = new List<dynamic>();

Python circular importing?

I was able to import the module within the function (only) that would require the objects from this module:

def my_func():
    import Foo
    foo_instance = Foo()

Is it wrong to place the <script> tag after the </body> tag?

Google actually recommends this in regards to 'CSS Optimization'. They recommend in-lining critical above-fold styles and deferring the rest(css file).

Example:

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

See: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery

What does "Content-type: application/json; charset=utf-8" really mean?

Dart http's implementation process the bytes thanks to that "charset=utf-8", so i'm sure several implementations out there supports this, to avoid the "latin-1" fallback charset when reading the bytes from the response. In my case, I totally lose format on the response body string, so I have to do the bytes encoding manually to utf8, or add that header "inner" parameter on my server's API response.

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

Use Moment.js (https://momentjs.com/)

moment().isDST(); will give you if Day light savings is observed.

Also it has helper function to calculate relative time for you. You don't need to do manual calculations e.g moment("20200105", "YYYYMMDD").fromNow();

cmake error 'the source does not appear to contain CMakeLists.txt'

Since you add .. after cmake, it will jump up and up (just like cd ..) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use . instead of ...

How to read a PEM RSA private key from .NET

I've tried the accepted answer for PEM-encoded PKCS#8 RSA private key and it resulted in PemException with malformed sequence in RSA private key message. The reason is that Org.BouncyCastle.OpenSsl.PemReader seems to only support PKCS#1 private keys.

I was able to get the private key by switching to Org.BouncyCastle.Utilities.IO.Pem.PemReader (note that type names match!) like this

private static RSAParameters GetRsaParameters(string rsaPrivateKey)
{
    var byteArray = Encoding.ASCII.GetBytes(rsaPrivateKey);
    using (var ms = new MemoryStream(byteArray))
    {
        using (var sr = new StreamReader(ms))
        {
            var pemReader = new Org.BouncyCastle.Utilities.IO.Pem.PemReader(sr);
            var pem = pemReader.ReadPemObject();
            var privateKey = PrivateKeyFactory.CreateKey(pem.Content);

            return DotNetUtilities.ToRSAParameters(privateKey as RsaPrivateCrtKeyParameters);
        }
    }
}

Print string to text file

If you are using numpy, printing a single (or multiply) strings to a file can be done with just one line:

numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')

MySQL pivot table query with dynamic columns

The only way in MySQL to do this dynamically is with Prepared statements. Here is a good article about them:

Dynamic pivot tables (transform rows to columns)

Your code would look like this:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(pa.fieldname = ''',
      fieldname,
      ''', pa.fieldvalue, NULL)) AS ',
      fieldname
    )
  ) INTO @sql
FROM product_additional;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See Demo

NOTE: GROUP_CONCAT function has a limit of 1024 characters. See parameter group_concat_max_len

How do I check to see if a value is an integer in MySQL?

I have tried using the regular expressions listed above, but they do not work for the following:

SELECT '12 INCHES' REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$' FROM ...

The above will return 1 (TRUE), meaning the test of the string '12 INCHES' against the regular expression above, returns TRUE. It looks like a number based on the regular expression used above. In this case, because the 12 is at the beginning of the string, the regular expression interprets it as a number.

The following will return the right value (i.e. 0) because the string starts with characters instead of digits

SELECT 'TOP 10' REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$' FROM ...

The above will return 0 (FALSE) because the beginning of the string is text and not numeric.

However, if you are dealing with strings that have a mix of numbers and letters that begin with a number, you will not get the results you want. REGEXP will interpret the string as a valid number when in fact it is not.

List of zeros in python

#add code here to figure out the number of 0's you need, naming the variable n.
listofzeros = [0] * n

if you prefer to put it in the function, just drop in that code and add return listofzeros

Which would look like this:

def zerolistmaker(n):
    listofzeros = [0] * n
    return listofzeros

sample output:

>>> zerolistmaker(4)
[0, 0, 0, 0]
>>> zerolistmaker(5)
[0, 0, 0, 0, 0]
>>> zerolistmaker(15)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> 

How to sort List of objects by some property

You can call Collections.sort() and pass in a Comparator which you need to write to compare different properties of the object.

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

Be aware that need to change both location:

File > Settings... > Editor > Code Style > "Hard Wrap at"

and

File > Settings... > Editor > Code Style > (your language) > Wrapping and Braces > Hard wrap at

Accessing the web page's HTTP Headers in JavaScript

I've just tested, and this works for me using Chrome Version 28.0.1500.95.

I was needing to download a file and read the file name. The file name is in the header so I did the following:

var xhr = new XMLHttpRequest(); 
xhr.open('POST', url, true); 
xhr.responseType = "blob";
xhr.onreadystatechange = function () { 
    if (xhr.readyState == 4) {
        success(xhr.response); // the function to proccess the response

        console.log("++++++ reading headers ++++++++");
        var headers = xhr.getAllResponseHeaders();
        console.log(headers);
        console.log("++++++ reading headers end ++++++++");

    }
};

Output:

Date: Fri, 16 Aug 2013 16:21:33 GMT
Content-Disposition: attachment;filename=testFileName.doc
Content-Length: 20
Server: Apache-Coyote/1.1
Content-Type: application/octet-stream

Launching Google Maps Directions via an intent on Android

to open maps app that in HUAWEI devices which contains HMS:

const val GOOGLE_MAPS_APP = "com.google.android.apps.maps"
const val HUAWEI_MAPS_APP = "com.huawei.maps.app"

    fun openMap(lat:Double,lon:Double) {
    val packName = if (isHmsOnly(context)) {
        HUAWEI_MAPS_APP
    } else {
        GOOGLE_MAPS_APP
    }

        val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        intent.setPackage(packName);
        if (intent.resolveActivity(context.packageManager) != null) {
            appLifecycleObserver.isSecuredViewing = true
            context.startActivity(intent)
        } else {
            openMapOptions(lat, lon)
        }
}

private fun openMapOptions(lat: Double, lon: Double) {
    val intent = Intent(
        Intent.ACTION_VIEW,
        Uri.parse("geo:$lat,$lon?q=$lat,$lon")
    )
    context.startActivity(intent)
}

HMS checks:

private fun isHmsAvailable(context: Context?): Boolean {
var isAvailable = false
if (null != context) {
    val result =
        HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context)
    isAvailable = ConnectionResult.SUCCESS == result
}
return isAvailable}

private fun isGmsAvailable(context: Context?): Boolean {
    var isAvailable = false
    if (null != context) {
        val result: Int = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
        isAvailable = com.google.android.gms.common.ConnectionResult.SUCCESS == result
    }
    return isAvailable }

fun isHmsOnly(context: Context?) = isHmsAvailable(context) && !isGmsAvailable(context)

How to scroll table's "tbody" independent of "thead"?

I saw this post about a month ago when I was having similar problems. I needed y-axis scrolling for a table inside of a ui dialog (yes, you heard me right). I was lucky, in that a working solution presented itself fairly quickly. However, it wasn't long before the solution took on a life of its own, but more on that later.

The problem with just setting the top level elements (thead, tfoot, and tbody) to display block, is that browser synchronization of the column sizes between the various components is quickly lost and everything packs to the smallest permissible size. Setting the widths of the columns seems like the best course of action, but without setting the widths of all the internal table components to match the total of these columns, even with a fixed table layout, there is a slight divergence between the headers and body when a scroll bar is present.

The solution for me was to set all the widths, check if a scroll bar was present, and then take the scaled widths the browser had actually decided on, and copy those to the header and footer adjusting the last column width for the size of the scroll bar. Doing this provides some fluidity to the column widths. If changes to the table's width occur, most major browsers will auto-scale the tbody column widths accordingly. All that's left is to set the header and footer column widths from their respective tbody sizes.

$table.find("> thead,> tfoot").find("> tr:first-child")
    .each(function(i,e) {
        $(e).children().each(function(i,e) {
            if (i != column_scaled_widths.length - 1) {
                $(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()));
            } else {
                $(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()) + $.position.scrollbarWidth());
            }
        });
    });

This fiddle illustrates these notions: http://jsfiddle.net/borgboyone/gbkbhngq/.

Note that a table wrapper or additional tables are not needed for y-axis scrolling alone. (X-axis scrolling does require a wrapping table.) Synchronization between the column sizes for the body and header will still be lost if the minimum pack size for either the header or body columns is encountered. A mechanism for minimum widths should be provided if resizing is an option or small table widths are expected.

The ultimate culmination from this starting point is fully realized here: http://borgboyone.github.io/jquery-ui-table/

A.

Basic calculator in Java

public class SwitchExample {

    public static void main(String[] args) throws Exception {
        System.out.println(":::::::::::::::::::::Start:::::::::::::::::::");
        System.out.println("\n\n");

        System.out.println("1. Addition");
        System.out.println("2. Multiplication");
        System.out.println("3. Substraction");
        System.out.println("4. Division");
        System.out.println("0. Exit");
        System.out.println("\n");

        System.out.println("Enter Your Choice :::::::  ");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();

        int usrChoice = Integer.parseInt(str);

        switch (usrChoice) {
            case 1:
                doAddition();
                break;
            case 2:
                doMultiplication();
                break;
            case 3:
                doSubstraction();
                break;
            case 4:
                doDivision();
                break;

            case 0:
                System.out.println("Thank you.....");
                break;

            default:
                System.out.println("Invalid Value");
        }

        System.out.println(":::::::::::::::::::::End:::::::::::::::::::");
}

public static void doAddition() throws Exception {
    System.out.println("******* Enter in Addition Process ********");

    String strNo1, strNo2;

    System.out.println("Enter Number 1 For Addition : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    strNo1 = br.readLine();

    System.out.println("Enter Number 2 For Addition : ");
    BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
    strNo2 = br1.readLine();

    int no1 = Integer.parseInt(strNo1);
    int no2 = Integer.parseInt(strNo2);

    int result = no1 + no2;

    System.out.println("Addition of " + no1 + " and " + no2 + " is ::::::: " + result);
}

public static void doSubstraction() throws Exception {
    System.out.println("******* Enter in Substraction Process ********");

    String strNo1, strNo2;

    System.out.println("Enter Number 1 For Substraction : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    strNo1 = br.readLine();

    System.out.println("Enter Number 2 For Substraction : ");
    BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
    strNo2 = br1.readLine();

    int no1 = Integer.parseInt(strNo1);
    int no2 = Integer.parseInt(strNo2);

    int result = no1 - no2;

    System.out.println("Substraction of " + no1 + " and " + no2 + " is ::::::: " + result);
}

public static void doMultiplication() throws Exception {
    System.out.println("******* Enter in Multiplication Process ********");

    String strNo1, strNo2;

    System.out.println("Enter Number 1 For Multiplication : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    strNo1 = br.readLine();

    System.out.println("Enter Number 2 For Multiplication : ");
    BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
    strNo2 = br1.readLine();

    int no1 = Integer.parseInt(strNo1);
    int no2 = Integer.parseInt(strNo2);

    int result = no1 * no2;

    System.out.println("Multiplication of " + no1 + " and " + no2 + " is ::::::: " + result);
}

public static void doDivision() throws Exception {
    System.out.println("******* Enter in Dividion Process ********");

    String strNo1, strNo2;

    System.out.println("Enter Number 1 For Dividion : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    strNo1 = br.readLine();

    System.out.println("Enter Number 2 For Dividion : ");
    BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
    strNo2 = br1.readLine();

    int no1 = Integer.parseInt(strNo1);
    int no2 = Integer.parseInt(strNo2);

    float result = no1 / no2;

    System.out.println("Division of " + no1 + " and " + no2 + " is ::::::: " + result);
}

}

List vs tuple, when to use each?

The first thing you need to decide is whether the data structure needs to be mutable or not. As has been mentioned, lists are mutable, tuples are not. This also means that tuples can be used for dictionary keys, wheres lists cannot.

In my experience, tuples are generally used where order and position is meaningful and consistant. For example, in creating a data structure for a choose your own adventure game, I chose to use tuples instead of lists because the position in the tuple was meaningful. Here is one example from that data structure:

pages = {'foyer': {'text' : "some text", 
          'choices' : [('open the door', 'rainbow'),
                     ('go left into the kitchen', 'bottomless pit'),
                     ('stay put','foyer2')]},}

The first position in the tuple is the choice displayed to the user when they play the game and the second position is the key of the page that choice goes to and this is consistent for all pages.

Tuples are also more memory efficient than lists, though I'm not sure when that benefit becomes apparent.

Also check out the chapters on lists and tuples in Think Python.

How to install easy_install in Python 2.7.1 on Windows 7

That tool is part of the setuptools (now called Distribute) package. Install Distribute. Of course you'll have to fetch that one manually.

http://pypi.python.org/pypi/distribute#installation-instructions

Current user in Magento?

$customer = Mage::getSingleton('customer/session')->getCustomer();
    $customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
    $address = Mage::getModel('customer/address')->load($customerAddressId);
    $fullname = $customer->getName();
    $firstname = $customer->getFirstname();
    $lastname = $customer->getLastname();
    $email = $customer->getEmail();
    $taxvat = $customer->getTaxvat();
    $tele = $customer->getTelephone();
    $telephone = $address->getTelephone();
    $street = $address->getStreet();
    $City = $address->getCity();
    $region = $address->getRegion();
    $postcode = $address->getPostcode();

Get customer Default Billing address

Spring Boot not serving static content

Did you check the Spring Boot reference docs?

By default Spring Boot will serve static content from a folder called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext.

You can also compare your project with the guide Serving Web Content with Spring MVC, or check out the source code of the spring-boot-sample-web-ui project.

"Unable to get the VLookup property of the WorksheetFunction Class" error

Try below code

I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.

Private Sub ComboBox1_Change()


    On Error Resume Next
    Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
    On Error GoTo 0

    If Ret <> "" Then MsgBox Ret


End Sub

OR

 On Error Resume Next

    Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)

    If Result = "Error 2042" Then
        'nothing found
    ElseIf cell <> Result Then
        MsgBox cell.Value
    End If

    On Error GoTo 0

What is setup.py?

setup.py is a python file, the presence of which is an indication that the module/package you are about to install has likely been packaged and distributed with Distutils, which is the standard for distributing Python Modules.

This allows you to easily install Python packages. Often it's enough to write:

$ pip install . 

pip will use setup.py to install your module. Avoid calling setup.py directly.

https://docs.python.org/3/installing/index.html#installing-index

Unrecognized SSL message, plaintext connection? Exception

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

You should have a local SMTP domain name that will contact the mail server and establishes a new connection as well you should change the SSL property in your programming below

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection

 props.put("mail.smtp.socketFactory.fallback", "true"); // Should be true

What's the difference between OpenID and OAuth?

More an extension to the question than an answer, but it may add some perspective to the great technical answers above. I'm an experienced programmer in a number of areas, but a total noob to programming for the web. Now trying to build a web-based application using Zend Framework.

Definitely will implement an application-specific basic username/password authentication interface, but recognize that for a growing number of users the thought of yet another username and password is a deterrent. While not exactly social networking, I know that a very large percentage of the application's potential users already have facebook or twitter accounts. The application doesn't really want or need to access information about the user's account from those sites, it just wants to offer the convenience of not requiring the user to set up new account credentials if they don't want to. From a functionality point of view, that would seem a poster child for OpenID. But it seems that neither facebook nor twitter are OpenID providers as such, though they do support OAuth authentication to access their user's data.

In all the articles I've read about the two and how they differ, it wan't until I saw Karl Anderson's observation above, that "OAuth can be used for authentication, which can be thought of as a no-op authorization" that I saw any explicit confirmation that OAuth was good enough for what I wanted to do.

In fact, when I went to post this "answer", not being a member at the time, I looked long and hard at the bottom of this page at the options for identifying myself. The option for using an OpenID login or obtaining one if I didn't have one, but nothing about twitter or facebook, seemed to suggest that OAuth wasn't adequate for the job. But then I opened another window and looked for the general signup process for stackoverflow - and lo and behold there's a slew of 3rd-party authentication options including facebook and twitter. In the end I decided to use my google id (which is an OpenID) for exactly the reason that I didn't want to grant stackoverflow access to my friends list and anything else facebook likes to share about its users - but at least it's a proof point that OAuth is adequate for the use I had in mind.

It would really be great if someone could either post info or pointers to info about supporting this kind of multiple 3rd-part authorization setup, and how you deal with users that revoke authorization or lose access to their 3rd party site. I also get the impression that my username here identifies a unique stackoverflow account that I could access with basic authentication if I wanted to set it up, and also access this same account through other 3rd-party authenticators (e.g. so that I would be considered logged in to stackoverflow if I was logged in to any of google, facebook, or twitter...). Since this site is doing it, somebody here probably has some pretty good insight on the subject. :-)

Sorry this was so long, and more a question than an answer - but Karl's remark made it seem like the most appropriate place to post amidst the volume of threads on OAuth and OpenID. If there's a better place for this that I didn't find, I apologize in advance, I did try.

How to get pip to work behind a proxy server

at least pip3 also works without "=", however, instead of "http" you might need "https"

Final command, which worked for me:

sudo pip3 install --proxy https://{proxy}:{port} {BINARY}

How can I declare and define multiple variables in one line using C++?

If you declare one variable/object per line not only does it solve this problem, but it makes the code clearer and prevents silly mistakes when declaring pointers.

To directly answer your question though, you have to initialize each variable to 0 explicitly. int a = 0, b = 0, c = 0;.

Android ListView with different layouts for each row

Take a look in the code below.

First, we create custom layouts. In this case, four types.

even.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ff500000"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/white"
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:textSize="24sp"
        android:layout_height="wrap_content" />

 </LinearLayout>

odd.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ff001f50"
    android:gravity="right"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:textSize="28sp"
        android:layout_height="wrap_content"  />

 </LinearLayout>

white.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ffffffff"
    android:gravity="right"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/black"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:textSize="28sp"
        android:layout_height="wrap_content"   />

 </LinearLayout>

black.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ff000000"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:textSize="33sp"
        android:layout_height="wrap_content"   />

 </LinearLayout>

Then, we create the listview item. In our case, with a string and a type.

public class ListViewItem {
        private String text;
        private int type;

        public ListViewItem(String text, int type) {
            this.text = text;
            this.type = type;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

    }

After that, we create a view holder. It's strongly recommended because Android OS keeps the layout reference to reuse your item when it disappears and appears back on the screen. If you don't use this approach, every single time that your item appears on the screen Android OS will create a new one and causing your app to leak memory.

public class ViewHolder {
        TextView text;

        public ViewHolder(TextView text) {
            this.text = text;
        }

        public TextView getText() {
            return text;
        }

        public void setText(TextView text) {
            this.text = text;
        }

    }

Finally, we create our custom adapter overriding getViewTypeCount() and getItemViewType(int position).

public class CustomAdapter extends ArrayAdapter {

        public static final int TYPE_ODD = 0;
        public static final int TYPE_EVEN = 1;
        public static final int TYPE_WHITE = 2;
        public static final int TYPE_BLACK = 3;

        private ListViewItem[] objects;

        @Override
        public int getViewTypeCount() {
            return 4;
        }

        @Override
        public int getItemViewType(int position) {
            return objects[position].getType();
        }

        public CustomAdapter(Context context, int resource, ListViewItem[] objects) {
            super(context, resource, objects);
            this.objects = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;
            ListViewItem listViewItem = objects[position];
            int listViewItemType = getItemViewType(position);


            if (convertView == null) {

                if (listViewItemType == TYPE_EVEN) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_even, null);
                } else if (listViewItemType == TYPE_ODD) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_odd, null);
                } else if (listViewItemType == TYPE_WHITE) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_white, null);
                } else {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_black, null);
                }

                TextView textView = (TextView) convertView.findViewById(R.id.text);
                viewHolder = new ViewHolder(textView);

                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.getText().setText(listViewItem.getText());

            return convertView;
        }

    }

And our activity is something like this:

private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main); // here, you can create a single layout with a listview

        listView = (ListView) findViewById(R.id.listview);

        final ListViewItem[] items = new ListViewItem[40];

        for (int i = 0; i < items.length; i++) {
            if (i == 4) {
                items[i] = new ListViewItem("White " + i, CustomAdapter.TYPE_WHITE);
            } else if (i == 9) {
                items[i] = new ListViewItem("Black " + i, CustomAdapter.TYPE_BLACK);
            } else if (i % 2 == 0) {
                items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_EVEN);
            } else {
                items[i] = new ListViewItem("ODD " + i, CustomAdapter.TYPE_ODD);
            }
        }

        CustomAdapter customAdapter = new CustomAdapter(this, R.id.text, items);
        listView.setAdapter(customAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                Toast.makeText(getBaseContext(), items[i].getText(), Toast.LENGTH_SHORT).show();
            }
        });

    }
}

now create a listview inside mainactivity.xml like this

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.shivnandan.gygy.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <ListView
        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:id="@+id/listView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"


        android:layout_marginTop="100dp" />

</android.support.design.widget.CoordinatorLayout>

Scroll to element on click in Angular 4

Here is how I did it using Angular 4.

Template

<div class="col-xs-12 col-md-3">
  <h2>Categories</h2>
  <div class="cat-list-body">
    <div class="cat-item" *ngFor="let cat of web.menu | async">
      <label (click)="scroll('cat-'+cat.category_id)">{{cat.category_name}}</label>
    </div>
  </div>
</div>

add this function to the Component.

scroll(id) {
  console.log(`scrolling to ${id}`);
  let el = document.getElementById(id);
  el.scrollIntoView();
}

Hiding the scroll bar on an HTML page

Cross browser approach to hiding the scrollbar.

It was tested on Edge, Chrome, Firefox, and Safari

Hide scrollbar while still being able to scroll with mouse wheel!

Codepen

/* Make parent invisible */
#parent {
    visibility: hidden;
    overflow: scroll;
}

/* Safari and Chrome specific style. Don't need to make parent invisible, because we can style WebKit scrollbars */
#parent:not(*:root) {
  visibility: visible;
}

/* Make Safari and Chrome scrollbar invisible */
#parent::-webkit-scrollbar {
  visibility: hidden;
}

/* Make the child visible */
#child {
    visibility: visible;
}

Generate random numbers uniformly over an entire range

The solution given by man 3 rand for a number between 1 and 10 inclusive is:

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

In your case, it would be:

j = min + (int) ((max-min+1) * (rand() / (RAND_MAX + 1.0)));

Of course, this is not perfect randomness or uniformity as some other messages are pointing out, but this is enough for most cases.

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

jQuery ajax upload file in asp.net mvc

I have a sample like this on vuejs version: v2.5.2

<form action="url" method="post" enctype="multipart/form-data">
    <div class="col-md-6">
        <input type="file" class="image_0" name="FilesFront" ref="FilesFront" />
    </div>
    <div class="col-md-6">
        <input type="file" class="image_1" name="FilesBack" ref="FilesBack" />
    </div>
</form>
<script>
Vue.component('v-bl-document', {
    template: '#document-item-template',
    props: ['doc'],
    data: function () {
        return {
            document: this.doc
        };
    },
    methods: {
        submit: function () {
            event.preventDefault();

            var data = new FormData();
            var _doc = this.document;
            Object.keys(_doc).forEach(function (key) {
                data.append(key, _doc[key]);
            });
            var _refs = this.$refs;
            Object.keys(_refs).forEach(function (key) {
                data.append(key, _refs[key].files[0]);
            });

            debugger;
            $.ajax({
                type: "POST",
                data: data,
                url: url,
                cache: false,
                contentType: false,
                processData: false,
                success: function (result) {
                    //do something
                },

            });
        }
    }
});
</script>

Change the spacing of tick marks on the axis of a plot?

I have a data set with Time as the x-axis, and Intensity as y-axis. I'd need to first delete all the default axes except the axes' labels with:

plot(Time,Intensity,axes=F)

Then I rebuild the plot's elements with:

box() # create a wrap around the points plotted
axis(labels=NA,side=1,tck=-0.015,at=c(seq(from=0,to=1000,by=100))) # labels = NA prevents the creation of the numbers and tick marks, tck is how long the tick mark is.
axis(labels=NA,side=2,tck=-0.015)
axis(lwd=0,side=1,line=-0.4,at=c(seq(from=0,to=1000,by=100))) # lwd option sets the tick mark to 0 length because tck already takes care of the mark
axis(lwd=0,line=-0.4,side=2,las=1) # las changes the direction of the number labels to horizontal instead of vertical.

So, at = c(...) specifies the collection of positions to put the tick marks. Here I'd like to put the marks at 0, 100, 200,..., 1000. seq(from =...,to =...,by =...) gives me the choice of limits and the increments.

How to get a variable name as a string in PHP?

Many replies question the usefulness of this. However, getting a reference for a variable can be very useful. Especially in cases with objects and $this. My solution works with objects, and as property defined objects as well:

function getReference(&$var)
{
    if(is_object($var))
        $var->___uniqid = uniqid();
    else
        $var = serialize($var);
    $name = getReference_traverse($var,$GLOBALS);
    if(is_object($var))
        unset($var->___uniqid);
    else
        $var = unserialize($var);
    return "\${$name}";    
}

function getReference_traverse(&$var,$arr)
{
    if($name = array_search($var,$arr,true))
        return "{$name}";
    foreach($arr as $key=>$value)
        if(is_object($value))
            if($name = getReference_traverse($var,get_object_vars($value)))
                return "{$key}->{$name}";
}

Example for the above:

class A
{
    public function whatIs()
    {
        echo getReference($this);
    }
}

$B = 12;
$C = 12;
$D = new A;

echo getReference($B)."<br/>"; //$B
echo getReference($C)."<br/>"; //$C
$D->whatIs(); //$D

Download multiple files as a zip-file using php

You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:

$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  $zip->addFile($file);
}
$zip->close();

and to stream it:

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.

Blurry text after using CSS transform: scale(); in Chrome

I have tried a lot of examples from these answers unfortunately nothing help for Chrome Version 81.0.4044.138 I have added to transforming element instead

 transform-origin: 50% 50%;

this one

 transform-origin: 51% 51%;

it helps for me

Most efficient way to prepend a value to an array

I'm not sure about more efficient in terms of big-O but certainly using the unshift method is more concise:

var a = [1, 2, 3, 4];
a.unshift(0);
a; // => [0, 1, 2, 3, 4]

[Edit]

This jsPerf benchmark shows that unshift is decently faster in at least a couple of browsers, regardless of possibly different big-O performance if you are ok with modifying the array in-place. If you really can't mutate the original array then you would do something like the below snippet, which doesn't seem to be appreciably faster than your solution:

a.slice().unshift(0); // Use "slice" to avoid mutating "a".

[Edit 2]

For completeness, the following function can be used instead of OP's example prependArray(...) to take advantage of the Array unshift(...) method:

function prepend(value, array) {
  var newArray = array.slice();
  newArray.unshift(value);
  return newArray;
}

var x = [1, 2, 3];
var y = prepend(0, x);
y; // => [0, 1, 2, 3];
x; // => [1, 2, 3];

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

How to increase dbms_output buffer?

Here you go:

DECLARE
BEGIN
  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !
END;

Bootstrap change div order with pull-right, pull-left on 3 columns

Try this...

<div class="row">
    <div class="col-xs-3">
        Menu
    </div>
    <div class="col-xs-9">
        <div class="row">
          <div class="col-sm-4 col-sm-push-8">
          Right content
          </div>
          <div class="col-sm-8 col-sm-pull-4">
          Content
          </div>
       </div>
    </div>
</div>

Bootply

"Unorderable types: int() < str()"

The issue here is that input() returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.

To fix this, simply call int() to convert your string to an integer:

int(input(...))

As a note, if you want to deal with decimal numbers, you will want to use one of float() or decimal.Decimal() (depending on your accuracy and speed needs).

Note that the more pythonic way of looping over a series of numbers (as opposed to a while loop and counting) is to use range(). For example:

def main():
    print("Let me Retire Financial Calculator")
    deposit = float(input("Please input annual deposit in dollars: $"))
    rate = int(input ("Please input annual rate in percentage: %")) / 100
    time = int(input("How many years until retirement?"))
    value = 0
    for x in range(1, time+1):
        value = (value * rate) + deposit
        print("The value of your account after" + str(x) + "years will be $" + str(value))

How to refer to Excel objects in Access VBA?

First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.

After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:

Dim xlApp as Excel.Application

Let's say you added an Excel Workbook Object in your Form and named it xLObject.

Here is how you Access a Sheet of this Object and change a Range

Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"

(I copied the above from my answer to this question)

Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)

How to list all the files in a commit?

Preferred Way (because it's a plumbing command; meant to be programmatic):

$ git diff-tree --no-commit-id --name-only -r bd61ad98
index.html
javascript/application.js
javascript/ie6.js

Another Way (less preferred for scripts, because it's a porcelain command; meant to be user-facing)

$ git show --pretty="" --name-only bd61ad98    
index.html
javascript/application.js
javascript/ie6.js

  • The --no-commit-id suppresses the commit ID output.
  • The --pretty argument specifies an empty format string to avoid the cruft at the beginning.
  • The --name-only argument shows only the file names that were affected (Thanks Hank). Use --name-status instead, if you want to see what happened to each file (Deleted, Modified, Added)
  • The -r argument is to recurse into sub-trees

Switching users inside Docker image to a non-root user

Add this line to docker file

USER <your_user_name>

Use docker instruction USER

Checkboxes in web pages – how to make them bigger?

I'm writtinga phonegap app, and checkboxes vary in size, look, etc. So I made my own simple checkbox:

First the HTML code:

<span role="checkbox"/>

Then the CSS:

[role=checkbox]{
    background-image: url(../img/checkbox_nc.png);
    height: 15px;
    width: 15px;
    display: inline-block;
    margin: 0 5px 0 5px;
    cursor: pointer;
}

.checked[role=checkbox]{
    background-image: url(../img/checkbox_c.png);
}

To toggle checkbox state, I used JQuery:

CLICKEVENT='touchend';
function createCheckboxes()
{
    $('[role=checkbox]').bind(CLICKEVENT,function()
    {
        $(this).toggleClass('checked');
    });
}

But It can easily be done without it...

Hope it can help!

How to create a laravel hashed password

The Laravel Hash facade provides secure Bcrypt hashing for storing user passwords.

Basic usage required two things:

First include the Facade in your file

use Illuminate\Support\Facades\Hash;

and use Make Method to generate password.

$hashedPassword = Hash::make($request->newPassword);

and when you want to match the Hashed string you can use the below code:

Hash::check($request->newPasswordAtLogin, $hashedPassword)

You can learn more with the Laravel document link below for Hashing: https://laravel.com/docs/5.5/hashing

How to get SQL from Hibernate Criteria API (*not* for logging)

Here is a method I used and worked for me

public static String toSql(Session session, Criteria criteria){
    String sql="";
    Object[] parameters = null;
    try{
        CriteriaImpl c = (CriteriaImpl) criteria;
        SessionImpl s = (SessionImpl)c.getSession();
        SessionFactoryImplementor factory = (SessionFactoryImplementor)s.getSessionFactory();
        String[] implementors = factory.getImplementors( c.getEntityOrClassName() );
        CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable)factory.getEntityPersister(implementors[0]), factory, c, implementors[0], s.getEnabledFilters());
        Field f = OuterJoinLoader.class.getDeclaredField("sql");
        f.setAccessible(true);
        sql = (String)f.get(loader);
        Field fp = CriteriaLoader.class.getDeclaredField("traslator");
        fp.setAccessible(true);
        CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
        parameters = translator.getQueryParameters().getPositionalParameterValues();
    }
    catch(Exception e){
        throw new RuntimeException(e);
    }
    if (sql !=null){
        int fromPosition = sql.indexOf(" from ");
        sql = "SELECT * "+ sql.substring(fromPosition);

        if (parameters!=null && parameters.length>0){
            for (Object val : parameters) {
                String value="%";
                if(val instanceof Boolean){
                    value = ((Boolean)val)?"1":"0";
                }else if (val instanceof String){
                    value = "'"+val+"'";
                }
                sql = sql.replaceFirst("\\?", value);
            }
        }
    }
    return sql.replaceAll("left outer join", "\nleft outer join").replace(" and ", "\nand ").replace(" on ", "\non ");
}

python: order a list of numbers without built-in sort, min, max function

Here's a more readable example of an in-place Insertion sort algorithm.

a = [3, 1, 5, 2, 4]

for i in a[1:]:
    j = a.index(i)
    while j > 0 and a[j-1] > a[j]:
        a[j], a[j-1] = a[j-1], a[j]
        j = j - 1

How to log SQL statements in Spring Boot?

We can use any one of these in application.properties file:

spring.jpa.show-sql=true 

example :
//Hibernate: select country0_.id as id1_0_, country0_.name as name2_0_ from country country0_

or

logging.level.org.hibernate.SQL=debug 

example :
2018-11-23 12:28:02.990 DEBUG 12972 --- [nio-8086-exec-2] org.hibernate.SQL   : select country0_.id as id1_0_, country0_.name as name2_0_ from country country0_

Syntax for async arrow function

This the simplest way to assign an async arrow function expression to a named variable:

const foo = async () => {
  // do something
}

(Note that this is not strictly equivalent to async function foo() { }. Besides the differences between the function keyword and an arrow expression, the function in this answer is not "hoisted to the top".)

How can I pass a parameter to a Java Thread?

To create a thread you normally create your own implementation of Runnable. Pass the parameters to the thread in the constructor of this class.

class MyThread implements Runnable{
   private int a;
   private String b;
   private double c;

   public MyThread(int a, String b, double c){
      this.a = a;
      this.b = b;
      this.c = c;
   }

   public void run(){
      doSomething(a, b, c);
   }
}

Wait Until File Is Completely Written

There is only workaround for the issue you are facing.

Check whether file id in process before starting the process of copy. You can call the following function until you get the False value.

1st Method, copied directly from this answer:

private bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

2nd Method:

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(string file)
{
    //check that problem is not in destination file
    if (File.Exists(file) == true)
    {
        FileStream stream = null;
        try
        {
            stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (Exception ex2)
        {
            //_log.WriteLog(ex2, "Error in checking whether file is locked " + file);
            int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1);
            if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION))
            {
                return true;
            }
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }
    }
    return false;
}

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

My JavaDude Bean Annotation Processor generates code to do this.

http://javadude.googlecode.com

For example:

@Bean(
  createPropertyMap=true,
  properties={
    @Property(name="name"),
    @Property(name="phone", bound=true),
    @Property(name="friend", type=Person.class, kind=PropertyKind.LIST)
  }
)
public class Person extends PersonGen {}

The above generates superclass PersonGen that includes a createPropertyMap() method that generates a Map for all properties defined using @Bean.

(Note that I'm changing the API slightly for the next version -- the annotation attribute will be defineCreatePropertyMap=true)

How to create a temporary directory?

Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.

check for null date in CASE statement, where have I gone wrong?

Try:

select
     id,
     StartDate,
CASE WHEN StartDate IS NULL
    THEN 'Awaiting'
    ELSE 'Approved' END AS StartDateStatus
FROM myTable

You code would have been doing a When StartDate = NULL, I think.


NULL is never equal to NULL (as NULL is the absence of a value). NULL is also never not equal to NULL. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL.

You can run the following:

SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison

And this returns:

EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1

For completeness, in SQL Server you can:

SET ANSI_NULLS OFF;

Which would result in your equals comparisons working differently:

SET ANSI_NULLS OFF

SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison

Which returns:

EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1

But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...

Also, it will no longer work in upcoming versions of SQL server:

https://msdn.microsoft.com/en-GB/library/ms188048.aspx

how does unix handle full path name with space and arguments?

You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.

/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture

"/Applications/Image Capture.app/Contents/MacOS/Image Capture"

/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"

All refer to the same executable under Mac OS X.

I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.

Remove all occurrences of char from string

Hello Try this code below

public class RemoveCharacter {

    public static void main(String[] args){
        String str = "MXy nameX iXs farXazX";
        char x = 'X';
        System.out.println(removeChr(str,x));
    }

    public static String removeChr(String str, char x){
        StringBuilder strBuilder = new StringBuilder();
        char[] rmString = str.toCharArray();
        for(int i=0; i<rmString.length; i++){
            if(rmString[i] == x){

            } else {
                strBuilder.append(rmString[i]);
            }
        }
        return strBuilder.toString();
    }
}

AppStore - App status is ready for sale, but not in app store

you must change Territory and click on save, after one minute your app will be available. No need to Remove from sale

no target device found android studio 2.1.1

try with

sudo adb kill-server
sudo devices

or

echo $ANDROID_HOME
sudo $ANDROID_HOME/platform-tools/adb kill-server 
sudo $ANDROID_HOME/platform-tools/adb devices

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

Create a File object in memory from a string in Java

No; instances of class File represent a path in a filesystem. Therefore, you can use that function only with a file. But perhaps there is an overload that takes an InputStream instead?

error: ‘NULL’ was not declared in this scope

NULL isn't a keyword; it's a macro substitution for 0, and comes in stddef.h or cstddef, I believe. You haven't #included an appropriate header file, so g++ sees NULL as a regular variable name, and you haven't declared it.

Git blame -- prior commits?

Building on DavidN's answer and I want to follow renamed file:

LINE=8 FILE=Info.plist; for commit in $(git log --format='%h%%' --name-only --follow -- $FILE | xargs echo | perl -pe 's/\%\s/,/g'); do hash=$(echo $commit | cut -f1 -d ','); fileMayRenamed=$(echo $commit | cut -f2 -d ','); git blame -n -L$LINE,+1 $hash -- $fileMayRenamed; done | sed '$!N; /^\(.*\)\n\1$/!P; D'

ref: nicely display file rename history in git log

How do I return JSON without using a template in Django?

For rendering my models in JSON in django 1.9 I had to do the following in my views.py:

from django.core import serializers
from django.http import HttpResponse
from .models import Mymodel

def index(request):
    objs = Mymodel.objects.all()
    jsondata = serializers.serialize('json', objs)
    return HttpResponse(jsondata, content_type='application/json')

Differences between Ant and Maven

Maven also houses a large repository of commonly used open source projects. During the build Maven can download these dependencies for you (as well as your dependencies dependencies :)) to make this part of building a project a little more manageable.

When should you NOT use a Rules Engine?

I don't really understand some points such as :
a) business people needs to understand business very well, or;
b) disagreement on business people don't need to know the rule.

For me, as a people just touching BRE, the benefit of BRE is so called to let system adapt to business change, hence it's focused on adaptive of change.
Does it matter if the rule set up at time x is different from the rule set up at time y because of:
a) business people don't understand business, or;
b) business people don't understand rules?

Python handling socket.error: [Errno 104] Connection reset by peer

You can try to add some time.sleep calls to your code.

It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.

In order to avoid your code from crashing, try to catch this error with try .. except around the urllib2 calls.

How can I initialize an ArrayList with all zeroes in Java?

// apparently this is broken. Whoops for me!
java.util.Collections.fill(list,new Integer(0));

// this is better
Integer[] data = new Integer[60];
Arrays.fill(data,new Integer(0));
List<Integer> list = Arrays.asList(data);

Get size of a View in React Native

You can directly use the Dimensions module and calc your views sizes. Actually, Dimensions give to you the main window sizes.

import { Dimensions } from 'Dimensions';

Dimensions.get('window').height;
Dimensions.get('window').width;

Hope to help you!

Update: Today using native StyleSheet with Flex arranging on your views help to write clean code with elegant layout solutions in wide cases instead computing your view sizes...

Although building a custom grid components, which responds to main window resize events, could produce a good solution in simple widget components

z-index issue with twitter bootstrap dropdown menu

Solved by removing the -webkit-transform from the navbar:

-webkit-transform: translate3d(0, 0, 0);

pillaged from https://stackoverflow.com/a/12653766/391925

Android: Storing username and password?

Most Android and iPhone apps I have seen use an initial screen or dialog box to ask for credentials. I think it is cumbersome for the user to have to re-enter their name/password often, so storing that info makes sense from a usability perspective.

The advice from the (Android dev guide) is:

In general, we recommend minimizing the frequency of asking for user credentials -- to make phishing attacks more conspicuous, and less likely to be successful. Instead use an authorization token and refresh it.

Where possible, username and password should not be stored on the device. Instead, perform initial authentication using the username and password supplied by the user, and then use a short-lived, service-specific authorization token.

Using the AccountManger is the best option for storing credentials. The SampleSyncAdapter provides an example of how to use it.

If this is not an option to you for some reason, you can fall back to persisting credentials using the Preferences mechanism. Other applications won't be able to access your preferences, so the user's information is not easily exposed.

how to take user input in Array using java?

You can do the following:

    import java.util.Scanner;

    public class Test {

            public static void main(String[] args) {

            int arr[];
            Scanner scan = new Scanner(System.in);
            // If you want to take 5 numbers for user and store it in an int array
            for(int i=0; i<5; i++) {
                System.out.print("Enter number " + (i+1) + ": ");
                arr[i] = scan.nextInt();    // Taking user input
            }

            // For printing those numbers
            for(int i=0; i<5; i++) 
                System.out.println("Number " + (i+1) + ": " + arr[i]);
        }
    }

How do I move a file from one location to another in Java?

To move a file you could also use Jakarta Commons IOs FileUtils.moveFile

On error it throws an IOException, so when no exception is thrown you know that that the file was moved.

Unable instantiate android.gms.maps.MapFragment

I've this issue i just update Google Play services and make sure that you are adding the google-play-service-lib project as dependency, it's working now without any code change but i still getting "The Google Play services resources were not found. Check your project configuration to ensure that the resources are included." but this only happens when you have setMyLocationEnabled(true), anyone knows why?

How to return part of string before a certain character?

Another method could be to split the string by ":" and then pop off the end. var newString = string.split(":").pop();

Determining the size of an Android view at runtime

There are actually multiple solutions, depending on the scenario:

  1. The safe method, will work just before drawing the view, after the layout phase has finished:
public static void runJustBeforeBeingDrawn(final View view, final Runnable runnable) {
    final OnPreDrawListener preDrawListener = new OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            runnable.run();
            return true;
        }
    };
    view.getViewTreeObserver().addOnPreDrawListener(preDrawListener); 
}

Sample usage:

    ViewUtil.runJustBeforeBeingDrawn(yourView, new Runnable() {
        @Override
        public void run() {
            //Here you can safely get the view size (use "getWidth" and "getHeight"), and do whatever you wish with it
        }
    });
  1. On some cases, it's enough to measure the size of the view manually:
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width=view.getMeasuredWidth(); 
int height=view.getMeasuredHeight();

If you know the size of the container:

    val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(maxWidth, View.MeasureSpec.AT_MOST)
    val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(maxHeight, View.MeasureSpec.AT_MOST)
    view.measure(widthMeasureSpec, heightMeasureSpec)
    val width=view.measuredWidth
    val height=view.measuredHeight
  1. if you have a custom view that you've extended, you can get its size on the "onMeasure" method, but I think it works well only on some cases :
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
    final int newHeight= MeasureSpec.getSize(heightMeasureSpec);
    final int newWidth= MeasureSpec.getSize(widthMeasureSpec);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
  1. If you write in Kotlin, you can use the next function, which behind the scenes works exactly like runJustBeforeBeingDrawn that I've written:

     view.doOnPreDraw { actionToBeTriggered() }
    

Note that you need to add this to gradle (found via here) :

android {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

implementation 'androidx.core:core-ktx:#.#'

MySQL count occurrences greater than 2

To get a list of the words that appear more than once together with how often they occur, use a combination of GROUP BY and HAVING:

SELECT word, COUNT(*) AS cnt
FROM words
GROUP BY word
HAVING cnt > 1

To find the number of words in the above result set, use that as a subquery and count the rows in an outer query:

SELECT COUNT(*)
FROM
(
    SELECT NULL
    FROM words
    GROUP BY word
    HAVING COUNT(*) > 1
) T1

How can I upload fresh code at github?

If you haven't already created the project in Github, do so on that site. If memory serves, they display a page that tells you exactly how to get your existing code into your new repository. At the risk of oversimplification, though, you'd follow Veeti's instructions, then:

git remote add [name to use for remote] [private URI] # associate your local repository to the remote
git push [name of remote] master # push your repository to the remote

What's the difference between map() and flatMap() methods in Java 8?

map() and flatMap()

  1. map()

Just takes a Function a lambda param where T is element and R the return element built using T. At the end we'll have a Stream with objects of Type R. A simple example can be:

Stream
  .of(1,2,3,4,5)
  .map(myInt -> "preFix_"+myInt)
  .forEach(System.out::println);

It simply takes elements 1 to 5 of Type Integer, uses each element to build a new element from type String with value "prefix_"+integer_value and prints it out.

  1. flatMap()

It is useful to know that flatMap() takes a function F<T, R> where

  • T is a type from which a Stream can be built from/with. It can be a List (T.stream()), an array (Arrays.stream(someArray)), etc.. anything that from which a Stream can be with/or form. in the example below each dev has many languages, so dev. Languages is a List and will use a lambda parameter.

  • R is the resulting Stream that will be built using T. Knowing that we have many instances of T, we will naturally have many Streams from R. All these Streams from Type R will now be combined into one single 'flat' Stream from Type R.

Example

The examples of Bachiri Taoufiq see its answer here are simple and easy to understanding. Just for clarity, let just say we have a team of developers:

dev_team = {dev_1,dev_2,dev_3}

, with each developer knowing many languages:

dev_1 = {lang_a,lang_b,lang_c},
dev_2 = {lang_d},
dev_2 = {lang_e,lang_f}

Applying Stream.map() on dev_team to get the languages of each dev:

dev_team.map(dev -> dev.getLanguages())

will give you this structure:

{ 
  {lang_a,lang_b,lang_c},
  {lang_d},
  {lang_e,lang_f}
}

which is basically a List<List<Languages>> /Object[Languages[]]. Not so very pretty, nor Java8-like!!

with Stream.flatMap() you can 'flatten' things out as it takes the above structure
and turns it into {lang_a, lang_b, lang_c, lang_d, lang_e, lang_f}, which can basically used as List<Languages>/Language[]/etc...

so in the end, your code would make more sense like this:

dev_team
   .stream()    /* {dev_1,dev_2,dev_3} */
   .map(dev -> dev.getLanguages()) /* {{lang_a,...,lang_c},{lang_d}{lang_e,lang_f}}} */
   .flatMap(languages ->  languages.stream()) /* {lang_a,...,lang_d, lang_e, lang_f} */
   .doWhateverWithYourNewStreamHere();

or simply:

dev_team
       .stream()    /* {dev_1,dev_2,dev_3} */
       .flatMap(dev -> dev.getLanguages().stream()) /* {lang_a,...,lang_d, lang_e, lang_f} */
       .doWhateverWithYourNewStreamHere();

When to use map() and use flatMap():

  • Use map() when each element of type T from your stream is supposed to be mapped/transformed to a single element of type R. The result is a mapping of type (1 start element -> 1 end element) and new stream of elements of type R is returned.

  • Use flatMap() when each element of type T from your stream is supposed to mapped/transformed to a Collections of elements of type R. The result is a mapping of type (1 start element -> n end elements). These Collections are then merged (or flattened) to a new stream of elements of type R. This is useful for example to represent nested loops.

Pre Java 8:

List<Foo> myFoos = new ArrayList<Foo>();
    for(Foo foo: myFoos){
        for(Bar bar:  foo.getMyBars()){
            System.out.println(bar.getMyName());
        }
    }

Post Java 8

myFoos
    .stream()
    .flatMap(foo -> foo.getMyBars().stream())
    .forEach(bar -> System.out.println(bar.getMyName()));

How to install PyQt4 in anaconda?

It looks like the latest version of anaconda forces install of pyqt5.6 over any pyqt build, which will be fatal for your applications. In a terminal, Try:

conda install -c anaconda pyqt=4.11.4

It will prompt to downgrade conda client. After that, it should be good.

UPDATE: If you want to know what pyqt versions are available for install, try:

conda search pyqt

UPDATE: The most recent version of conda installs anaconda-navigator. This depends on qt5, and should first be removed:

conda uninstall anaconda-navigator

Then install "newest" qt4:

conda install qt=4

How to use WebRequest to POST some data and read response?

Below is the code that read the data from the text file and sends it to the handler for processing and receive the response data from the handler and read it and store the data in the string builder class

 //Get the data from text file that needs to be sent.
                FileStream fileStream = new FileStream(@"G:\Papertest.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                byte[] buffer = new byte[fileStream.Length];
                int count = fileStream.Read(buffer, 0, buffer.Length);

                //This is a handler would recieve the data and process it and sends back response.
                WebRequest myWebRequest = WebRequest.Create(@"http://localhost/Provider/ProcessorHandler.ashx");

                myWebRequest.ContentLength = buffer.Length;
                myWebRequest.ContentType = "application/octet-stream";
                myWebRequest.Method = "POST";
                // get the stream object that holds request stream.
                Stream stream = myWebRequest.GetRequestStream();
                       stream.Write(buffer, 0, buffer.Length);
                       stream.Close();

                //Sends a web request and wait for response.
                try
                {
                    WebResponse webResponse = myWebRequest.GetResponse();
                    //get Stream Data from the response
                    Stream respData = webResponse.GetResponseStream();
                    //read the response from stream.
                    StreamReader streamReader = new StreamReader(respData);
                    string name;
                    StringBuilder str = new StringBuilder();
                    while ((name = streamReader.ReadLine()) != null)
                    {
                        str.Append(name); // Add to stringbuider when response contains multple lines data
                   }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

npm command to uninstall or prune unused packages in Node.js

You can use npm-prune to remove extraneous packages.

npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.

If the --dry-run flag is used then no changes will actually be made.

If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.

In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.

If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.

Use npm-dedupe to reduce duplication

npm dedupe
npm ddp

Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.

For example, consider this dependency graph:

a
+-- b <-- depends on [email protected]
|    `-- [email protected]
`-- d <-- depends on c@~1.0.9
     `-- [email protected]

In this case, npm-dedupe will transform the tree to:

 a
 +-- b
 +-- d
 `-- [email protected]

Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.

The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.

How do I subtract minutes from a date in javascript?

moment.js has some really nice convenience methods to manipulate date objects

The .subtract method, allows you to subtract a certain amount of time units from a date, by providing the amount and a timeunit string.

var now = new Date();
// Sun Jan 22 2017 17:12:18 GMT+0200 ...
var olderDate = moment(now).subtract(3, 'minutes').toDate();
// Sun Jan 22 2017 17:09:18 GMT+0200 ...

Convert Mongoose docs to json

Try this options:

  UserModel.find({}, function (err, users) {
    //i got into errors using so i changed to res.send()
    return res.send( JSON.parse(JSON.stringify(users)) );
    //Or
    //return JSON.parse(JSON.stringify(users));
  }

How to upload a file in Django?

Phew, Django documentation really does not have good example about this. I spent over 2 hours to dig up all the pieces to understand how this works. With that knowledge I implemented a project that makes possible to upload files and show them as list. To download source for the project, visit https://github.com/axelpale/minimal-django-file-upload-example or clone it:

> git clone https://github.com/axelpale/minimal-django-file-upload-example.git

Update 2013-01-30: The source at GitHub has also implementation for Django 1.4 in addition to 1.3. Even though there is few changes the following tutorial is also useful for 1.4.

Update 2013-05-10: Implementation for Django 1.5 at GitHub. Minor changes in redirection in urls.py and usage of url template tag in list.html. Thanks to hubert3 for the effort.

Update 2013-12-07: Django 1.6 supported at GitHub. One import changed in myapp/urls.py. Thanks goes to Arthedian.

Update 2015-03-17: Django 1.7 supported at GitHub, thanks to aronysidoro.

Update 2015-09-04: Django 1.8 supported at GitHub, thanks to nerogit.

Update 2016-07-03: Django 1.9 supported at GitHub, thanks to daavve and nerogit

Project tree

A basic Django 1.3 project with single app and media/ directory for uploads.

minimal-django-file-upload-example/
    src/
        myproject/
            database/
                sqlite.db
            media/
            myapp/
                templates/
                    myapp/
                        list.html
                forms.py
                models.py
                urls.py
                views.py
            __init__.py
            manage.py
            settings.py
            urls.py

1. Settings: myproject/settings.py

To upload and serve files, you need to specify where Django stores uploaded files and from what URL Django serves them. MEDIA_ROOT and MEDIA_URL are in settings.py by default but they are empty. See the first lines in Django Managing Files for details. Remember also set the database and add myapp to INSTALLED_APPS

...
import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'database.sqlite3'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}
...
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
...
INSTALLED_APPS = (
    ...
    'myapp',
)

2. Model: myproject/myapp/models.py

Next you need a model with a FileField. This particular field stores files e.g. to media/documents/2011/12/24/ based on current date and MEDIA_ROOT. See FileField reference.

# -*- coding: utf-8 -*-
from django.db import models

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

3. Form: myproject/myapp/forms.py

To handle upload nicely, you need a form. This form has only one field but that is enough. See Form FileField reference for details.

# -*- coding: utf-8 -*-
from django import forms

class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file',
        help_text='max. 42 megabytes'
    )

4. View: myproject/myapp/views.py

A view where all the magic happens. Pay attention how request.FILES are handled. For me, it was really hard to spot the fact that request.FILES['docfile'] can be saved to models.FileField just like that. The model's save() handles the storing of the file to the filesystem automatically.

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from myproject.myapp.models import Document
from myproject.myapp.forms import DocumentForm

def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )

5. Project URLs: myproject/urls.py

Django does not serve MEDIA_ROOT by default. That would be dangerous in production environment. But in development stage, we could cut short. Pay attention to the last line. That line enables Django to serve files from MEDIA_URL. This works only in developement stage.

See django.conf.urls.static.static reference for details. See also this discussion about serving media files.

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    (r'^', include('myapp.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

6. App URLs: myproject/myapp/urls.py

To make the view accessible, you must specify urls for it. Nothing special here.

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

urlpatterns = patterns('myapp.views',
    url(r'^list/$', 'list', name='list'),
)

7. Template: myproject/myapp/templates/myapp/list.html

The last part: template for the list and the upload form below it. The form must have enctype-attribute set to "multipart/form-data" and method set to "post" to make upload to Django possible. See File Uploads documentation for details.

The FileField has many attributes that can be used in templates. E.g. {{ document.docfile.url }} and {{ document.docfile.name }} as in the template. See more about these in Using files in models article and The File object documentation.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Minimal Django File Upload Example</title>   
    </head>
    <body>
    <!-- List of uploaded documents -->
    {% if documents %}
        <ul>
        {% for document in documents %}
            <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>No documents.</p>
    {% endif %}

        <!-- Upload form. Note enctype attribute! -->
        <form action="{% url 'list' %}" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <p>{{ form.non_field_errors }}</p>
            <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
            <p>
                {{ form.docfile.errors }}
                {{ form.docfile }}
            </p>
            <p><input type="submit" value="Upload" /></p>
        </form>
    </body>
</html> 

8. Initialize

Just run syncdb and runserver.

> cd myproject
> python manage.py syncdb
> python manage.py runserver

Results

Finally, everything is ready. On default Django developement environment the list of uploaded documents can be seen at localhost:8000/list/. Today the files are uploaded to /path/to/myproject/media/documents/2011/12/17/ and can be opened from the list.

I hope this answer will help someone as much as it would have helped me.

How to force IE to reload javascript?

In javascript I think that it is not possible, because modern browsers have a policy on security in javascripts.. and clearing the cache is a very violating one.

You can try to add

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">

In your header, but you will have performance loss.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

There is now a new way of addressing this issue - if you remove position: relative from the container which needs to have the overflow-y visible, you can have overflow-y visible and overflow-x hidden, and vice versa (have overflow-x visible and overflow-y hidden, just make sure the container with the visible property is not relatively positioned).

See this post from CSS Tricks for more details - it worked for me: https://css-tricks.com/popping-hidden-overflow/

How to convert a single char into an int

By this way You can convert char to int and int to char easily:

int charToInt(char c)
{
   int arr[]={0,1,2,3,4,5,6,7,8,9};
   return arr[c-'0'];
}

How to open standard Google Map application from my application?

Check this page from google :

http://developer.android.com/guide/appendix/g-app-intents.html

You can use a URI of the form

geo:latitude,longitude

to open Google map viewer and point it to a location.

How to merge a Series and DataFrame

If I could suggest setting up your dataframes like this (auto-indexing):

df = pd.DataFrame({'a':[np.nan, 1, 2], 'b':[4, 5, 6]})

then you can set up your s1 and s2 values thus (using shape() to return the number of rows from df):

s = pd.DataFrame({'s1':[5]*df.shape[0], 's2':[6]*df.shape[0]})

then the result you want is easy:

display (df.merge(s, left_index=True, right_index=True))

Alternatively, just add the new values to your dataframe df:

df = pd.DataFrame({'a':[nan, 1, 2], 'b':[4, 5, 6]})
df['s1']=5
df['s2']=6
display(df)

Both return:

     a  b  s1  s2
0  NaN  4   5   6
1  1.0  5   5   6
2  2.0  6   5   6

If you have another list of data (instead of just a single value to apply), and you know it is in the same sequence as df, eg:

s1=['a','b','c']

then you can attach this in the same way:

df['s1']=s1

returns:

     a  b s1
0  NaN  4  a
1  1.0  5  b
2  2.0  6  c

Random numbers with Math.random() in Java

The first one generates numbers in the wrong range, while the second one is correct.

To show that the first one is incorrect, let's say min is 10 and max is 20. In other words, the result is expected to be greater than or equal to ten, and strictly less than twenty. If Math.random() returns 0.75, the result of the first formula is 25, which is outside the range.

Get everything after and before certain character in SQL Server

use the following function

left(@test, charindex('/', @test) - 1)

invalid byte sequence for encoding "UTF8"

It is also very possible with this error that the field is encrypted in place. Be sure you are looking at the right table, in some cases administrators will create an unencrypted view that you can use instead. I recently encountered a very similar issue.

How to localise a string inside the iOS info.plist file?

For anyone experiencing the problem of the info.plist not being included when trying to add localizations, like in Xcode 9.

You need make the info.plist localiazble by going into it and clicking on the localize button in the file inspector, as shown below.

The info.plist will then be included in the file resources for when you go to add new Localizations.

enter image description here

to_string is not a member of std, says g++ (mingw)

For me, ensuring that I had:

#include <iostream>  
#include<string>  
using namespace std;

in my file made something like to_string(12345) work.

How to access PHP session variables from jQuery function in a .js file?

If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create jquery plugins for your code and then pass the $_SESSION['param'] as a variable.

So in page.php:

<script src="my_progress_bar.js"></script>
<script>
$(function () {
    var percent = <?php echo $_SESSION['percent']; ?>;
    $.my_progress_bar(percent);
});
</script>

Then in my_progress_bar.js:

(function ($) {
    $.my_progress_bar = function(percent) {
        $( "#progressbar" ).progressbar({
            value: percent
        });
    };
})(jQuery);

Getting "project" nuget configuration is invalid error

Simply restarting Visual Studio worked for me.

Using helpers in model: how do I include helper dependencies?

Just change the first line as follows :

include ActionView::Helpers

that will make it works.

UPDATE: For Rails 3 use:

ActionController::Base.helpers.sanitize(str)

Credit goes to lornc's answer

How to execute a java .class from the command line

You need to specify the classpath. This should do it:

java -cp . Echo "hello"

This tells java to use . (the current directory) as its classpath, i.e. the place where it looks for classes. Note than when you use packages, the classpath has to contain the root directory, not the package subdirectories. e.g. if your class is my.package.Echo and the .class file is bin/my/package/Echo.class, the correct classpath directory is bin.

less than 10 add 0 to number

Hope, this help:

Number.prototype.zeroFill= function (n) {
    var isNegative = this < 0;
    var number = isNegative ? -1 * this : this;
    for (var i = number.toString().length; i < n; i++) {
        number = '0' + number;
    }
    return (isNegative ? '-' : '') + number;
}

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 

Italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>

Bold:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>

Bold-italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>

Light:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>

Light-italic:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :

Medium:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>

Medium-italic:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>

Black:

<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

Command-line svn for Windows?

You can get SVN command-line tools with TortoiseSVN 1.7 or later or get a 6.5mb standalone package from VisualSVN.

Starting with TortoiseSVN 1.7, its installer provides you with an option to install the command-line tools.

It also makes sense to check the Apache Subversion "Binary Packages" page. xD

Calling the base constructor in C#

As per some of the other answers listed here, you can pass parameters into the base class constructor. It is advised to call your base class constructor at the beginning of the constructor for your inherited class.

public class MyException : Exception
{
    public MyException(string message, string extraInfo) : base(message)
    {
    }
}

I note that in your example you never made use of the extraInfo parameter, so I assumed you might want to concatenate the extraInfo string parameter to the Message property of your exception (it seems that this is being ignored in the accepted answer and the code in your question).

This is simply achieved by invoking the base class constructor, and then updating the Message property with the extra info.

public class MyException: Exception
{
    public MyException(string message, string extraInfo) : base($"{message} Extra info: {extraInfo}")
    {
    }
}

bash export command

SHELL is an environment variable, and so it's not the most reliable for what you're trying to figure out. If your tool is using a shell which doesn't set it, it will retain its old value.

Use ps to figure out what's really going on.

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

querySelector and querySelectorAll are a relatively new APIs, whereas getElementById and getElementsByClassName have been with us for a lot longer. That means that what you use will mostly depend on which browsers you need to support.

As for the :, it has a special meaning so you have to escape it if you have to use it as a part of a ID/class name.

How do I push to GitHub under a different username?

this, should work: git push origin local-name:remote-name

Better, for GitLab I use a second "origin", say "origin2":

git remote add origin2 ...
then

git push origin2 master

The conventional (short) git push should work implicitly as with the 1st "origin"

Call method when home button pressed

use onPause() method to do what you want to do on home button.

jQuery Get Selected Option From Dropdown

try this code: :)

get value:

 $("#Ostans option:selected").val() + '.' + $("#shahrha option:selected").val()

get text:

 $("#Ostans option:selected").text() + '.' + $("#shahrha option:selected").text()

Send Post Request with params using Retrofit

You should create an interface for that like it is working well

public interface Service {
    @FormUrlEncoded
    @POST("v1/EmergencyRequirement.php/?op=addPatient")
    Call<Result> addPerson(@Field("BloodGroup") String bloodgroup,
           @Field("Address") String Address,
           @Field("City") String city, @Field("ContactNumber") String  contactnumber, 
           @Field("PatientName") String name, 
           @Field("Time") String Time, @Field("DonatedBy") String donar);
}

or you can visit to http://teachmeandroidhub.blogspot.com/2018/08/post-data-using-retrofit-in-android.html

and youcan vist to https://github.com/rajkumu12/GetandPostUsingRatrofit

How do I import material design library to Android Studio?

Goto

  1. File (Top Left Corner)
  2. Project Structure
  3. Under Module. Find the Dependence tab
  4. press plus button (+) at top right.
  5. You will find all the dependencies

Form submit with AJAX passing form data to PHP without page refresh

<div class="container">
       <div class="row">
        <div class="col-md-3 col-sm-6 col-xs-12"></div>enter code here
          <div class="col-md-6 col-sm-6 col-xs-12">
          <div class="msg"></div>
            <form method="post" class="frm" id="form1" onsubmit="">
               <div class="form-group">
               <input type="text" class="form-control" name="fname" id="fname" placeholder="enter your first neme" required>
           <!--><span class="sp"><?php// echo $f_err;?></span><!-->
          </div>
        <div class="form-group">
               <input type="text" class="form-control" name="lname" id="lname" placeholder="enter your last neme" required>
              <!--><span class="sp"><?php// echo $l_err;?></span><!-->
             </div>
              <div class="form-group">
               <input type="text" class="form-control" name="email" id="email" placeholder="enter your email Address" required>
              <!--><span class="sp"><?php// echo $e_err;?></span><!-->
             </div>
             <div class="form-group">
               <input type="number" class="form-control" name="mno" id="mno" placeholder="enter your mobile number" required>
              <!--><span class="sp"><?php //echo $m_err;?></span><!-->
             </div>
              <div class="form-group">
               <input type="password" class="form-control" name="pass" id="pass" pattern="(?=.*[a-z])(?=.*[A-Z]).{4,8}" placeholder="enter your Password" required>
              <!--><span class="sp"><?php //echo $p_err;?></span><!-->
             </div>
              <div class="radio">
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="male" name="gender" id="gender" checked>male<br>
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="female" name="gender" id="gender">female<br>
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="other" name="gender" id="gender">other<br>
                                         <!--><span class="sp"> <?php //echo $r_err;?></span><!-->
             </div>
                <div class="checkbox">
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" name="check" id="check" checked>I Agree Turms&Condition<br>
                   <!--><span class="sp"> <?php //echo $c_err;?></span><!-->
                 </div>
                 <input type="submit"  class="btn btn-warning" name="submit" id="submit">
             </form>enter code here

          </div>
               <div class="col-md-3 col-sm-6 col-xs-12"></div>
         </div> 

    </div>

What is a "web service" in plain English?

Simple way to explain web service is ::

  • A web service is a method of communication between two electronic devices over the World Wide Web.
  • It can be called a process that a programmer uses to communicate with the server
  • To invoke this process programmer can use SOAP etc
  • Web services are built on top of open standards such as TCP/IP, HTTP

The advantage of a webservice is, say you develop one piece of code in .net and you wish to use JAVA to consume this code. You can interact directly with the abstracted layer and are unaware of what technology was used to develop the code.


Image

PHP Session timeout

Just check first the session is not already created and if not create one. Here i am setting it for 1 minute only.

<?php 
   if(!isset($_SESSION["timeout"])){
     $_SESSION['timeout'] = time();
   };
   $st = $_SESSION['timeout'] + 60; //session time is 1 minute
?>

<?php 
  if(time() < $st){
    echo 'Session will last 1 minute';
  }
?>

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

There are a few things you can try to get this working.

  1. Be ABSOLUTELY sure your script is being pulled into the page, one way to check is by using the 'sources' tab in the Chrome Debugger and searching for the file.

  2. Be sure that you've included the script after you've included jQuery, as it is most certainly dependant upon that.

Other than that, I checked out the API and you're definitely doing everything right as far as I can see. Best of luck friend!

EDIT: Ensure you close your script tag. There's an answer below that points to that being the solution.

Slicing a dictionary

Write a dict subclass that accepts a list of keys as an "item" and returns a "slice" of the dictionary:

class SliceableDict(dict):
    default = None
    def __getitem__(self, key):
        if isinstance(key, list):   # use one return statement below
            # uses default value if a key does not exist
            return {k: self.get(k, self.default) for k in key}
            # raises KeyError if a key does not exist
            return {k: self[k] for k in key}
            # omits key if it does not exist
            return {k: self[k] for k in key if k in self}
        return dict.get(self, key)

Usage:

d = SliceableDict({1:2, 3:4, 5:6, 7:8})
d[[1, 5]]   # {1: 2, 5: 6}

Or if you want to use a separate method for this type of access, you can use * to accept any number of arguments:

class SliceableDict(dict):
    def slice(self, *keys):
        return {k: self[k] for k in keys}
        # or one of the others from the first example

d = SliceableDict({1:2, 3:4, 5:6, 7:8})
d.slice(1, 5)     # {1: 2, 5: 6}
keys = 1, 5
d.slice(*keys)    # same

redistributable offline .NET Framework 3.5 installer for Windows 8

You don't have to copy everything to C:\dotnet35. Usually all the files are already copied to the folder C:\Windows\WinSxS. Then the command becomes (assuming Windows was installed to C:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:C:\Windows\WinSxS /LimitAccess" If not you can also point the command to the DVD directly. Then the command becomes (assuming DVD is mounted to D:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:D:\sources\sxs /LimitAccess".

MySQL: determine which database is selected?

In the comments of http://www.php.net/manual/de/function.mysql-db-name.php I found this one from ericpp % bigfoot.com:

If you just need the current database name, you can use MySQL's SELECT DATABASE() command:

<?php
function mysql_current_db() {
    $r = mysql_query("SELECT DATABASE()") or die(mysql_error());
    return mysql_result($r,0);
}
?>

unable to install pg gem

$ PATH=$PATH:/Library/PostgreSQL/9.1/bin sudo gem install pg

replace the 9.1 for the version installed on your system.

"date(): It is not safe to rely on the system's timezone settings..."

I had to put it in double quotes.

date_default_timezone_set("America/Los_Angeles"); // default time zone

Static way to get 'Context' in Android?

Kotlin

open class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        mInstance = this
    }

    companion object {
        lateinit var mInstance: MyApp
        fun getContext(): Context? {
            return mInstance.applicationContext
        }
    }
}

and get Context like

MyApp.mInstance

or

MyApp.getContext()

How to know function return type and argument types?

Well things have changed a little bit since 2011! Now there's type hints in Python 3.5 which you can use to annotate arguments and return the type of your function. For example this:

def greeting(name):
  return 'Hello, {}'.format(name)

can now be written as this:

def greeting(name: str) -> str:
  return 'Hello, {}'.format(name)

As you can now see types, there's some sort of optional static type checking which will help you and your type checker to investigate your code.

for more explanation I suggest to take a look at the blog post on type hints in PyCharm blog.

Client on Node.js: Uncaught ReferenceError: require is not defined

I am coming from an Electron environment, where I need IPC communication between a renderer process and the main process. The renderer process sits in an HTML file between script tags and generates the same error.

The line

const {ipcRenderer} = require('electron')

throws the Uncaught ReferenceError: require is not defined

I was able to work around that by specifying Node.js integration as true when the browser window (where this HTML file is embedded) was originally created in the main process.

function createAddItemWindow() {

    // Create a new window
    addItemWindown = new BrowserWindow({
        width: 300,
        height: 200,
        title: 'Add Item',

        // The lines below solved the issue
        webPreferences: {
            nodeIntegration: true
        }
})}

That solved the issue for me. The solution was proposed here.

Cloud Firestore collection count

In 2020 this is still not available in the Firebase SDK however it is available in Firebase Extensions (Beta) however it's pretty complex to setup and use...

A reasonable approach

Helpers... (create/delete seems redundant but is cheaper than onUpdate)

export const onCreateCounter = () => async (
  change,
  context
) => {
  const collectionPath = change.ref.parent.path;
  const statsDoc = db.doc("counters/" + collectionPath);
  const countDoc = {};
  countDoc["count"] = admin.firestore.FieldValue.increment(1);
  await statsDoc.set(countDoc, { merge: true });
};

export const onDeleteCounter = () => async (
  change,
  context
) => {
  const collectionPath = change.ref.parent.path;
  const statsDoc = db.doc("counters/" + collectionPath);
  const countDoc = {};
  countDoc["count"] = admin.firestore.FieldValue.increment(-1);
  await statsDoc.set(countDoc, { merge: true });
};

export interface CounterPath {
  watch: string;
  name: string;
}

Exported Firestore hooks


export const Counters: CounterPath[] = [
  {
    name: "count_buildings",
    watch: "buildings/{id2}"
  },
  {
    name: "count_buildings_subcollections",
    watch: "buildings/{id2}/{id3}/{id4}"
  }
];


Counters.forEach(item => {
  exports[item.name + '_create'] = functions.firestore
    .document(item.watch)
    .onCreate(onCreateCounter());

  exports[item.name + '_delete'] = functions.firestore
    .document(item.watch)
    .onDelete(onDeleteCounter());
});

In action

The building root collection and all sub collections will be tracked.

enter image description here

Here under the /counters/ root path

enter image description here

Now collection counts will update automatically and eventually! If you need a count, just use the collection path and prefix it with counters.

const collectionPath = 'buildings/138faicnjasjoa89/buildingContacts';
const collectionCount = await db
  .doc('counters/' + collectionPath)
  .get()
  .then(snap => snap.get('count'));

Limitations

As this approach uses a single database and document, it is limited to the Firestore constraint of 1 Update per Second for each counter. It will be eventually consistent, but in cases where large amounts of documents are added/removed the counter will lag behind the actual collection count.

Capture iframe load complete event

Step 1: Add iframe in template.

<iframe id="uvIFrame" src="www.google.com"></iframe>

Step 2: Add load listener in Controller.

document.querySelector('iframe#uvIFrame').addEventListener('load', function () {
  $scope.loading = false;
  $scope.$apply();
});

What encoding/code page is cmd.exe using?

Type

chcp

to see your current code page (as Dewfy already said).

Use

nlsinfo

to see all installed code pages and find out what your code page number means.

You need to have Windows Server 2003 Resource kit installed (works on Windows XP) to use nlsinfo.

Check if a number is int or float

It's easier to ask forgiveness than ask permission. Simply perform the operation. If it works, the object was of an acceptable, suitable, proper type. If the operation doesn't work, the object was not of a suitable type. Knowing the type rarely helps.

Simply attempt the operation and see if it works.

inNumber = somenumber
try:
    inNumberint = int(inNumber)
    print "this number is an int"
except ValueError:
    pass
try:
    inNumberfloat = float(inNumber)
    print "this number is a float"
except ValueError:
    pass

selecting from multi-index pandas

You can use DataFrame.loc:

>>> df.loc[1]

Example

>>> print(df)
       result
A B C        
1 1 1       6
    2       9
  2 1       8
    2      11
2 1 1       7
    2      10
  2 1       9
    2      12

>>> print(df.loc[1])
     result
B C        
1 1       6
  2       9
2 1       8
  2      11

>>> print(df.loc[2, 1])
   result
C        
1       7
2      10

In JavaScript can I make a "click" event fire programmatically for a file input element?

THIS IS POSSIBLE: Under FF4+, Opera ?, Chrome: but:

  1. inputElement.click() should be called from user action context! (not script execution context)

  2. <input type="file" /> should be visible (inputElement.style.display !== 'none') (you can hide it with visibility or something other, but not "display" property)

What is a Python equivalent of PHP's var_dump()?

So I have taken the answers from this question and another question and came up below. I suspect this is not pythonic enough for most people, but I really wanted something that let me get a deep representation of the values some unknown variable has. I would appreciate any suggestions about how I can improve this or achieve the same behavior easier.

def dump(obj):
  '''return a printable representation of an object for debugging'''
  newobj=obj
  if '__dict__' in dir(obj):
    newobj=obj.__dict__
    if ' object at ' in str(obj) and not newobj.has_key('__type__'):
      newobj['__type__']=str(obj)
    for attr in newobj:
      newobj[attr]=dump(newobj[attr])
  return newobj

Here is the usage

class stdClass(object): pass
obj=stdClass()
obj.int=1
obj.tup=(1,2,3,4)
obj.dict={'a':1,'b':2, 'c':3, 'more':{'z':26,'y':25}}
obj.list=[1,2,3,'a','b','c',[1,2,3,4]]
obj.subObj=stdClass()
obj.subObj.value='foobar'

from pprint import pprint
pprint(dump(obj))

and the results.

{'__type__': '<__main__.stdClass object at 0x2b126000b890>',
 'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
 'int': 1,
 'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
 'subObj': {'__type__': '<__main__.stdClass object at 0x2b126000b8d0>',
            'value': 'foobar'},
 'tup': (1, 2, 3, 4)}

How do I ignore ampersands in a SQL script running from SQL Plus?

I resolved with the code below:

set escape on

and put a \ beside & in the left 'value_\&_intert'

Att

Can I obtain method parameter name using Java reflection?

see org.springframework.core.DefaultParameterNameDiscoverer class

DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
String[] params = discoverer.getParameterNames(MathUtils.class.getMethod("isPrime", Integer.class));

Catch multiple exceptions in one line (except block)

From Python documentation -> 8.3 Handling Exceptions:

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

except (RuntimeError, TypeError, NameError):
    pass

Note that the parentheses around this tuple are required, because except ValueError, e: was the syntax used for what is normally written as except ValueError as e: in modern Python (described below). The old syntax is still supported for backwards compatibility. This means except RuntimeError, TypeError is not equivalent to except (RuntimeError, TypeError): but to except RuntimeError as TypeError: which is not what you want.

How to quickly clear a JavaScript Object?

You can delete the props, but don't delete variables. delete abc; is invalid in ES5 (and throws with use strict).

You can assign it to null to set it for deletion to the GC (it won't if you have other references to properties)

Setting length property on an object does not change anything. (it only, well, sets the property)

Javascript to sort contents of select element

Working with the answers provided by Marco Lazzeri and Terre Porter (vote them up if this answer is useful), I came up with a slightly different solution that preserves the selected value (probably doesn't preserve event handlers or attached data, though) using jQuery.

// save the selected value for sorting
var v = jQuery("#id").val();

// sort the options and select the value that was saved
j$("#id")
    .html(j$("#id option").sort(function(a,b){
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;}))
    .val(v);

Close Bootstrap modal on form submit

Add the same attribute as you have on the Close button:

data-dismiss="modal"

e.g.

<button type="submit" class="btn btn-success" data-dismiss="modal"><i class="glyphicon glyphicon-ok"></i> Save</button>

You can also use jQuery if you wish:

$('#frmStudent').submit(function() {

    // submission stuff

    $('#StudentModal').modal('hide');
    return false;
});

How to create war files

Simplistic Shell code for creating WAR files from a standard Eclipse dynamic Web Project. Uses RAM File system (/dev/shm) on a Linux platform.

#!/bin/sh

UTILITY=$(basename $0)

if [ -z "$1" ] ; then
    echo "usage: $UTILITY [-s] <web-app-directory>..."
    echo "       -s ..... With source"
    exit 1
fi

if [ "$1" == "-s" ] ; then
    WITH_SOURCE=1
    shift
fi

while [ ! -z "$1" ] ; do
    WEB_APP_DIR=$1

    shift

    if [ ! -d $WEB_APP_DIR ] ; then
        echo "\"$WEB_APP_DIR\" is not a directory"
        continue
    fi

    if [ ! -d $WEB_APP_DIR/WebContent ] ; then
        echo "\"$WEB_APP_DIR\" is not a Web Application directory"
        continue
    fi

    TMP_DIR=/dev/shm/${WEB_APP_DIR}.$$.tmp
    WAR_FILE=/dev/shm/${WEB_APP_DIR}.war

    mkdir $TMP_DIR

    pushd $WEB_APP_DIR > /dev/null
    cp -r WebContent/* $TMP_DIR
    cp -r build/* $TMP_DIR/WEB-INF
    [ ! -z "$WITH_SOURCE" ] && cp -r src/* $TMP_DIR/WEB-INF/classes
    cd $TMP_DIR > /dev/null
    [ -e $WAR_FILE ] && rm -f $WAR_FILE
    jar cf $WAR_FILE .
    ls -lsF $WAR_FILE
    popd > /dev/null

    rm -rf $TMP_DIR
done

what is the difference between GROUP BY and ORDER BY in sql

ORDER BY shows a field in ascending or descending order. While GROUP BY shows same fieldnames, id's etc in only one output.

Test a weekly cron job

A wee bit beyond the scope of your question... but here's what I do.

The "how do I test a cron job?" question is closely connected to "how do I test scripts that run in non-interactive contexts launched by other programs?" In cron, the trigger is some time condition, but lots of other *nix facilities launch scripts or script fragments in non-interactive ways, and often the conditions in which those scripts run contain something unexpected and cause breakage until the bugs are sorted out. (See also: https://stackoverflow.com/a/17805088/237059 )

A general approach to this problem is helpful to have.

One of my favorite techniques is to use a script I wrote called 'crontest'. It launches the target command inside a GNU screen session from within cron, so that you can attach with a separate terminal to see what's going on, interact with the script, even use a debugger.

To set this up, you would use "all stars" in your crontab entry, and specify crontest as the first command on the command line, e.g.:

* * * * * crontest /command/to/be/tested --param1 --param2

So now cron will run your command every minute, but crontest will ensure that only one instance runs at a time. If the command takes time to run, you can do a "screen -x" to attach and watch it run. If the command is a script, you can put a "read" command at the top to make it stop and wait for the screen attachment to complete (hit enter after attaching)

If your command is a bash script, you can do this instead:

* * * * * crontest --bashdb /command/to/be/tested --param1 --param2

Now, if you attach with "screen -x", you'll be facing an interactive bashdb session, and you can step through the code, examine variables, etc.

#!/bin/bash

# crontest
# See https://github.com/Stabledog/crontest for canonical source.

# Test wrapper for cron tasks.  The suggested use is:
#
#  1. When adding your cron job, use all 5 stars to make it run every minute
#  2. Wrap the command in crontest
#        
#
#  Example:
#
#  $ crontab -e
#     * * * * * /usr/local/bin/crontest $HOME/bin/my-new-script --myparams
#
#  Now, cron will run your job every minute, but crontest will only allow one
#  instance to run at a time.  
#
#  crontest always wraps the command in "screen -d -m" if possible, so you can
#  use "screen -x" to attach and interact with the job.   
#
#  If --bashdb is used, the command line will be passed to bashdb.  Thus you
#  can attach with "screen -x" and debug the remaining command in context.
#
#  NOTES:
#   - crontest can be used in other contexts, it doesn't have to be a cron job.
#       Any place where commands are invoked without an interactive terminal and
#       may need to be debugged.
#
#   - crontest writes its own stuff to /tmp/crontest.log
#
#   - If GNU screen isn't available, neither is --bashdb
#

crontestLog=/tmp/crontest.log
lockfile=$(if [[ -d /var/lock ]]; then echo /var/lock/crontest.lock; else echo /tmp/crontest.lock; fi )
useBashdb=false
useScreen=$( if which screen &>/dev/null; then echo true; else echo false; fi )
innerArgs="$@"
screenBin=$(which screen 2>/dev/null)

function errExit {
    echo "[-err-] $@" | tee -a $crontestLog >&2
}

function log {
    echo "[-stat-] $@" >> $crontestLog
}

function parseArgs {
    while [[ ! -z $1 ]]; do
        case $1 in
            --bashdb)
                if ! $useScreen; then
                    errExit "--bashdb invalid in crontest because GNU screen not installed"
                fi
                if ! which bashdb &>/dev/null; then
                    errExit "--bashdb invalid in crontest: no bashdb on the PATH"
                fi

                useBashdb=true
                ;;
            --)
                shift
                innerArgs="$@"
                return 0
                ;;
            *)
                innerArgs="$@"
                return 0
                ;;
        esac
        shift
    done
}

if [[ -z  $sourceMe ]]; then
    # Lock the lockfile (no, we do not wish to follow the standard
    # advice of wrapping this in a subshell!)
    exec 9>$lockfile
    flock -n 9 || exit 1

    # Zap any old log data:
    [[ -f $crontestLog ]] && rm -f $crontestLog

    parseArgs "$@"

    log "crontest starting at $(date)"
    log "Raw command line: $@"
    log "Inner args: $@"
    log "screenBin: $screenBin"
    log "useBashdb: $( if $useBashdb; then echo YES; else echo no; fi )"
    log "useScreen: $( if $useScreen; then echo YES; else echo no; fi )"

    # Were building a command line.
    cmdline=""

    # If screen is available, put the task inside a pseudo-terminal
    # owned by screen.  That allows the developer to do a "screen -x" to
    # interact with the running command:
    if $useScreen; then
        cmdline="$screenBin -D -m "
    fi

    # If bashdb is installed and --bashdb is specified on the command line,
    # pass the command to bashdb.  This allows the developer to do a "screen -x" to
    # interactively debug a bash shell script:
    if $useBashdb; then
        cmdline="$cmdline $(which bashdb) "
    fi

    # Finally, append the target command and params:
    cmdline="$cmdline $innerArgs"

    log "cmdline: $cmdline"


    # And run the whole schlock:
    $cmdline 

    res=$?

    log "Command result: $res"


    echo "[-result-] $(if [[ $res -eq 0 ]]; then echo ok; else echo fail; fi)" >> $crontestLog

    # Release the lock:
    9<&-
fi

Open Facebook page from Android app?

As of July 2018 this works perfectly with or without the Facebook app on all the devices.

private void goToFacebook() {
    try {
        String facebookUrl = getFacebookPageURL();
        Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
        facebookIntent.setData(Uri.parse(facebookUrl));
        startActivity(facebookIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private String getFacebookPageURL() {
    String FACEBOOK_URL = "https://www.facebook.com/Yourpage-1548219792xxxxxx/";
    String facebookurl = null;

    try {
        PackageManager packageManager = getPackageManager();

        if (packageManager != null) {
            Intent activated = packageManager.getLaunchIntentForPackage("com.facebook.katana");

            if (activated != null) {
                int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

                if (versionCode >= 3002850) {
                    facebookurl = "fb://page/1548219792xxxxxx";
                }
            } else {
                facebookurl = FACEBOOK_URL;
            }
        } else {
            facebookurl = FACEBOOK_URL;
        }
    } catch (Exception e) {
        facebookurl = FACEBOOK_URL;
    }
    return facebookurl;
}

yii2 hidden input value

Like This:

<?= $form->field($model, 'hidden')->hiddenInput(['class' => 'form-control', 'maxlength' => true,])->label(false) ?>

How to generate the whole database script in MySQL Workbench?

Try the export function of phpMyAdmin.

I think there is also a possibility to copy the database files from one server to another, but I do not have a server available at the moment so I can't test it.

Does Python have a package/module management system?

In 2019 poetry is the package and dependency manager you are looking for.

https://github.com/sdispater/poetry#why

It's modern, simple and reliable.