Programs & Examples On #Opaque pointers

Is it possible to forward-declare a function in Python?

"just reorganize my code so that I don't have this problem." Correct. Easy to do. Always works.

You can always provide the function prior to it's reference.

"However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion"

Can't see how that's even remotely possible. Please provide an example of a place where you cannot define the function prior to it's use.

Elegant solution for line-breaks (PHP)

I have defined this:

if (PHP_SAPI === 'cli')
{
   define( "LNBR", PHP_EOL);
}
else
{
   define( "LNBR", "<BR/>");
}

After this use LNBR wherever I want to use \n.

How to combine date from one field with time from another field - MS SQL Server

Convert the first date stored in a datetime field to a string, then convert the time stored in a datetime field to string, append the two and convert back to a datetime field all using known conversion formats.

Convert(datetime, Convert(char(10), MYDATETIMEFIELD, 103) + ' ' + Convert(char(8), MYTIMEFIELD, 108), 103) 

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

How to change current Theme at runtime in Android

I would like to see the method too, where you set once for all your activities. But as far I know you have to set in each activity before showing any views.

For reference check this:

http://www.anddev.org/applying_a_theme_to_your_application-t817.html

Edit (copied from that forum):

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

        // Call setTheme before creation of any(!) View.
         setTheme(android.R.style.Theme_Dark);

        // ...
        setContentView(R.layout.main);
    }


Edit
If you call setTheme after super.onCreate(savedInstanceState); your activity recreated but if you call setTheme before super.onCreate(savedInstanceState); your theme will set and activity does not recreate anymore

  protected void onCreate(Bundle savedInstanceState) {
     setTheme(android.R.style.Theme_Dark);
     super.onCreate(savedInstanceState);


    // ...
    setContentView(R.layout.main);
}

What's in an Eclipse .classpath/.project file?

This eclipse documentation has details on the markups in .project file: The project description file

It describes the .project file as:

When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"

Overcoming "Display forbidden by X-Frame-Options"

Solution for loading an external website into an iFrame even tough the x-frame option is set to deny on the external website.

If you want to load a other website into an iFrame and you get the Display forbidden by X-Frame-Options” error then you can actually overcome this by creating a server side proxy script.

The src attribute of the iFrame could have an url looking like this: /proxy.php?url=https://www.example.com/page&key=somekey

Then proxy.php would look something like:

if (isValidRequest()) {
   echo file_get_contents($_GET['url']);
}

function isValidRequest() {
    return $_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['key']) && 
    $_GET['key'] === 'somekey';
}

This by passes the block, because it is just a GET request that might as wel have been a ordinary browser page visit.

Be aware: You might want to improve the security in this script. Because hackers could start loading in webpages via your proxy script.

Android Fragment no view found for ID?

In our case we have purged/corrupted class.dex file along with gradle compiled outputs. Due to cache recompile weren't tried hence no error, but apk was not having the required file causing this confusing error. A gradle resync and fresh build cleared us from all errors.

// Happy coding

How to iterate object in JavaScript?

You can do it with the below code. You first get the data array using dictionary.data and assign it to the data variable. After that you can iterate it using a normal for loop. Each row will be a row object in the array.

var data = dictionary.data;

for (var i in data)
{
     var id = data[i].id;
     var name = data[i].name;
}

You can follow similar approach to iterate the image array.

How can I print a circular structure in a JSON-like format?

I know this is an old question, but I'd like to suggest an NPM package I've created called smart-circular, which works differently from the other ways proposed. It's specially useful if you're using big and deep objects.

Some features are:

  • Replacing circular references or simply repeated structures inside the object by the path leading to its first occurrence (not just the string [circular]);

  • By looking for circularities in a breadth-first search, the package ensures this path is as small as possible, which is important when dealing with very big and deep objects, where the paths can get annoyingly long and difficult to follow (the custom replacement in JSON.stringify does a DFS);

  • Allows personalised replacements, handy to simplify or ignore less important parts of the object;

  • Finally, the paths are written exactly in the way necessary to access the field referenced, which can help you debugging.

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

Using -XX:+UseParNewGC along with -XX:+UseConcMarkSweepGC, will cause higher pause time for Minor GCs, when compared to -XX:+UseParallelGC.

This is because, promotion of objects from Young to Old Generation will require running a Best-Fit algorithm (due to old generation fragmentation) to find an address for this object.
Running such an algorithm is not required when using -XX:+UseParallelGC, as +UseParallelGC can be configured only with MarkandCompact Collector, in which case there is no fragmentation.

Difficulty with ng-model, ng-repeat, and inputs

how do something like:

<select ng-model="myModel($index+1)">

And in my inspector element be:

<select ng-model="myModel1">
...
<select ng-model="myModel2">

Passing variable number of arguments around

Though you can solve passing the formatter by storing it in local buffer first, but that needs stack and can sometime be issue to deal with. I tried following and it seems to work fine.

#include <stdarg.h>
#include <stdio.h>

void print(char const* fmt, ...)
{
    va_list arg;
    va_start(arg, fmt);
    vprintf(fmt, arg);
    va_end(arg);
}

void printFormatted(char const* fmt, va_list arg)
{
    vprintf(fmt, arg);
}

void showLog(int mdl, char const* type, ...)
{
    print("\nMDL: %d, TYPE: %s", mdl, type);

    va_list arg;
    va_start(arg, type);
    char const* fmt = va_arg(arg, char const*);
    printFormatted(fmt, arg);
    va_end(arg);
}

int main() 
{
    int x = 3, y = 6;
    showLog(1, "INF, ", "Value = %d, %d Looks Good! %s", x, y, "Infact Awesome!!");
    showLog(1, "ERR");
}

Hope this helps.

Upload Progress Bar in PHP

Implementation of the upload progress bar is easy and doesn't require any additional PHP extension, JavaScript or Flash. But you need PHP 5.4 and newer.

You have to enable collecting of the upload progress information by setting the directive session.upload_progress.enabled to On in php.ini.

Then add a hidden input to the HTML upload form just before any other file inputs. HTML attribute name of that hidden input should be the same as the value of the directive session.upload_progress.name from php.ini (eventually preceded by session.upload_progress.prefix). The value attribute is up to you, it will be used as part of the session key.

HTML form could looks like this:

<form action="upload.php" method="POST" enctype="multipart/form-data">
   <input type="hidden" name="<?php echo ini_get('session.upload_progress.prefix').ini_get('session.upload_progress.name'); ?>" value="myupload" />
   <input type="file" name="file1" />
   <input type="submit" />
</form>

When you send this form, PHP should create a new key in the $_SESSION superglobal structure which will be populated with the upload status information. The key is concatenated name and value of the hidden input.

In PHP you can take a look at populated upload information:

var_dump($_SESSION[
    ini_get('session.upload_progress.prefix')
   .ini_get('session.upload_progress.name')
   .'_myupload'
]);

The output will look similarly to the following:

$_SESSION["upload_progress_myupload"] = array(
  "start_time" => 1234567890,   // The request time
  "content_length" => 57343257, // POST content length
  "bytes_processed" => 54321,   // Amount of bytes received and processed
  "done" => false,              // true when the POST handler has finished, successfully or not
  "files" => array(
    0 => array(
      "field_name" => "file1",    // Name of the <input /> field
      // The following 3 elements equals those in $_FILES
      "name" => "filename.ext",
      "tmp_name" => "/tmp/phpxxxxxx",
      "error" => 0,
      "done" => false,            // True when the POST handler has finished handling this file
      "start_time" => 1234567890, // When this file has started to be processed
      "bytes_processed" => 54321, // Number of bytes received and processed for this file
    )
  )
);

There is all the information needed to create a progress bar — you have the information if the upload is still in progress, the information how many bytes is going to be transferred in total and how many bytes has been transferred already.

To present the upload progress to the user, write an another PHP script than the uploading one, which will only look at the upload information in the session and return it in the JSON format, for example. This script can be called periodically, for example every second, using AJAX and information presented to the user.

You are even able to cancel the upload by setting the $_SESSION[$key]['cancel_upload'] to true.

For detailed information, additional settings and user's comments see PHP manual.

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

Get Current date in epoch from Unix shell script

Depending on the language you're using it's going to be something simple like

CInt(CDate("1970-1-1") - CDate(Today()))

Ironically enough, yesterday was day 40,000 if you use 1/1/1900 as "day zero" like many computer systems use.

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Find the files existing in one directory but not in the other

GNU grep can inverse the search with the option -v. This makes grep reporting the lines, which do not match. By this you can remove the files in dir2 from the list of files in dir1.

grep -v -F -x -f <(find dir2 -type f -printf '%P\n') <(find dir1 -type f -printf '%P\n')

The options -F -x tell grep to perform a string search on the whole line.

How to view transaction logs in SQL Server 2008

You can't read the transaction log file easily because that's not properly documented. There are basically two ways to do this. Using undocumented or semi-documented database functions or using third-party tools.

Note: This only makes sense if your database is in full recovery mode.

SQL Functions:

DBCC LOG and fn_dblog - more details here and here.

Third-party tools:

Toad for SQL Server and ApexSQL Log.

You can also check out several other topics where this was discussed:

Android ListView with Checkbox and all clickable

Below code will help you:

public class DeckListAdapter extends BaseAdapter{

      private LayoutInflater mInflater;
        ArrayList<String> teams=new ArrayList<String>();
        ArrayList<Integer> teamcolor=new ArrayList<Integer>();


        public DeckListAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);

            teams.add("Upload");
            teams.add("Download");
            teams.add("Device Browser");
            teams.add("FTP Browser");
            teams.add("Options");

            teamcolor.add(Color.WHITE);
            teamcolor.add(Color.LTGRAY);
            teamcolor.add(Color.WHITE);
            teamcolor.add(Color.LTGRAY);
            teamcolor.add(Color.WHITE);


        }



        public int getCount() {
            return teams.size();
        }


        public Object getItem(int position) {
            return position;
        }


        public long getItemId(int position) {
            return position;
        }

       @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;


            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.decklist, null);

                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.deckarrow);
                holder.text = (TextView) convertView.findViewById(R.id.textname);

             .......here you can use holder.text.setonclicklistner(new View.onclick.

                        for each textview


                System.out.println(holder.text.getText().toString());

                convertView.setTag(holder);
            } else {

                holder = (ViewHolder) convertView.getTag();
            }



             holder.text.setText(teams.get(position));

             if(position<teamcolor.size())
             holder.text.setBackgroundColor(teamcolor.get(position));

             holder.icon.setImageResource(R.drawable.arraocha);







            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView text;



        }
}

Hope this helps.

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

AngularJS - difference between pristine/dirty and touched/untouched

AngularJS Developer Guide - CSS classes used by AngularJS

  • @property {boolean} $untouched True if control has not lost focus yet.
  • @property {boolean} $touched True if control has lost focus.
  • @property {boolean} $pristine True if user has not interacted with the control yet.
  • @property {boolean} $dirty True if user has already interacted with the control.

Suppress command line output

You can do this instead too:

tasklist | find /I "test.exe" > nul && taskkill /f /im test.exe > nul

Do subclasses inherit private fields?

No, private fields are not inherited. The only reason is that subclass can not access them directly.

How to top, left justify text in a <td> cell that spans multiple rows

td[rowspan] {
  vertical-align: top;
  text-align: left;
}

See: CSS attribute selectors.

How to run code after some delay in Flutter?

Just adding more description over the above answers

The Timer functionality works with below duration time also:

const Duration(
      {int days = 0,
      int hours = 0,
      int minutes = 0,
      int seconds = 0,
      int milliseconds = 0,
      int microseconds = 0})

Example:

  Timer(Duration(seconds: 3), () {
    print("print after every 3 seconds");
  });

minimum double value in C/C++

Try this:

-1 * numeric_limits<double>::max()

Reference: numeric_limits

This class is specialized for each of the fundamental types, with its members returning or set to the different values that define the properties that type has in the specific platform in which it compiles.

How to redirect to action from JavaScript method?

I wish that I could just comment on yojimbo87's answer to post this, but I don't have enough reputation to comment yet. It was pointed out that this relative path only works from the root:

        window.location.href = "/{controller}/{action}/{params}";

Just wanted to confirm that you can use @Url.Content to provide the absolute path:

function DeleteJob() {
    if (confirm("Do you really want to delete selected job/s?"))
        window.location.href = '@Url.Content("~/{controller}/{action}/{params}")';
    else
        return false;
}

Finding the type of an object in C++

Because your class is not polymorphic. Try:

struct BaseClas { int base; virtual ~BaseClas(){} };
class Derived1 : public BaseClas { int derived1; };

Now BaseClas is polymorphic. I changed class to struct because the members of a struct are public by default.

How to serve up a JSON response using Go?

In gobuffalo.io framework I got it to work like this:

// say we are in some resource Show action
// some code is omitted
user := &models.User{}
if c.Request().Header.Get("Content-type") == "application/json" {
    return c.Render(200, r.JSON(user))
} else {
    // Make user available inside the html template
    c.Set("user", user)
    return c.Render(200, r.HTML("users/show.html"))
}

and then when I want to get JSON response for that resource I have to set "Content-type" to "application/json" and it works.

I think Rails has more convenient way to handle multiple response types, I didn't see the same in gobuffalo so far.

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.

The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.

If this issue is causing serious problems, here are a few things I would suggest:

  • Revert back to JDK 1.7.0_25 until a fix is added to the JDK.

  • Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.

  • Try the JDK early releases as they come out. One of them might fix your problem.

Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.

How to vertically center <div> inside the parent element with CSS?

have you try this one?

.parentdiv {
 margin: auto;
 position: absolute;
 top: 0; left: 0; bottom: 0; right: 0;
 height: 300px; // at least you have to specify height
}

hope this helps

How do I center a window onscreen in C#?

If you want to center your windows during runtime use the code below, copy it into your application:

protected void ReallyCenterToScreen()
{
  Screen screen = Screen.FromControl(this);

  Rectangle workingArea = screen.WorkingArea;
  this.Location = new Point() {
    X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
    Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)};
}

And finally call the method above to get it working:

ReallyCenterToScreen();

How do I add target="_blank" to a link within a specified div?

I use this for every external link:

window.onload = function(){
  var anchors = document.getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    if (anchors[i].hostname != window.location.hostname) {
        anchors[i].setAttribute('target', '_blank');
    }
  }
}

How to get annotations of a member variable?

You can get annotations on the getter method:

propertyDescriptor.getReadMethod().getDeclaredAnnotations();

Getting the annotations of a private field seems like a bad idea... what if the property isn't even backed by a field, or is backed by a field with a different name? Even ignoring those cases, you're breaking abstraction by looking at private stuff.

angular-cli server - how to proxy API requests to another server?

Cors-origin issue screenshot

Cors issue has been faced in my application. refer above screenshot. After adding proxy config issue has been resolved. my application url: localhost:4200 and requesting api url:"http://www.datasciencetoolkit.org/maps/api/geocode/json?sensor=false&address="

Api side no-cors permission allowed. And also I'm not able to change cors-issue in server side and I had to change only in angular(client side).

Steps to resolve:

  1. create proxy.conf.json file inside src folder.
   {
      "/maps/*": {
        "target": "http://www.datasciencetoolkit.org",
        "secure": false,
        "logLevel": "debug",
        "changeOrigin": true
      }
    }
  1. In Api request
this.http
      .get<GeoCode>('maps/api/geocode/json?sensor=false&address=' + cityName)
      .pipe(
        tap(cityResponse => this.responseCache.set(cityName, cityResponse))
      );

Note: We have skip hostname name url in Api request, it will auto add while giving request. whenever changing proxy.conf.js we have to restart ng-serve, then only changes will update.

  1. Config proxy in angular.json
"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "TestProject:build",
            "proxyConfig": "src/proxy.conf.json"
          },
          "configurations": {
            "production": {
              "browserTarget": "TestProject:build:production"
            }
          }
        },

After finishing these step restart ng-serve Proxy working correctly as expect refer here

> WARNING in
> D:\angular\Divya_Actian_Assignment\src\environments\environment.prod.ts
> is part of the TypeScript compilation but it's unused. Add only entry
> points to the 'files' or 'include' properties in your tsconfig.
> ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** : Compiled
> successfully. [HPM] GET
> /maps/api/geocode/json?sensor=false&address=chennai ->
> http://www.datasciencetoolkit.org

Dynamically generating a QR code with PHP

The phpqrcode library is really fast to configure and the API documentation is easy to understand.

In addition to abaumg's answer I have attached 2 examples in PHP from http://phpqrcode.sourceforge.net/examples/index.php

1. QR code encoder

first include the library from your local path

include('../qrlib.php');

then to output the image directly as PNG stream do for example:

QRcode::png('your texte here...');

to save the result locally as a PNG image:

$tempDir = EXAMPLE_TMP_SERVERPATH;

$codeContents = 'your message here...';

$fileName = 'qrcode_name.png';

$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = EXAMPLE_TMP_URLRELPATH.$fileName;

QRcode::png($codeContents, $pngAbsoluteFilePath); 

2. QR code decoder

See also the zxing decoder:

http://zxing.org/w/decode.jspx

Pretty useful to check the output.

3. List of Data format

A list of data format you can use in your QR code according to the data type :

  • Website URL: http://stackoverflow.com (including the protocole http://)
  • email address: mailto:[email protected]
  • Telephone Number: +16365553344 (including country code)
  • SMS Message: smsto:number:message
  • MMS Message: mms:number:subject
  • YouTube Video: youtube://ID (may work on iPhone, not standardized)

How can I add a Google search box to my website?

Sorry for replying on an older question, but I would like to clarify the last question.

You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:

https://www.google.com/search?g=[value from input-field]

But when you search with google, you notice the following URL:

https://www.google.nl/search?q=google+search+bar

Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.

Adjusting HttpWebRequest Connection Timeout in C#

Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.

From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:

I Set:

.Timeout=5000
.ReadWriteTimeout=32000

The connect and post time for the HttpWebRequest took 26ms

but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.

I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.

For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.

How to scroll to top of page with JavaScript/jQuery?

The following code works in Firefox, Chrome and Safari, but I was unable to test this in Internet Explorer. Can someone test it, and then edit my answer or comment on it?

$(document).scrollTop(0);

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

The following method can be used to get the formatted string of the date which is passed in to it. It'll format the date to say 1st,2nd,3rd,4th .. using SimpleDateFormat in Java. eg:- 1st of September 2015

public String getFormattedDate(Date date){
            Calendar cal=Calendar.getInstance();
            cal.setTime(date);
            //2nd of march 2015
            int day=cal.get(Calendar.DATE);

            switch (day % 10) {
            case 1:  
                return new SimpleDateFormat("d'st' 'of' MMMM yyyy").format(date);
            case 2:  
                return new SimpleDateFormat("d'nd' 'of' MMMM yyyy").format(date);
            case 3:  
                return new SimpleDateFormat("d'rd' 'of' MMMM yyyy").format(date);
            default: 
                return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
        }

"Full screen" <iframe>

You could try frameborder=0.

How to automate browsing using python?

Internet Explorer specific, but rather good:

http://pamie.sourceforge.net/

The advantage compared to urllib/BeautifulSoup is that it executes Javascript as well since it uses IE.

How to create a function in SQL Server

I can give a small hack, you can use T-SQL function. Try this:

SELECT ID, PARSENAME(WebsiteName, 2)
FROM dbo.YourTable .....

ssh_exchange_identification: Connection closed by remote host under Git bash

If you are using a VPN, Turn it off and try to push again.

Border Radius of Table is not working

border-collapse: separate !important; worked.

Thanks.

HTML

<table class="bordered">
    <thead>
        <tr>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>                            
        </tr>
    </tbody>                    
</table>

CSS

table {
    border-collapse: separate !important;
    border-spacing: 0;
    width: 600px;
    margin: 30px;
}
.bordered {
    border: solid #ccc 1px;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    -webkit-box-shadow: 0 1px 1px #ccc;
    -moz-box-shadow: 0 1px 1px #ccc;
    box-shadow: 0 1px 1px #ccc;
}
.bordered tr:hover {
    background: #ECECEC;    
    -webkit-transition: all 0.1s ease-in-out;
    -moz-transition: all 0.1s ease-in-out;
    transition: all 0.1s ease-in-out;
}
.bordered td, .bordered th {
    border-left: 1px solid #ccc;
    border-top: 1px solid #ccc;
    padding: 10px;
    text-align: left;
}
.bordered th {
    background-color: #ECECEC;
    background-image: -webkit-gradient(linear, left top, left bottom, from(#F8F8F8), to(#ECECEC));
    background-image: -webkit-linear-gradient(top, #F8F8F8, #ECECEC);
    background-image: -moz-linear-gradient(top, #F8F8F8, #ECECEC);    
    background-image: linear-gradient(top, #F8F8F8, #ECECEC);
    -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    -moz-box-shadow:0 1px 0 rgba(255,255,255,.8) inset;
    box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    border-top: none;
    text-shadow: 0 1px 0 rgba(255,255,255,.5);
}
.bordered td:first-child, .bordered th:first-child {
    border-left: none;
}
.bordered th:first-child {
    -moz-border-radius: 6px 0 0 0;
    -webkit-border-radius: 6px 0 0 0;
    border-radius: 6px 0 0 0;
}
.bordered th:last-child {
    -moz-border-radius: 0 6px 0 0;
    -webkit-border-radius: 0 6px 0 0;
    border-radius: 0 6px 0 0;
}
.bordered th:only-child{
    -moz-border-radius: 6px 6px 0 0;
    -webkit-border-radius: 6px 6px 0 0;
    border-radius: 6px 6px 0 0;
}
.bordered tr:last-child td:first-child {
    -moz-border-radius: 0 0 0 6px;
    -webkit-border-radius: 0 0 0 6px;
    border-radius: 0 0 0 6px;
}
.bordered tr:last-child td:last-child {
    -moz-border-radius: 0 0 6px 0;
    -webkit-border-radius: 0 0 6px 0;
    border-radius: 0 0 6px 0;
} 

jsFiddle

Calling a JSON API with Node.js

Unirest library simplifies this a lot. If you want to use it, you have to install unirest npm package. Then your code could look like this:

unirest.get("http://graph.facebook.com/517267866/?fields=picture")
  .send()
  .end(response=> {
    if (response.ok) {
      console.log("Got a response: ", response.body.picture)
    } else {
      console.log("Got an error: ", response.error)
    }
  })

HTML form input tag name element array with JavaScript

Here’s some PHP and JavaScript demonstration code that shows a simple way to create indexed fields on a form (fields that have the same name) and then process them in both JavaScript and PHP. The fields must have both "ID" names and "NAME" names. Javascript uses the ID and PHP uses the NAME.

<?php
// How to use same field name multiple times on form
// Process these fields in Javascript and PHP
// Must use "ID" in Javascript and "NAME" in PHP 
echo "<HTML>";
echo "<HEAD>";
?>
<script type="text/javascript">
function TestForm(form) {
// Loop through the HTML form field (TheId) that is returned as an array. 
// The form field has multiple (n) occurrences on the form, each which has the same name.
// This results in the return of an array of elements indexed from 0 to n-1.
// Use ID  in Javascript
var i = 0;
document.write("<P>Javascript responding to your button click:</P>");
for (i=0; i < form.TheId.length; i++) {
  document.write(form.TheId[i].value);
  document.write("<br>");
}  
}
</script>
<?php
echo "</HEAD>";
echo "<BODY>";
$DQ = '"';  # Constant for building string with double quotes in it.

if (isset($_POST["MyButton"])) {
  $TheNameArray = $_POST["TheName"];  # Use NAME in PHP
  echo "<P>Here are the names you submitted to server:</P>";
  for ($i = 0; $i <3; $i++) {   
    echo $TheNameArray[$i] . "<BR>";
  } 
}
echo "<P>Enter names and submit to server or Javascript</P>";
echo "<FORM NAME=TstForm METHOD=POST ACTION=" ;
echo $DQ . "TestArrayFormToJavascript2.php" . $DQ . "OnReset=" . $DQ . "return allowreset(this)" . $DQ . ">";
echo "<FORM>";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<P><INPUT TYPE=submit NAME=MyButton VALUE=" . $DQ . "Submit to server"    . $DQ . "></P>";
echo "<P><BUTTON onclick=" . $DQ . "TestForm(this.form)" . $DQ . ">Submit to Javascript</BUTTON></P>"; 
echo "</FORM>";
echo "</BODY>";
echo "</HTML>";

How to write a cursor inside a stored procedure in SQL Server 2008

Try the following snippet. You can call the the below stored procedure from your application, so that NoOfUses in the coupon table will be updated.

CREATE PROCEDURE [dbo].[sp_UpdateCouponCount]
AS

Declare     @couponCount int,
            @CouponName nvarchar(50),
            @couponIdFromQuery int


Declare curP cursor For

  select COUNT(*) as totalcount , Name as name,couponuse.couponid  as couponid from Coupon as coupon 
  join CouponUse as couponuse on coupon.id = couponuse.couponid
  where couponuse.id=@cuponId
  group by couponuse.couponid , coupon.Name

OPEN curP 
Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery

While @@Fetch_Status = 0 Begin

    print @couponCount
    print @CouponName

    update Coupon SET NoofUses=@couponCount
    where couponuse.id=@couponIdFromQuery


Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery

End -- End of Fetch

Close curP
Deallocate curP

Hope this helps!

How to create a batch file to run cmd as administrator

This script does the trick! Just paste it into the top of your bat file. If you want to review the output of your script, add a "pause" command at the bottom of your batch file.

This script is now slightly edited to support command line args.

@echo off
:: BatchGotAdmin
::-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"="
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
::--------------------------------------

::ENTER YOUR CODE BELOW:

How to check null objects in jQuery

use $("#selector").get(0) to check with null like that. get returns the dom element, until then you re dealing with an array, where you need to check the length property. I personally don't like length check for null handling, it confuses me for some reason :)

What are the "standard unambiguous date" formats for string-to-date conversion in R?

In other words, is there a better solution than needing to specify the format?

Yes, there is now (ie in late 2016), thanks to anytime::anydate from the anytime package.

See the following for some examples from above:

R> anydate(c("01 Jan 2000", "01/01/2000", "2015/10/10"))
[1] "2000-01-01" "2000-01-01" "2015-10-10"
R> 

As you said, these are in fact unambiguous and should just work. And via anydate() they do. Without a format.

A cron job for rails: best practices?

I Use script to run cron, that is the best way to run a cron. Here is some example for cron,

Open CronTab —> sudo crontab -e

And Paste Bellow lines:

00 00 * * * wget https://your_host/some_API_end_point

Here is some cron format, will help you

::CRON FORMAT::

cron format table

Examples Of crontab Entries
15 6 2 1 * /home/melissa/backup.sh
Run the shell script /home/melissa/backup.sh on January 2 at 6:15 A.M.

15 06 02 Jan * /home/melissa/backup.sh
Same as the above entry. Zeroes can be added at the beginning of a number for legibility, without changing their value.

0 9-18 * * * /home/carl/hourly-archive.sh
Run /home/carl/hourly-archive.sh every hour, on the hour, from 9 A.M. through 6 P.M., every day.

0 9,18 * * Mon /home/wendy/script.sh
Run /home/wendy/script.sh every Monday, at 9 A.M. and 6 P.M.

30 22 * * Mon,Tue,Wed,Thu,Fri /usr/local/bin/backup
Run /usr/local/bin/backup at 10:30 P.M., every weekday. 

Hope this will help you :)

How can I set response header on express.js assets

This is so annoying.

Okay if anyone is still having issues or just doesn't want to add another library. All you have to do is place this middle ware line of code before your routes.

Cors Example

app.use((req, res, next) => {
    res.append('Access-Control-Allow-Origin', ['*']);
    res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.append('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

// Express routes
app.get('/api/examples', (req, res)=> {...});

Nested classes' scope?

All explanations can be found in Python Documentation The Python Tutorial

For your first error <type 'exceptions.NameError'>: name 'outer_var' is not defined. The explanation is:

There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method.

quoted from The Python Tutorial 9.4

For your second error <type 'exceptions.NameError'>: name 'OuterClass' is not defined

When a class definition is left normally (via the end), a class object is created.

quoted from The Python Tutorial 9.3.1

So when you try inner_var = Outerclass.outer_var, the Quterclass hasn't been created yet, that's why name 'OuterClass' is not defined

A more detailed but tedious explanation for your first error:

Although classes have access to enclosing functions’ scopes, though, they do not act as enclosing scopes to code nested within the class: Python searches enclosing functions for referenced names, but never any enclosing classes. That is, a class is a local scope and has access to enclosing local scopes, but it does not serve as an enclosing local scope to further nested code.

quoted from Learning.Python(5th).Mark.Lutz

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

image has a shape of (64,64,3).

Your input placeholder _x have a shape of (?, 64,64,3).

The problem is that you're feeding the placeholder with a value of a different shape.

You have to feed it with a value of (1, 64, 64, 3) = a batch of 1 image.

Just reshape your image value to a batch with size one.

image = array(img).reshape(1, 64,64,3)

P.S: the fact that the input placeholder accepts a batch of images, means that you can run predicions for a batch of images in parallel. You can try to read more than 1 image (N images) and than build a batch of N image, using a tensor with shape (N, 64,64,3)

Adding rows to tbody of a table using jQuery

As @wirey said appendTo should work, if not then you can try this:

$("#tblEntAttributes tbody").append(newRowContent);

ByRef argument type mismatch in Excel VBA

It looks like ByRef needs to know the size of the parameter. A declaration of Dim last_name as string doesn't specify the size of the string so it takes it as an error. Before using Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name) The last_name has to be declared as Dim last_name as string *10 ' size of string is up to you but must be a fix length

No need to change the function. Function doesn't take a fix length declaration.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

I just add an answear because I spent hours trying to solve the same symptoms (but different issue):

A possible cause is a x86 dll in a 64 bits app pool, the solution is to enable 32 bits apps in the application pool settings.

Eclipse doesn't stop at breakpoints

Sometimes you do start the debug mode but the debugger doesn't actually get attached/gets detached. I've also had this issue a few times when my laptop was reacting really slowly. A reboot always solved it for me.

Also try doing a clean all (works miracles in Eclipse).

How do I create a folder in a GitHub repository?

First you have to clone the repository to you local machine

git clone github_url local_directory

Then you can create local folders and files inside your local_directory, and add them to the repository using:

git add file_path

You can also add everything using:

git add .

Note that Git does not track empty folders. A workaround is to create a file inside the empty folder you want to track. I usually name that file empty, but it can be whatever name you choose.

Finally, you commit and push back to GitHub:

git commit
git push

For more information on Git, check out the Pro Git book.

How to add and get Header values in WebApi

On the Web API side, simply use Request object instead of creating new HttpRequestMessage

     var re = Request;
    var headers = re.Headers;

    if (headers.Contains("Custom"))
    {
        string token = headers.GetValues("Custom").First();
    }

    return null;

Output -

enter image description here

AutoComplete TextBox in WPF

Nimgoble's is the version I used in 2015. Thought I'd put it here as this question was top of the list in google for "wpf autocomplete textbox"

  1. Install nuget package for project in Visual Studio

  2. Add a reference to the library in the xaml:
    xmlns:behaviors="clr-namespace:WPFTextBoxAutoComplete;assembly=WPFTextBoxAutoComplete"

  3. Create a textbox and bind the AutoCompleteBehaviour to List<String> (TestItems):
    <TextBox Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}" behaviors:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding TestItems}" />

IMHO this is much easier to get started and manage than the other options listed above.

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

You'll need to decide how you'd like to handle exceptions thrown by the encrypt method.

Currently, encrypt is declared with throws Exception - however, in the body of the method, exceptions are caught in a try/catch block. I recommend you either:

  • remove the throws Exception clause from encrypt and handle exceptions internally (consider writing a log message at the very least); or,
  • remove the try/catch block from the body of encrypt, and surround the call to encrypt with a try/catch instead (i.e. in actionPerformed).

Regarding the compilation error you refer to: if an exception was thrown in the try block of encrypt, nothing gets returned after the catch block finishes. You could address this by initially declaring the return value as null:

public static byte[] encrypt(String toEncrypt) throws Exception{
  byte[] encrypted = null;
  try {
    // ...
    encrypted = ...
  }
  catch(Exception e){
    // ...
  }
  return encrypted;
}

However, if you can correct the bigger issue (the exception-handling strategy), this problem will take care of itself - particularly if you choose the second option I've suggested.

make a phone call click on a button

I've just solved the problem on an Android 4.0.2 device (GN) and the only version working for this device/version was similar to the first 5-starred with CALL_PHONE permission and the answer:

Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:123456789"));
startActivity(callIntent);

With any other solution i got the ActivityNotFoundException on this device/version. How about the older versions? Would someone give feedback?

How to use wget in php?

wget

wget is a linux command, not a PHP command, so to run this you woud need to use exec, which is a PHP command for executing shell commands.

exec("wget --http-user=[user] --http-password=[pass] http://www.example.com/file.xml");

This can be useful if you are downloading a large file - and would like to monitor the progress, however when working with pages in which you are just interested in the content, there are simple functions for doing just that.

The exec function is enabled by default, but may be disabled in some situations. The configuration options for this reside in your php.ini, to enable, remove exec from the disabled_functions config string.

alternative

Using file_get_contents we can retrieve the contents of the specified URL/URI. When you just need to read the file into a variable, this would be the perfect function to use as a replacement for curl - follow the URI syntax when building your URL.

// standard url
$content = file_get_contents("http://www.example.com/file.xml");

// or with basic auth
$content = file_get_contents("http://user:[email protected]/file.xml");

As noted by Sean the Bean - you may also need to change allow_url_fopen to true in your php.ini to allow the use of a URL in this method, however, this should be true by default.

If you want to then store that file locally, there is a function file_put_contents to write that into a file, combined with the previous, this could emulate a file download:

file_put_contents("local_file.xml", $content);

Is the NOLOCK (Sql Server hint) bad practice?

None of the answers is wrong, however a little confusing maybe.

  • When querying single values/rows it's always bad practise to use NOLOCK -- you probably never want to display incorrect information or maybe even take any action on incorrect data.
  • When displaying rough statistical information, NOLOCK can be very useful. Take SO as an example: It would be nonsense to take locks to read the exact number of views of a question, or the exact number of questions for a tag. Nobody cares if you incorrectly state 3360 questions tagged with "sql-server" now, and because of a transaction rollback, 3359 questions one second later.

How to delete columns that contain ONLY NAs?

Here is a dplyr solution:

df %>% select_if(~sum(!is.na(.)) > 0)

Update: The summarise_if() function is superseded as of dplyr 1.0. Here are two other solutions that use the where() tidyselect function:

df %>% 
  select(
    where(
      ~sum(!is.na(.x)) > 0
    )
  )
df %>% 
  select(
    where(
      ~!all(is.na(.x))
    )
  )

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

Angular Directive refresh on parameter change

Link function only gets called once, so it would not directly do what you are expecting. You need to use angular $watch to watch a model variable.

This watch needs to be setup in the link function.

If you use isolated scope for directive then the scope would be

scope :{typeId:'@' }

In your link function then you add a watch like

link: function(scope, element, attrs) {
    scope.$watch("typeId",function(newValue,oldValue) {
        //This gets called when data changes.
    });
 }

If you are not using isolated scope use watch on some_prop

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

A great substitute for np.isnan() and pd.isnull() is

for i in range(0,a.shape[0]):
    if(a[i]!=a[i]):
       //do something here
       //a[i] is nan

since only nan is not equal to itself.

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

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

    No, it's only local. You can decide to push (publish) some branches on GitHub.

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

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

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

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

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

    Yes, committing and pushing are both manual.

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

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

How to convert DateTime? to DateTime

DateTime UpdatedTime = _objHotelPackageOrder.HasValue ? _objHotelPackageOrder.UpdatedDate.Value : DateTime.Now;

Pyspark: Filter dataframe based on multiple conditions

Your logic condition is wrong. IIUC, what you want is:

import pyspark.sql.functions as f

df.filter((f.col('d')<5))\
    .filter(
        ((f.col('col1') != f.col('col3')) | 
         (f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
    )\
    .show()

I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.

Output:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

Calculating Time Difference

Here is a piece of code to do so:

def(StringChallenge(str1)):

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0

def time_dif(h1,m1,h2,m2):
    if(h1 == h2):
        return m2-m1
    else:
        return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0

if str1[1] == ':':
    h1=int(str1[:1])
    m1=int(str1[2:4])
else:
    h1=int(str1[:2])
    m1=int(str1[3:5])

if str1[-7] == '-':
    h2=int(str1[-6])
    m2=int(str1[-4:-2])
else:
    h2=int(str1[-7:-5])
    m2=int(str1[-4:-2])

if h1 == 12:
    h1 = 0
if h2 == 12:
    h2 = 0

if "am" in str1[:8]:
    flag1 = 0
else:
    flag1= 1

if "am" in str1[7:]:
    flag2 = 0
else:
    flag2 = 1

if flag1 == flag2:
    if h2 > h1 or (h2 == h1 and m2 >= m1):
        count_min += time_dif(h1,m1,h2,m2)
    else:
        count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
    count_min += (12-h1-1)*60
    count_min += (60 - m1)
    count_min += (h2*60)+m2


return count_min

Pandas DataFrame Groupby two columns and get counts

Followed by @Andy's answer, you can do following to solve your second question:

In [56]: df.groupby(['col5','col2']).size().reset_index().groupby('col2')[[0]].max()
Out[56]: 
      0
col2   
A     3
B     2
C     1
D     3

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});

sql primary key and index

I have a huge database with no (separate) index.

Any time I query by the primary key the results are, for all intensive purposes, instant.

Mercurial undo last commit

after you have pulled and updated your workspace do a thg and right click on the change set you want to get rid of and then click modify history -> strip, it will remove the change set and you will point to default tip.

Downloading and unzipping a .zip file without writing to disk

Adding on to the other answers using requests:

 # download from web

 import requests
 url = 'http://mlg.ucd.ie/files/datasets/bbc.zip'
 content = requests.get(url)

 # unzip the content
 from io import BytesIO
 from zipfile import ZipFile
 f = ZipFile(BytesIO(content.content))
 print(f.namelist())

 # outputs ['bbc.classes', 'bbc.docs', 'bbc.mtx', 'bbc.terms']

Use help(f) to get more functions details for e.g. extractall() which extracts the contents in zip file which later can be used with with open.

How to get input type using jquery?

EDIT Feb 1, 2013. Due to the popularity of this answer and the changes to jQuery in version 1.9 (and 2.0) regarding properties and attributes, I added some notes and a fiddle to see how it works when accessing properties/attributes on input, buttons and some selects. The fiddle here: http://jsfiddle.net/pVBU8/1/


get all the inputs:

var allInputs = $(":input");

get all the inputs type:

allInputs.attr('type');

get the values:

allInputs.val();

NOTE: .val() is NOT the same as :checked for those types where that is relevent. use:

.attr("checked");

EDIT Feb 1, 2013 - re: jQuery 1.9 use prop() not attr() as attr will not return proper values for properties that have changed.

.prop('checked');

or simply

$(this).checked;

to get the value of the check - whatever it is currently. or simply use the ':checked' if you want only those that ARE checked.

EDIT: Here is another way to get type:

var allCheckboxes=$('[type=checkbox]');

EDIT2: Note that the form of:

$('input:radio');

is perferred over

$(':radio');

which both equate to:

$('input[type=radio]');

but the "input" is desired so it only gets the inputs and does not use the universal '*" when the form of $(':radio') is used which equates to $('*:radio');

EDIT Aug 19, 2015: preference for the $('input[type=radio]'); should be used as that then allows modern browsers to optimize the search for a radio input.


EDIT Feb 1, 2013 per comment re: select elements @dariomac

$('select').prop("type");

will return either "select-one" or "select-multiple" depending upon the "multiple" attribute and

$('select')[0].type 

returns the same for the first select if it exists. and

($('select')[0]?$('select')[0].type:"howdy") 

will return the type if it exists or "howdy" if it does not.

 $('select').prop('type');

returns the property of the first one in the DOM if it exists or "undefined" if none exist.

$('select').type

returns the type of the first one if it exists or an error if none exist.

Unable to open a file with fopen()

Well, now you know there is a problem, the next step is to figure out what exactly the error is, what happens when you compile and run this?:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *file;
    file = fopen("TestFile1.txt", "r");
    if (file == NULL) {
      perror("Error");
    } else {
      fclose(file);
    }
}

C fopen vs open

Using open, read, write means you have to worry about signal interaptions.

If the call was interrupted by a signal handler the functions will return -1 and set errno to EINTR.

So the proper way to close a file would be

while (retval = close(fd), retval == -1 && ernno == EINTR) ;

EditText underline below text property

To change bottom line color, you can use this in your app theme:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="colorControlNormal">#c5c5c5</item>
    <item name="colorControlActivated">#ffe100</item>
    <item name="colorControlHighlight">#ffe100</item>
</style>

To change floating label color write following theme:

<style name="TextAppearence.App.TextInputLayout" parent="@android:style/TextAppearance">
<item name="android:textColor">#4ffd04[![enter image description here][1]][1]</item>
</style>

and use this theme in your layout:

 <android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    app:hintTextAppearance="@style/TextAppearence.App.TextInputLayout">

    <EditText
        android:id="@+id/edtTxtFirstName_CompleteProfileOneActivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:capitalize="characters"
        android:hint="User Name"
        android:imeOptions="actionNext"
        android:inputType="text"
        android:singleLine="true"
        android:textColor="@android:color/white" />

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

enter image description here

How to monitor Java memory usage?

If you use java 1.5, you can look at ManagementFactory.getMemoryMXBean() which give you numbers on all kinds of memory. heap and non-heap, perm-gen.

A good example can be found there http://www.freshblurbs.com/explaining-java-lang-outofmemoryerror-permgen-space

How do I temporarily disable triggers in PostgreSQL?

PostgreSQL knows the ALTER TABLE tblname DISABLE TRIGGER USER command, which seems to do what I need. See ALTER TABLE.

Android selector & text color

Here's my implementation, which behaves exactly as item in list (at least on 2.3)

res/layout/list_video_footer.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/list_video_footer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@android:drawable/list_selector_background"
        android:clickable="true"
        android:gravity="center"
        android:minHeight="98px"
        android:text="@string/more"
        android:textColor="@color/bright_text_dark_focused"
        android:textSize="18dp"
        android:textStyle="bold" />

</FrameLayout>

res/color/bright_text_dark_focused.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_selected="true" android:color="#444"/>
    <item android:state_focused="true" android:color="#444"/>
    <item android:state_pressed="true" android:color="#444"/>
    <item android:color="#ccc"/>

</selector>

PHP: check if any posted vars are empty - form: all fields required

if( isset( $_POST['login'] ) &&  strlen( $_POST['login'] ))
{
  // valid $_POST['login'] is set and its value is greater than zero
}
else
{
  //error either $_POST['login'] is not set or $_POST['login'] is empty form field
}

Set date input field's max date to today

I also had same issue .I build it trough this way.I used struts 2 framework.

  <script type="text/javascript">

  $(document).ready(function () {
  var year = (new Date).getFullYear();
  $( "#effectiveDateId" ).datepicker({dateFormat: "mm/dd/yy", maxDate: 
  0});

  });


  </script>

        <s:textfield name="effectiveDate" cssClass="input-large" 
   key="label.warrantRateMappingToPropertyTypeForm.effectiveDate" 
   id="effectiveDateId" required="true"/>

This worked for me.

Set title background color

Paste this code after setContentView or into onCreate

if you have a color code use this ;

getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#408ed4")));

if you want a specific code from Color library use this ;

getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.WHITE));

Reference member variables as class members

It's called dependency injection via constructor injection: class A gets the dependency as an argument to its constructor and saves the reference to dependent class as a private variable.

There's an interesting introduction on wikipedia.

For const-correctness I'd write:

using T = int;

class A
{
public:
  A(const T &thing) : m_thing(thing) {}
  // ...

private:
   const T &m_thing;
};

but a problem with this class is that it accepts references to temporary objects:

T t;
A a1{t};    // this is ok, but...

A a2{T()};  // ... this is BAD.

It's better to add (requires C++11 at least):

class A
{
public:
  A(const T &thing) : m_thing(thing) {}
  A(const T &&) = delete;  // prevents rvalue binding
  // ...

private:
  const T &m_thing;
};

Anyway if you change the constructor:

class A
{
public:
  A(const T *thing) : m_thing(*thing) { assert(thing); }
  // ...

private:
   const T &m_thing;
};

it's pretty much guaranteed that you won't have a pointer to a temporary.

Also, since the constructor takes a pointer, it's clearer to users of A that they need to pay attention to the lifetime of the object they pass.


Somewhat related topics are:

sqldeveloper error message: Network adapter could not establish the connection error

https://forums.oracle.com/forums/thread.jspa?threadID=2150962

Re: SQL DevErr:The Network Adapter could not establish the connection VenCode20 Posted: Dec 7, 2011 3:23 AM in response to: MehulDoshi Reply

This worked for me:

Open the "New/Select Database Connection" dialogue and try changing the connection type setting from "Basic" to "TNS" and then selecting the network alias (for me: "ORCL").

How to start an Intent by passing some parameters to it?

In order to pass the parameters you create new intent and put a parameter map:

Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);

In order to get the parameters values inside the started activity, you must call the get[type]Extra() on the same intent:

// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"

If your parameters are ints you would use getIntExtra() instead etc. Now you can use your parameters like you normally would.

How can I compare two ordered lists in python?

If you want to just check if they are identical or not, a == b should give you true / false with ordering taken into account.

In case you want to compare elements, you can use numpy for comparison

c = (numpy.array(a) == numpy.array(b))

Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I solved this issue by adding a no argument constractor. If you are using Lombok, you only need to add @NoArgsConstructor annotation:

@AllArgsConstructor
@NoArgsConstructor
@Getter
@ToString
@EqualsAndHashCode
public class User {
    private Long userId;
    private String shortName;
}

Twitter - share button, but with image

You're right in thinking that, in order to share an image in this way without going down the Twitter Cards route, you need to to have tweeted the image already. As you say, it's also important that you grab the image link that's of the form pic.twitter.com/NuDSx1ZKwy

This step-by-step guide is worth checking out for anyone looking to implement a 'tweet this' link or button: http://onlinejournalismblog.com/2015/02/11/how-to-make-a-tweetable-image-in-your-blog-post/.

Wrap a text within only two lines inside div

CSS only

    line-height: 1.5;
    white-space: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;

How to break out of jQuery each Loop

"each" uses callback function. Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.

use for loop if you have to stop the loop execution based on some condition and remain in to the same function.

.NET DateTime to SqlDateTime Conversion

-To compare only the date part, you can do:

var result = db.query($"SELECT * FROM table WHERE date >= '{fromDate.ToString("yyyy-MM-dd")}' and date <= '{toDate.ToString("yyyy-MM-dd"}'");

Java 8 LocalDate Jackson format

In configuration class define LocalDateSerializer and LocalDateDeserializer class and register them to ObjectMapper via JavaTimeModule like below:

@Configuration
public class AppConfig
{
@Bean
    public ObjectMapper objectMapper()
    {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_EMPTY);
        //other mapper configs
        // Customize de-serialization


        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
        mapper.registerModule(javaTimeModule);

        return mapper;
    }

    public class LocalDateSerializer extends JsonSerializer<LocalDate> {
        @Override
        public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.format(Constant.DATE_TIME_FORMATTER));
        }
    }

    public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

        @Override
        public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            return LocalDate.parse(p.getValueAsString(), Constant.DATE_TIME_FORMATTER);
        }
    }
}

Regular expression - starting and ending with a character string

This should do it for you ^wp.*php$

Matches

wp-comments-post.php
wp.something.php
wp.php

Doesn't match

something-wp.php
wp.php.txt

Flask - Calling python function on button OnClick event

You can simply do this with help of AJAX... Here is a example which calls a python function which prints hello without redirecting or refreshing the page.

In app.py put below code segment.

#rendering the HTML page which has the button
@app.route('/json')
def json():
    return render_template('json.html')

#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
    print ("Hello")
    return ("nothing")

And your json.html page should look like below.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
        $(function() {
          $('a#test').on('click', function(e) {
            e.preventDefault()
            $.getJSON('/background_process_test',
                function(data) {
              //do nothing
            });
            return false;
          });
        });
</script>


//button
<div class='container'>
    <h3>Test</h3>
        <form>
            <a href=# id=test><button class='btn btn-default'>Test</button></a>
        </form>

</div>

Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.

Why do you have to link the math library in C?

All libraries like stdio.h and stdlib.h have their implementation in libc.so or libc.a and get linked by the linker by default. The libraries for libc.so are automatically linked while compiling and is included in the executable file.
But math.h has its implementations in libm.so or libm.a which is seperate from libc.so and it does not get linked by default and you have to manually link it while compiling your program in gcc by using -lm flag.

The gnu gcc team designed it to be seperate from the other header files, while the other header files get linked by default but math.h file doesn't.

Here read the item no 14.3, you could read it all if you wish: Reason why math.h is needs to be linked
Look at this article: why we have to link math.h in gcc?
Have a look at the usage: using the library

How do I determine k when using k-means clustering?

Yes, you can find the best number of clusters using Elbow method, but I found it troublesome to find the value of clusters from elbow graph using script. You can observe the elbow graph and find the elbow point yourself, but it was lot of work finding it from script.

So another option is to use Silhouette Method to find it. The result from Silhouette completely comply with result from Elbow method in R.

Here`s what I did.

#Dataset for Clustering
n = 150
g = 6 
set.seed(g)
d <- data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))), 
                y = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))))
mydata<-d
#Plot 3X2 plots
attach(mtcars)
par(mfrow=c(3,2))

#Plot the original dataset
plot(mydata$x,mydata$y,main="Original Dataset")

#Scree plot to deterine the number of clusters
wss <- (nrow(mydata)-1)*sum(apply(mydata,2,var))
  for (i in 2:15) {
    wss[i] <- sum(kmeans(mydata,centers=i)$withinss)
}   
plot(1:15, wss, type="b", xlab="Number of Clusters",ylab="Within groups sum of squares")

# Ward Hierarchical Clustering
d <- dist(mydata, method = "euclidean") # distance matrix
fit <- hclust(d, method="ward") 
plot(fit) # display dendogram
groups <- cutree(fit, k=5) # cut tree into 5 clusters
# draw dendogram with red borders around the 5 clusters 
rect.hclust(fit, k=5, border="red")

#Silhouette analysis for determining the number of clusters
library(fpc)
asw <- numeric(20)
for (k in 2:20)
  asw[[k]] <- pam(mydata, k) $ silinfo $ avg.width
k.best <- which.max(asw)

cat("silhouette-optimal number of clusters:", k.best, "\n")
plot(pam(d, k.best))

# K-Means Cluster Analysis
fit <- kmeans(mydata,k.best)
mydata 
# get cluster means 
aggregate(mydata,by=list(fit$cluster),FUN=mean)
# append cluster assignment
mydata <- data.frame(mydata, clusterid=fit$cluster)
plot(mydata$x,mydata$y, col = fit$cluster, main="K-means Clustering results")

Hope it helps!!

How to check if a user likes my Facebook Page or URL using Facebook's API

Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.

The basic code is rather simple:

FB.api("me/likes/SOME_ID", function(response) {
    if ( response.data.length === 1 ) { //there should only be a single value inside "data"
        console.log('You like it');
    } else {
        console.log("You don't like it");
    }
});

ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:

FB.login(function(response) {
    //do whatever you need to do after a (un)successfull login         
}, { scope: 'user_likes' });

width:auto for <input> fields

It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.

Combining paste() and expression() functions in plot labels

If x^2 and y^2 were expressions already given in the variable squared, this solves the problem:

labNames <- c('xLab','yLab')
squared <- c(expression('x'^2), expression('y'^2))

xlab <- eval(bquote(expression(.(labNames[1]) ~ .(squared[1][[1]]))))
ylab <- eval(bquote(expression(.(labNames[2]) ~ .(squared[2][[1]]))))

plot(c(1:10), xlab = xlab, ylab = ylab)

Please note the [[1]] behind squared[1]. It gives you the content of "expression(...)" between the brackets without any escape characters.

how to stop a loop arduino

Matti Virkkunen said it right, there's no "decent" way of stopping the loop. Nonetheless, by looking at your code and making several assumptions, I imagine you're trying to output a signal with a given frequency, but you want to be able to stop it.

If that's the case, there are several solutions:

  1. If you want to generate the signal with the input of a button you could do the following

    int speakerOut = A0;
    int buttonPin = 13;
    
    void setup() {
        pinMode(speakerOut, OUTPUT);
        pinMode(buttonPin, INPUT_PULLUP);
    }
    
    int a = 0;
    
    void loop() {
        if(digitalRead(buttonPin) == LOW) {
            a ++;
            Serial.println(a);
            analogWrite(speakerOut, NULL);
    
            if(a > 50 && a < 300) {
                analogWrite(speakerOut, 200);
            }
    
            if(a <= 49) {
                analogWrite(speakerOut, NULL);
            }
    
            if(a >= 300 && a <= 2499) {
                analogWrite(speakerOut, NULL);
            }
        }
    }
    

    In this case we're using a button pin as an INPUT_PULLUP. You can read the Arduino reference for more information about this topic, but in a nutshell this configuration sets an internal pullup resistor, this way you can just have your button connected to ground, with no need of external resistors. Note: This will invert the levels of the button, LOW will be pressed and HIGH will be released.

  2. The other option would be using one of the built-ins hardware timers to get a function called periodically with interruptions. I won't go in depth be here's a great description of what it is and how to use it.

Visual Studio Code: How to show line endings

There's an extension that shows line endings. You can configure the color used, the characters that represent CRLF and LF and a boolean that turns it on and off.

Name: Line endings 
Id: jhartell.vscode-line-endings 
Description: Display line ending characters in vscode 
Version: 0.1.0 
Publisher: Johnny Härtell 

VS Marketplace Link

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece (in core since Perl 5.10) also has a strftime function and by default overloads localtime and gmtime to return Time::Piece objects:

use Time::Piece;
print localtime->strftime('%Y-%m-%d');

or without the overridden localtime:

use Time::Piece (); 
print Time::Piece::localtime->strftime('%F %T');

Automatically scroll down chat div

Let's review a few useful concepts about scrolling first:

When should you scroll?

  • User has loaded messages for the first time.
  • New messages have arrived and you are at the bottom of the scroll (you don't want to force scroll when the user is scrolling up to read previous messages).

Programmatically that is:

if (firstTime) {
  container.scrollTop = container.scrollHeight;
  firstTime = false;
} else if (container.scrollTop + container.clientHeight === container.scrollHeight) {
  container.scrollTop = container.scrollHeight;
}

Full chat simulator (with JavaScript):

https://jsfiddle.net/apvtL9xa/

_x000D_
_x000D_
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
 const message = document.getElementsByClassName('message')[0];_x000D_
  const newMessage = message.cloneNode(true);_x000D_
  messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
 // Prior to getting your messages._x000D_
  shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
  /*_x000D_
   * Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
   */_x000D_
  appendMessage();_x000D_
  // After getting your messages._x000D_
  if (!shouldScroll) {_x000D_
    scrollToBottom();_x000D_
  }_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
  messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
  height: 200px;_x000D_
  overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
  <div class="message">_x000D_
    Hello world_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

Change this dialog.cancel(); to dialog.dismiss();

The solution is to call dismiss() on the Dialog you created in NetErrorPage.java:114 before exiting the Activity, e.g. in onPause().

Views have a reference to their parent Context (taken from constructor argument). If you leave an Activity without destroying Dialogs and other dynamically created Views, they still hold this reference to your Activity (if you created with this as Context: like new ProgressDialog(this)), so it cannot be collected by the GC, causing a memory leak.

one line if statement in php

use the ternary operator ?:

change this

<?php if ($requestVars->_name == '') echo $redText; ?>

with

<?php echo ($requestVars->_name == '') ? $redText : ''; ?>

In short

// (Condition)?(thing's to do if condition true):(thing's to do if condition false);

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

How to resize array in C++?

You cannot resize array, you can only allocate new one (with a bigger size) and copy old array's contents. If you don't want to use std::vector (for some reason) here is the code to it:

int size = 10;
int* arr = new int[size];

void resize() {
    size_t newSize = size * 2;
    int* newArr = new int[newSize];

    memcpy( newArr, arr, size * sizeof(int) );

    size = newSize;
    delete [] arr;
    arr = newArr;
}

code is from here http://www.cplusplus.com/forum/general/11111/.

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

As mentioned by others here, that you could have two adb's running ... And to add to these answers from a Linux box perspective ( for the next newbie who is working from Linux );

  1. Uninstall your distro's android-tools ( use zypper or yum etc )

    # zypper -v rm android-tools
    
  2. Find where your other adb is

    # find /home -iname "*adb"|grep -i android
    

    Say it was at ;

    /home/developer/Android/Sdk/platform-tools/adb

  3. Then Make a softlink to it in the /usr/bin folder

     ln -s /home/developer/Android/Sdk/platform-tools/adb  /usr/bin/adb
    
  4. Then;

     # adb start-server
    

How to create major and minor gridlines with different linestyles in Python

A simple DIY way would be to make the grid yourself:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot([1,2,3], [2,3,4], 'ro')

for xmaj in ax.xaxis.get_majorticklocs():
  ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
  ax.axvline(x=xmin, ls='--')

for ymaj in ax.yaxis.get_majorticklocs():
  ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
  ax.axhline(y=ymin, ls='--')
plt.show()

Is there a function to round a float in C or do I need to write my own?

As Rob mentioned, you probably just want to print the float to 1 decimal place. In this case, you can do something like the following:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  float conver = 45.592346543;
  printf("conver is %0.1f\n",conver);
  return 0;
}

If you want to actually round the stored value, that's a little more complicated. For one, your one-decimal-place representation will rarely have an exact analog in floating-point. If you just want to get as close as possible, something like this might do the trick:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
  float conver = 45.592346543;
  printf("conver is %0.1f\n",conver);

  conver = conver*10.0f;
  conver = (conver > (floor(conver)+0.5f)) ? ceil(conver) : floor(conver);
  conver = conver/10.0f;

  //If you're using C99 or better, rather than ANSI C/C89/C90, the following will also work.
  //conver = roundf(conver*10.0f)/10.0f;

  printf("conver is now %f\n",conver);
  return 0;
}

I doubt this second example is what you're looking for, but I included it for completeness. If you do require representing your numbers in this way internally, and not just on output, consider using a fixed-point representation instead.

How can I disable a tab inside a TabControl?

This will remove the tab page, but you'll need to re-add it when you need it:

tabControl1.Controls.Remove(tabPage2);

If you are going to need it later, you might want to store it in a temporary tabpage before the remove and then re-add it when needed.

git error: failed to push some refs to remote

Rename your branch and then push, e.g.:

git branch -m new-name
git push -u new-name

This worked for me.

Delete commits from a branch in Git

Say we want to remove commits 2 & 4 from the repo.

commit 0 : b3d92c5
commit 1 : 2c6a45b
commit 2 : <any_hash>
commit 3 : 77b9b82
commit 4 : <any_hash>

Note: You need to have admin rights over the repo since you are using --hard and -f.

  • git checkout b3d92c5 Checkout the last usable commit.
  • git checkout -b repair Create a new branch to work on.
  • git cherry-pick 77b9b82 Run through commit 3.
  • git cherry-pick 2c6a45b Run through commit 1.
  • git checkout master Checkout master.
  • git reset --hard b3d92c5 Reset master to last usable commit.
  • git merge repair Merge our new branch onto master.
  • git push -f origin master Push master to the remote repo.

Understanding dispatch_async

The main reason you use the default queue over the main queue is to run tasks in the background.

For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});

How to clear File Input

Clear file input with jQuery

$("#fileInputId").val(null);

Clear file input with JavaScript

document.getElementById("fileInputId").value = null;

How to add Google Maps Autocomplete search box?

A significant portion of this code can be eliminated.

HTML excerpt:

<head>
  ...
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
  ...
</head>
<body>
  ...
  <input id="searchTextField" type="text" size="50">
  ...
</body>

Javascript:

function initialize() {
  var input = document.getElementById('searchTextField');
  new google.maps.places.Autocomplete(input);
}

google.maps.event.addDomListener(window, 'load', initialize);

php.ini & SMTP= - how do you pass username & password

I apply following details on php.ini file. its works fine.

SMTP = smtp.example.com
smtp_port = 25
username = [email protected]
password = yourmailpassord
sendmail_from = [email protected]

These details are same as on outlook settings.

How to initialize a vector with fixed length in R

?vector

X <- vector(mode="character", length=10)

This will give you empty strings which get printed as two adjacent double quotes, but be aware that there are no double-quote characters in the values themselves. That's just a side-effect of how print.default displays the values. They can be indexed by location. The number of characters will not be restricted, so if you were expecting to get 10 character element you will be disappointed.

>  X[5] <- "character element in 5th position"

>  X
 [1] ""                                  ""                                 
 [3] ""                                  ""                                 
 [5] "character element in 5th position" ""                                 
 [7] ""                                  ""                                 
 [9] ""                                  "" 
>  nchar(X)
 [1]  0  0  0  0 33  0  0  0  0  0

> length(X)
[1] 10

Self-reference for cell, column and row in worksheet functions

I don't see the need for Indirect, especially for conditional formatting.

The simplest way to self-reference a cell, row or column is to refer to it normally, e.g., "=A1" in cell A1, and make the reference partly or completely relative. For example, in a conditional formatting formula for checking whether there's a value in the first column of various cells' rows, enter the following with A1 highlighted and copy as necessary. The conditional formatting will always refer to column A for the row of each cell:

= $A1 <> ""

Concatenating two std::vectors

A general performance boost for concatenate is to check the size of the vectors. And merge/insert the smaller one with the larger one.

//vector<int> v1,v2;
if(v1.size()>v2.size()) {
    v1.insert(v1.end(),v2.begin(),v2.end());
} else {
    v2.insert(v2.end(),v1.begin(),v1.end());
}

When is it appropriate to use C# partial classes?

Aside from the other answers...

I've found them helpful as a stepping-stone in refactoring god-classes. If a class has multiple responsibilities (especially if it's a very large code-file) then I find it beneficial to add 1x partial class per-responsibility as a first-pass for organizing and then refactoring the code.

This helps greatly because it can help with making the code much more readable without actually effecting the executing behavior. It also can help identify when a responsibility is easy to refactor out or is tightly tangled with other aspects.

However--to be clear--this is still bad code, at the end of development you still want one responsibility per-class (NOT per partial class). It's just a stepping-stone :)

How to remove html special chars?

In addition to the good answers above, PHP also has a built-in filter function that is quite useful: filter-var.

To remove HMTL characters, use:

$cleanString = filter_var($dirtyString, FILTER_SANITIZE_STRING);

More info:

  1. function.filter-var
  2. filter_sanitize_string

How to make a <ul> display in a horizontal row

As @alex said, you could float it right, but if you wanted to keep the markup the same, float it to the left!

#ul_top_hypers li {
    float: left;
}

Start an activity from a fragment

You may have to replace getActivity() with MainActivity.this for those that are having issues with this.

What is the proper way to re-throw an exception in C#?

My preferences is to use

try 
{
}
catch (Exception ex)
{
     ...
     throw new Exception ("Put more context here", ex)
}

This preserves the original error, but allows you to put more context, such as an object ID, a connection string, stuff like that. Often my exception reporting tool will have 5 chained exceptions to report, each reporting more detail.

Retrieve Button value with jQuery

try this for your button:

<input type="button" class="my_button" name="buttonName" value="buttonValue" />

How to insert strings containing slashes with sed?

The s command can use any character as a delimiter; whatever character comes after the s is used. I was brought up to use a #. Like so:

s#?page=one&#/page/one#g

Css height in percent not working

Make it 100% of the viewport height:

div {
  height: 100vh;
}

Works in all modern browsers and IE>=9, see here for more info.

How can I flush GPU memory using CUDA (physical reset is unavailable)

One can also use nvtop, which gives an interface very similar to htop, but showing your GPU(s) usage instead, with a nice graph. You can also kill processes directly from here.

Here is a link to its Github : https://github.com/Syllo/nvtop

NVTOP interface

Print content of JavaScript object?

Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.

Function

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

Usage

var data = [1, 2, 3, 4];
print_r(data);

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

TypeScript or JavaScript type casting

In typescript it is possible to do an instanceof check in an if statement and you will have access to the same variable with the Typed properties.

So let's say MarkerSymbolInfo has a property on it called marker. You can do the following:

if (symbolInfo instanceof MarkerSymbol) {
    // access .marker here
    const marker = symbolInfo.marker
}

It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.

Check out these two resources for more information:

TypeScript instanceof & JavaScript instanceof

trying to align html button at the center of the my page

Here's your solution: JsFiddle

Basically, place your button into a div with centred text:

<div class="wrapper">
    <button class="button">Button</button>
</div>

With the following styles:

.wrapper {
    text-align: center;
}

.button {
    position: absolute;
    top: 50%;
}

There are many ways to skin a cat, and this is just one.

builder for HashMap

HashMap is mutable; there's no need for a builder.

Map<String, Integer> map = Maps.newHashMap();
map.put("a", 1);
map.put("b", 2);

Using a different font with twitter bootstrap

First of all you have to include your font in your website (or your CSS, to be more specific) using an appropriate @font-face rule.
From here on there are multiple ways to proceed. One thing I would not do is to edit the bootstrap.css directly - since once you get a newer version your changes will be lost. You do however have the possibility to customize your bootstrap files (there's a customize page on their website). Just enter the name of your font with all the fallback names into the corresponding typography textbox. Of course you will have to do this whenever you get a new or updated version of your bootstrap files.
Another chance you have is to overwrite the bootstrap rules within a different stylesheet. If you do this you just have to use selectors that are as specific as (or more specific than) the bootstrap selectors.
Side note: If you care about browser support a single EOT version of your font might not be sufficient. See http://caniuse.com/eot for a support table.

How to install MySQLi on MacOS

You are supposed to edit two lines in your php.ini file (i'm using windows for this example):

-The first one is regarding the extensions directory location. See below:

; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
extension_dir = "C:/php/ext"

-The second one is regarding the extension itself:

extension=php_mysqli.dll

Only modifying (uncommenting) the extension line was not enough for me. Hope it helps

how to change class name of an element by jquery

Instead of removeClass and addClass, you can also do it like this:

$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');

Increase distance between text and title on the y-axis

From ggplot2 2.0.0 you can use the margin = argument of element_text() to change the distance between the axis title and the numbers. Set the values of the margin on top, right, bottom, and left side of the element.

ggplot(mpg, aes(cty, hwy)) + geom_point()+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))

margin can also be used for other element_text elements (see ?theme), such as axis.text.x, axis.text.y and title.

addition

in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top"), you'll need a different theme setting - e.g. axis.title.x.top. See https://github.com/tidyverse/ggplot2/issues/4343.

How get an apostrophe in a string in javascript

You can use double quotes instead of single quotes:

theAnchorText = "I'm home";

Alternatively, escape the apostrophe:

theAnchorText = 'I\'m home';

The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.

There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n for a new line, or \t for a tab.

The shortest possible output from git log containing author and date

Feel free to use this one:

git log --pretty="%C(Yellow)%h  %C(reset)%ad (%C(Green)%cr%C(reset))%x09 %C(Cyan)%an: %C(reset)%s" -7

Note the -7 at the end, to show only the last 7 entries.

Look:

enter image description here

python replace single backslash with double backslash

You could use

os.path.abspath(path_with_backlash)

it returns the path with \

Return the characters after Nth character in a string

If your numbers are always 4 digits long:

=RIGHT(A1,LEN(A1)-5) //'0001 Baseball' returns Baseball

If the numbers are variable (i.e. could be more or less than 4 digits) then:

=RIGHT(A1,LEN(A1)-FIND(" ",A1,1)) //'123456 Baseball’ returns Baseball

MySQL WHERE IN ()

You have wrong database design and you should take a time to read something about database normalization (wikipedia / stackoverflow).

I assume your table looks somewhat like this

TABLE
================================
| group_id | user_ids | name   |
--------------------------------
| 1        | 1,4,6    | group1 |
--------------------------------
| 2        | 4,5,1    | group2 |    

so in your table of user groups, each row represents one group and in user_ids column you have set of user ids assigned to that group.

Normalized version of this table would look like this

GROUP
=====================
| id       | name   |
---------------------
| 1        | group1 |
---------------------
| 2        | group2 |    

GROUP_USER_ASSIGNMENT
======================
| group_id | user_id |
----------------------
| 1        | 1       |
----------------------
| 1        | 4       |
----------------------
| 1        | 6       |
----------------------
| 2        | 4       |
----------------------
| ...      

Then you can easily select all users with assigned group, or all users in group, or all groups of user, or whatever you can think of. Also, your sql query will work:

/* Your query to select assignments */
SELECT * FROM `group_user_assignment` WHERE user_id IN (1,2,3,4);

/* Select only some users */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE user_id IN (1,4);

/* Select all groups of user */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`user_id` = 1;

/* Select all users of group */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`group_id` = 1;

/* Count number of groups user is in */
SELECT COUNT(*) AS `groups_count` FROM `group_user_assignment` WHERE `user_id` = 1;

/* Count number of users in group */
SELECT COUNT(*) AS `users_count` FROM `group_user_assignment` WHERE `group_id` = 1;

This way it will be also easier to update database, when you would like to add new assignment, you just simply insert new row in group_user_assignment, when you want to remove assignment you just delete row in group_user_assignment.

In your database design, to update assignments, you would have to get your assignment set from database, process it and update and then write back to database.

Here is sqlFiddle to play with.

How to run JUnit test cases from the command line

In windows it is

java -cp .;/path/junit.jar org.junit.runner.JUnitCore TestClass [test class name without .class extension]

for example: c:\>java -cp .;f:/libraries/junit-4.8.2 org.junit.runner.JUnitCore TestSample1 TestSample2 ... and so on, if one has more than one test classes.

-cp stands for class path and the dot (.) represents the existing classpath while semi colon (;) appends the additional given jar to the classpath , as in above example junit-4.8.2 is now available in classpath to execute JUnitCore class that here we have used to execute our test classes.

Above command line statement helps you to execute junit (version 4+) tests from command prompt(i-e MSDos).

Note: JUnitCore is a facade to execute junit tests, this facade is included in 4+ versions of junit.

What are the safe characters for making URLs?

There are two sets of characters you need to watch out for: reserved and unsafe.

The reserved characters are:

  • ampersand ("&")
  • dollar ("$")
  • plus sign ("+")
  • comma (",")
  • forward slash ("/")
  • colon (":")
  • semi-colon (";")
  • equals ("=")
  • question mark ("?")
  • 'At' symbol ("@")
  • pound ("#").

The characters generally considered unsafe are:

  • space (" ")
  • less than and greater than ("<>")
  • open and close brackets ("[]")
  • open and close braces ("{}")
  • pipe ("|")
  • backslash ("")
  • caret ("^")
  • percent ("%")

I may have forgotten one or more, which leads to me echoing Carl V's answer. In the long run you are probably better off using a "white list" of allowed characters and then encoding the string rather than trying to stay abreast of characters that are disallowed by servers and systems.

HTML5 phone number validation with pattern

enter image description here

^[789]\d{9,9}$

  • Minimum digits 10
  • Maximum digits 10
  • number starts with 7,8,9

What is a unix command for deleting the first N characters of a line?

tail -f logfile | grep org.springframework | cut -c 900-

would remove the first 900 characters

cut uses 900- to show the 900th character to the end of the line

however when I pipe all of this through grep I don't get anything

Box-Shadow on the left side of the element only

You probably need more blur and a little less spread.

box-shadow: -10px 0px 10px 1px #aaaaaa;

Try messing around with the box shadow generator here http://css3generator.com/ until you get your desired effect.

How do I read the first line of a file using cat?

Use the below command to get the first row from a CSV file or any file formats.

head -1 FileName.csv

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

Just use

?

<form action="?" method="post" enctype="multipart/form-data" name="myForm" id="myForm">

It doesn't violate HTML5 standards.

Is there a color code for transparent in HTML?

There is not a Transparent color code, but there is an Opacity styling. Check out the documentation about it over at developer.mozilla.org

You will probably want to set the color of the element and then apply the opacity to it.

.transparent-style{

    background-color: #ffffff;
    opacity: .4;

}

You can use some online transparancy generatory which will also give you browser specific stylings. e.g. take a look at http://www.css-opacity.pascal-seven.de/

Note though that when you set the transparency of an element, any child element becomes transparent also. So you really need to overlay any other elements.

You may also want to try using an RGBA colour using the Alpha (A) setting to change the opacity. e.g.

.transparent-style{
    background-color: rgba(255, 255, 255, .4);
}

Using RGBA over opacity means that your child elements are not transparent.

How to convert webpage into PDF by using Python

here is the one working fine:

import sys 
from PyQt4.QtCore import *
from PyQt4.QtGui import * 
from PyQt4.QtWebKit import * 

app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.yahoo.com"))
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("fileOK.pdf")

def convertIt():
    web.print_(printer)
    print("Pdf generated")
    QApplication.exit()

QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
sys.exit(app.exec_())

How to add reference to a method parameter in javadoc?

The correct way of referring to a method parameter is like this:

enter image description here

Get file size before uploading

You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.

Turning a string into a Uri in Android

Uri.parse(STRING);

See doc:

String: an RFC 2396-compliant, encoded URI

Url must be canonicalized before using, like this:

Uri.parse(Uri.decode(STRING));

How to check for Is not Null And Is not Empty string in SQL server?

For some kind of reason my NULL values where of data length 8. That is why none of the abovementioned seemed to work. If you encounter the same problem, use the following code:

--Check the length of your NULL values
SELECT DATALENGTH(COLUMN) as length_column
FROM your_table

--Filter the length of your NULL values (8 is used as example)
WHERE DATALENGTH(COLUMN) > 8

How to convert milliseconds into human readable form?

I'm not able to comment first answer to your question, but there's a small mistake. You should use parseInt or Math.floor to convert floating point numbers to integer, i

var days, hours, minutes, seconds, x;
x = ms / 1000;
seconds = Math.floor(x % 60);
x /= 60;
minutes = Math.floor(x % 60);
x /= 60;
hours = Math.floor(x % 24);
x /= 24;
days = Math.floor(x);

Personally, I use CoffeeScript in my projects and my code looks like that:

getFormattedTime : (ms)->
        x = ms / 1000
        seconds = Math.floor x % 60
        x /= 60
        minutes = Math.floor x % 60
        x /= 60
        hours = Math.floor x % 24
        x /= 24
        days = Math.floor x
        formattedTime = "#{seconds}s"
        if minutes then formattedTime = "#{minutes}m " + formattedTime
        if hours then formattedTime = "#{hours}h " + formattedTime
        formattedTime 

jquery .on() method with load event

Refer to http://api.jquery.com/on/

It says

In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

If you want to do something when a new input box is added then you can simply write the code after appending it.

$('#add').click(function(){
        $('body').append(x);
        // Your code can be here
    });

And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click and document's ready event

Android: checkbox listener

Try this:

satView = (CheckBox) findViewById(R.id.sateliteCheckBox);

satView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
          if (buttonView.isChecked()) { 
                // checked
          } 
          else 
          {
                // not checked
          }
    }

});

Hope this helps.

Run reg command in cmd (bat file)?

You could also just create a Group Policy Preference and have it create the reg key for you. (no scripting involved)

How to get a list of installed Jenkins plugins with name and version pair

If you are a Jenkins administrator you can use the Jenkins system information page:

http://<jenkinsurl>/systemInfo

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

If you don't wish to use interop, you may want to try out OfficeWriter. Depending on how much processing you really need to do on the file, it might be overkill though. You can request a free trial. There's a fully documented api available at the documentation site.

DISCLAIMER: I'm one of the engineers who built the latest version.

Error: Uncaught SyntaxError: Unexpected token <

I don't know whether you got the answer. I met this issue today, and I thought I got a possible right answer: you don't put the script file in a right location.

Most people don't meet this issue because they put the scripts into their server directory directly. I meet this because I make a link of the source file (the html file) to the server root directory. I didn't link the script files, and I don't know how nginx find them. But they are not loaded correctly.

After I linked all files to the server root directory, problem solved.

How can I check whether a radio button is selected with JavaScript?

Give radio buttons, same name but different IDs.

var verified1 = $('#SOME_ELEMENT1').val();
var verified2 = $('#SOME_ELEMENT2').val();
var final_answer = null;
if( $('#SOME_ELEMENT1').attr('checked') == 'checked' ){
  //condition
  final_answer = verified1;
}
else
{
  if($('#SOME_ELEMENT2').attr('checked') == 'checked'){
    //condition
    final_answer = verified2;
   }
   else
   {
     return false;
   }
}

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

Finding moving average from data points in Python

There is a problem with the accepted answer. I think we need to use "valid" instead of "same" here - return numpy.convolve(interval, window, 'same') .

As an Example try out the MA of this data-set = [1,5,7,2,6,7,8,2,2,7,8,3,7,3,7,3,15,6] - the result should be [4.2,5.4,6.0,5.0,5.0,5.2,5.4,4.4,5.4,5.6,5.6,4.6,7.0,6.8], but having "same" gives us an incorrect output of [2.6,3.0,4.2,5.4,6.0,5.0,5.0,5.2,5.4,4.4,5.4,5.6,5.6, 4.6,7.0,6.8,6.2,4.8]

Rusty code to try this out -:

result=[]
dataset=[1,5,7,2,6,7,8,2,2,7,8,3,7,3,7,3,15,6]
window_size=5
for index in xrange(len(dataset)):
    if index <=len(dataset)-window_size :
        tmp=(dataset[index]+ dataset[index+1]+ dataset[index+2]+ dataset[index+3]+ dataset[index+4])/5.0
        result.append(tmp)
    else:
      pass

result==movingaverage(y, window_size) 

Try this with valid & same and see whether the math makes sense.

See also -: http://sentdex.com/sentiment-analysisbig-data-and-python-tutorials-algorithmic-trading/how-to-chart-stocks-and-forex-doing-your-own-financial-charting/calculate-simple-moving-average-sma-python/

How to redirect all HTTP requests to HTTPS

Do everything that is explained above for redirection. Just add "HTTP Strict Transport Security" to your header. This will avoid man in the middle attack.

Edit your apache configuration file (/etc/apache2/sites-enabled/website.conf and /etc/apache2/httpd.conf for example) and add the following to your VirtualHost:

# Optionally load the headers module:
LoadModule headers_module modules/mod_headers.so

<VirtualHost 67.89.123.45:443>
    Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
</VirtualHost>

https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security

Get width/height of SVG element

I'm using Firefox, and my working solution is very close to obysky. The only difference is that the method you call in an svg element will return multiple rects and you need to select the first one.

var chart = document.getElementsByClassName("chart")[0];
var width = chart.getClientRects()[0].width;
var height = chart.getClientRects()[0].height;

javascript: get a function's variable's value within another function

the OOP way to do this in ES5 is to make that variable into a property using the this keyword.

function first(){
    this.nameContent=document.getElementById('full_name').value;
}

function second() {
    y=new first();
    alert(y.nameContent);
}

How to center an image horizontally and align it to the bottom of the container?

wouldn't

margin-left:auto;
margin-right:auto;

added to the .image_block a img do the trick?
Note that that won't work in IE6 (maybe 7 not sure)
there you will have to do on .image_block the container Div

text-align:center;

position:relative; could be a problem too.

How to install pywin32 module in windows 7

are you just trying to install it, or are you looking to build from source?

If you just need to install, the easiest way is to use the MSI installers provided here:

http://sourceforge.net/projects/pywin32/files/pywin32/ (for updated versions)

make sure you get the correct version (matches Python version, 32bit/64bit, etc)

Angular 2: How to write a for loop, not a foreach loop

If you want to use the object of ith term and input it to another component in each iteration then:

<table class="table table-striped table-hover">
  <tr>
    <th> Blogs </th>
  </tr>
  <tr *ngFor="let blogEl of blogs">
    <app-blog-item [blog]="blogEl"> </app-blog-item>
  </tr>
</table>

Laravel 4: how to "order by" using Eloquent ORM

If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.

So, in the model you would have:

public function scopeIdDescending($query)
{
        return $query->orderBy('id','DESC');
}   

And outside the model you would have:

$posts = Post::idDescending()->get();

More info: http://laravel.com/docs/eloquent#query-scopes

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

read.table wants to return a data.frame, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE ) to fill in the blanks.

e.g.

read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
#        V1       V2       V3
#1 Element1 Element2         
#2 Element5 Element6 Element7

A note on whether or not to set header = FALSE... read.table tries to automatically determine if you have a header row thus:

header is set to TRUE if and only if the first row contains one fewer field than the number of columns

Reminder - \r\n or \n\r?

From Wikipedia (you can read which is correct for your OS at that article):

Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A).

Using Mockito with multiple calls to the same method with the same arguments

I've implemented a MultipleAnswer class that helps me to stub different answers in every call. Here the piece of code:

private final class MultipleAnswer<T> implements Answer<T> {

    private final ArrayList<Answer<T>> mAnswers;

    MultipleAnswer(Answer<T>... answer) {
        mAnswers = new ArrayList<>();
        mAnswers.addAll(Arrays.asList(answer));
    }

    @Override
    public T answer(InvocationOnMock invocation) throws Throwable {
        return mAnswers.remove(0).answer(invocation);
    }
}

C# string replace

You can't use string.replace...as one string is assigned you cannot manipulate. For that, we use string builder. Here is my example. In the HTML page I add [Name] which is replaced by Name. Make sure [Name] is unique or you can give any unique name:

string Name = txtname.Text;
string contents = File.ReadAllText(Server.MapPath("~/Admin/invoice.html"));

StringBuilder builder = new StringBuilder(contents);

builder.Replace("[Name]", Name);

StringReader sr = new StringReader(builder.ToString());

How to Customize the time format for Python logging?

Using logging.basicConfig, the following example works for me:

logging.basicConfig(
    filename='HISTORYlistener.log',
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
)

This allows you to format & config all in one line. A resulting log record looks as follows:

2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start

How to extract text from a PDF file?

Here is the simplest code for extracting text

code:

# importing required modules
import PyPDF2

# creating a pdf file object
pdfFileObj = open('filename.pdf', 'rb')

# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

# printing number of pages in pdf file
print(pdfReader.numPages)

# creating a page object
pageObj = pdfReader.getPage(5)

# extracting text from page
print(pageObj.extractText())

# closing the pdf file object
pdfFileObj.close()

How do I install Python packages in Google's Colab?

  1. Upload setup.py to drive.
  2. Mount the drive.
  3. Get the path of setup.py.
  4. !python PATH install.

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

TYPE CMD in search and when the command prompt appears in the BEST MATCH search result right-click on it and select 'Run as Administrator' when the user control window appears select 'Yes'. The command prompt window will appear and you should see "C:/WINDOWS/system32>"

at this point just type what you want, should work!

How do I upload a file with the JS fetch API?

The accepted answer here is a bit dated. As of April 2020, a recommended approach seen on the MDN website suggests using FormData and also does not ask to set the content type. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

I'm quoting the code snippet for convenience:

const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then((response) => response.json())
.then((result) => {
  console.log('Success:', result);
})
.catch((error) => {
  console.error('Error:', error);
});

Why is it important to override GetHashCode when Equals method is overridden?

Yes, it is important if your item will be used as a key in a dictionary, or HashSet<T>, etc - since this is used (in the absence of a custom IEqualityComparer<T>) to group items into buckets. If the hash-code for two items does not match, they may never be considered equal (Equals will simply never be called).

The GetHashCode() method should reflect the Equals logic; the rules are:

  • if two things are equal (Equals(...) == true) then they must return the same value for GetHashCode()
  • if the GetHashCode() is equal, it is not necessary for them to be the same; this is a collision, and Equals will be called to see if it is a real equality or not.

In this case, it looks like "return FooId;" is a suitable GetHashCode() implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that new Foo(3,5) has a different hash-code to new Foo(5,3)):

unchecked // only needed if you're compiling with arithmetic checks enabled
{ // (the default compiler behaviour is *disabled*, so most folks won't need this)
    int hash = 13;
    hash = (hash * 7) + field1.GetHashCode();
    hash = (hash * 7) + field2.GetHashCode();
    ...
    return hash;
}

Oh - for convenience, you might also consider providing == and != operators when overriding Equals and GetHashCode.


A demonstration of what happens when you get this wrong is here.

What is the best way to compare 2 folder trees on windows?

SyncToy is a free application from Microsoft with a "Preview" mode for comparing two paths. For example:

SyncToy Preview screenshot (source: https://maketecheasier-2d0f.kxcdn.com/assets/uploads/2010/06/synctoy-preview.png)

You can then choose one of three modes ("Synchronize", "Echo" and "Contribute") to resolve the differences.

Lastly, it comes with SyncToyCmd for creating and synchronizing folder pairs from the CLI or a Scheduled Task.

UITableView Cell selected Color?

Swift 5 - Xcode version 12.1 (12A7403)

|Step One|
Add the following to your AppDelegate.swift file

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let colorView = UIView()
    colorView.backgroundColor = UIColor.lightGray

    UITableViewCell.appearance().selectedBackgroundView = colorView
        
    return true
}

|Step Two|
Make sure your cell's Content View background is set to "Clear Color" (and not "Default") in the Attributes Inspector. This is done to not conflict with your App Delegate setting.

What are -moz- and -webkit-?

These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit for Chrome, Safari; -moz for Firefox, -o for Opera, -ms for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.

This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.

To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:

.elementClass {
    -moz-border-radius: 2em;
    -ms-border-radius: 2em;
    -o-border-radius: 2em;
    -webkit-border-radius: 2em;
    border-radius: 2em;
}

Specifically, to address the CSS in your question, the lines you quote:

-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;

Specify the column-count, column-gap and column-fill properties for Webkit browsers and Firefox.

References:

Check if year is leap year in javascript

My Code Is Very Easy To Understand

var year = 2015;
var LeapYear = year % 4;

if (LeapYear==0) {
    alert("This is Leap Year");
} else {
    alert("This is not leap year");
}

JFrame in full screen Java

Just use this code :

import java.awt.event.*;
import javax.swing.*;

public class FullscreenJFrame extends JFrame {
    private JPanel contentPane = new JPanel();
    private JButton fullscreenButton = new JButton("Fullscreen Mode");
    private boolean Am_I_In_FullScreen = false;
    private int PrevX, PrevY, PrevWidth, PrevHeight;

    public static void main(String[] args) {
        FullscreenJFrame frame = new FullscreenJFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 500);
        frame.setVisible(true);
    }

    public FullscreenJFrame() {
        super("My FullscreenJFrame");

        setContentPane(contentPane);

        // From Here starts the trick
        FullScreenEffect effect = new FullScreenEffect();

        fullscreenButton.addActionListener(effect);

        contentPane.add(fullscreenButton);
        fullscreenButton.setVisible(true);
    }

    private class FullScreenEffect implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (Am_I_In_FullScreen == false) {
                PrevX = getX();
                PrevY = getY();
                PrevWidth = getWidth();
                PrevHeight = getHeight();

                // Destroys the whole JFrame but keeps organized every Component
                // Needed if you want to use Undecorated JFrame dispose() is the
                // reason that this trick doesn't work with videos.
                dispose();
                setUndecorated(true);

                setBounds(0, 0, getToolkit().getScreenSize().width,
                        getToolkit().getScreenSize().height);
                setVisible(true);
                Am_I_In_FullScreen = true;
            } else {
                setVisible(true);
                setBounds(PrevX, PrevY, PrevWidth, PrevHeight);
                dispose();
                setUndecorated(false);
                setVisible(true);
                Am_I_In_FullScreen = false;
            }
        }
    }
}

I hope this helps.