Programs & Examples On #Uiscrollview

Use this tag for all questions about scroll views on iOS. Do NOT use this tag for other platforms.

How can I make a UITextField move up when the keyboard is present - on starting to edit?

I wrap everything in one class. Just call these lines of code when your viewcontroller is loaded:

- (void)viewDidLoad {
    [super viewDidLoad];
    KeyboardInsetScrollView *injectView = [[KeyboardInsetScrollView alloc] init];
    [injectView injectToView:self.view withRootView:self.view];
}

Here is link of sample project:
https://github.com/caohuuloc/KeyboardInsetScrollView

UIScrollView scroll to bottom programmatically

I found that contentSize doesn't really reflect the actual size of the text, so when trying to scroll to the bottom, it will be a little bit off. The best way to determine the actual content size is actually to use the NSLayoutManager's usedRectForTextContainer: method:

UITextView *textView;
CGSize textSize = [textView.layoutManager usedRectForTextContainer:textView.textContainer].size;

To determine how much text actually is shown in the UITextView, you can calculate it by subtracting the text container insets from the frame height.

UITextView *textView;
UIEdgeInsets textInsets = textView.textContainerInset;
CGFloat textViewHeight = textView.frame.size.height - textInsets.top - textInsets.bottom;

Then it becomes easy to scroll:

// if you want scroll animation, use contentOffset
UITextView *textView;
textView.contentOffset = CGPointMake(textView.contentOffset.x, textSize - textViewHeight);

// if you don't want scroll animation
CGRect scrollBounds = textView.bounds;
scrollBounds.origin = CGPointMake(textView.contentOffset.x, textSize - textViewHeight);
textView.bounds = scrollBounds;

Some numbers for reference on what the different sizes represent for an empty UITextView.

textView.frame.size = (width=246, height=50)
textSize = (width=10, height=16.701999999999998)
textView.contentSize = (width=246, height=33)
textView.textContainerInset = (top=8, left=0, bottom=8, right=0)

How to detect when a UIScrollView has finished scrolling

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self stoppedScrolling];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self stoppedScrolling];
    }
}

- (void)stoppedScrolling {
    // ...
}

Stop UIWebView from "bouncing" vertically?

To disable UIWebView scrolling you could use the following line of code:

[ObjWebview setUserInteractionEnabled:FALSE];

In this example, ObjWebview is of type UIWebView.

How do I auto size a UIScrollView to fit its content

Wrapping Richy's code I created a custom UIScrollView class that automates content resizing completely!

SBScrollView.h

@interface SBScrollView : UIScrollView
@end

SBScrollView.m:

@implementation SBScrollView
- (void) layoutSubviews
{
    CGFloat scrollViewHeight = 0.0f;
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    for (UIView* view in self.subviews)
    {
        if (!view.hidden)
        {
            CGFloat y = view.frame.origin.y;
            CGFloat h = view.frame.size.height;
            if (y + h > scrollViewHeight)
            {
                scrollViewHeight = h + y;
            }
        }
    }
    self.showsHorizontalScrollIndicator = YES;
    self.showsVerticalScrollIndicator = YES;
    [self setContentSize:(CGSizeMake(self.frame.size.width, scrollViewHeight))];
}
@end

How to use:
Simply import the .h file to your view controller and declare a SBScrollView instance instead of the normal UIScrollView one.

UIScrollView Scrollable Content Size Ambiguity

I made a video on youTube
Scroll StackViews using only Storyboard in Xcode

I think 2 kind of scenarios can appear here.

The view inside the scrollView -

  1. does not have any intrinsic content Size (e.g UIView)
  2. does have its own intrinsic content Size (e.g UIStackView)

For a vertically scrollable view in both cases you need to add these constraints:

  1. 4 constraints from top, left, bottom and right.

  2. Equal width to scrollview (to stop scrolling horizontally)

You don't need any other constraints for views which have his own intrinsic content height.

enter image description here


For views which do not have any intrinsic content height, you need to add a height constraint. The view will scroll only if the height constraint is more than the height of the scrollView.

enter image description here

How to disable horizontal scrolling of UIScrollView?

I struggled with this for some time trying unsuccessfully the various suggestions in this and other threads.

However, in another thread (not sure where) someone suggested that using a negative constraint on the UIScrollView worked for him.

So I tried various combinations of constraints with inconsistent results. What eventually worked for me was to add leading and trailing constraints of -32 to the scrollview and add an (invisible) textview with a width of 320 (and centered).

How to use UIScrollView in Storyboard

Here is a simple solution.

  1. Set the size attribute of your view controller in the storyboard to "Freeform" and set the size you want. Make sure it's big enough to fit the full content of your scroll view.

  2. Add your scroll view and set the constraints as you normally would. i.e. if you wants the scroll view to be the size of your view, then attach your top, bottom, leading, trailing margins to the superview as you normally would.

  3. Now just make sure there are constraints in the subviews of the scrollview that connect the top and bottom of the scroll view. Same for left and right if you have horizontal scrolling.

enter image description here

How to scroll UITableView to specific position

Simply single line of code:

self.tblViewMessages.scrollToRow(at: IndexPath.init(row: arrayChat.count-1, section: 0), at: .bottom, animated: isAnimeted)

UIScrollView not scrolling

I found that with this AutoLayout issue... if I just make the ViewController use UIView instead of UIScrollView for the class... then just add a UIScrollView myself... that it works.

What's the UIScrollView contentInset property for?

It's used to add padding in UIScrollView

Without contentInset, a table view is like this:

enter image description here

Then set contentInset:

tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)

The effect is as below:

enter image description here

Seems to be better, right?

And I write a blog to study the contentInset, criticism is welcome.

Finding the direction of scrolling in a UIScrollView?

In swift:

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0 {
        print("down")
    } else {
        print("up")
    }
}

You can do it also in scrollViewDidScroll.

Set UITableView content inset permanently

This is how it can be fixed easily through Storyboard (iOS 11 and Xcode 9.1):

Select Table View > Size Inspector > Content Insets: Never

How can I mimic the bottom sheet from the Maps app?

Maybe you can try my answer https://github.com/AnYuan/AYPannel, inspired by Pulley. Smooth transition from moving the drawer to scrolling the list. I added a pan gesture on the container scroll view, and set shouldRecognizeSimultaneouslyWithGestureRecognizer to return YES. More detail in my github link above. Wish to help.

Is it possible for UIStackView to scroll?

Horizontal Scrolling (UIStackView within UIScrollView)

For horizontal scrolling. First, create a UIStackView and a UIScrollView and add them to your view in the following way:

let scrollView = UIScrollView()
let stackView = UIStackView()

scrollView.addSubview(stackView)
view.addSubview(scrollView)

Remembering to set the translatesAutoresizingMaskIntoConstraints to false on the UIStackView and the UIScrollView:

stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false

To get everything working the trailing, leading, top and bottom anchors of the UIStackView should be equal to the UIScrollView anchors:

stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true

But the width anchor of the UIStackView must the equal to or greater than the width of the UIScrollView anchor:

stackView.widthAnchor.constraint(greaterThanOrEqualTo: scrollView.widthAnchor).isActive = true

Now anchor your UIScrollView, for example:

scrollView.heightAnchor.constraint(equalToConstant: 80).isActive = true
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

scrollView.bottomAnchor.constraint(equalTo:view.safeAreaLayoutGuide.bottomAnchor).isActive = true
scrollView.leadingAnchor.constraint(equalTo:view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo:view.trailingAnchor).isActive = true 

Next, I would suggest trying the following settings for the UIStackView alignment and distribution:

topicStackView.axis = .horizontal
topicStackView.distribution = .equalCentering
topicStackView.alignment = .center

topicStackView.spacing = 10

Finally you'll need to use the addArrangedSubview: method to add subviews to your UIStackView.

Text Insets

One additional feature that you might find useful is that because the UIStackView is held within a UIScrollView you now have access to text insets to make things look a bit prettier.

let inset:CGFloat = 20
scrollView.contentInset.left = inset
scrollView.contentInset.right = inset

// remember if you're using insets then reduce the width of your stack view to match
stackView.widthAnchor.constraint(greaterThanOrEqualTo: topicScrollView.widthAnchor, constant: -inset*2).isActive = true

Programmatically scroll a UIScrollView

I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!

What you're looking for is scrollRectToVisible(_:animated:).

Example:

extension SignUpView: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        scrollView.scrollRectToVisible(textField.frame, animated: true)
    }
}

What it does is exactly what you need, and it's far better than hacky contentOffset

This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.

From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible

Disabling vertical scrolling in UIScrollView

Just set the y to be always on top. Need to conform with UIScrollViewDelegate

func scrollViewDidScroll(scrollView: UIScrollView) {
        scrollView.contentOffset.y = 0.0
}

This will keep the Deceleration / Acceleration effect of the scrolling.

MISCONF Redis is configured to save RDB snapshots

Nowadays the Redis write-access problems that give this error message to the client re-emerged in the official redis docker containers.

Redis from the official redis image tries to write the .rdb file in the containers /data folder, which is rather unfortunate, as it is a root-owned folder and it is a non-persistent location too (data written there will disappear if your container/pod crashes).

So after an hour of inactivity, if you have run your redis container as a non-root user (e.g. docker run -u 1007 rather than default docker run -u 0), you will get a nicely detailed error msg in your server log (see docker logs redis):

1:M 29 Jun 2019 21:11:22.014 * 1 changes in 3600 seconds. Saving...
1:M 29 Jun 2019 21:11:22.015 * Background saving started by pid 499
499:C 29 Jun 2019 21:11:22.015 # Failed opening the RDB file dump.rdb (in server root dir /data) for saving: Permission denied
1:M 29 Jun 2019 21:11:22.115 # Background saving error

So what you need to do is to map container's /data folder to an external location (where the non-root user, here: 1007, has write access, such as /tmp on the host machine), e.g:

docker run --rm -d --name redis -p 6379:6379 -u 1007 -v /tmp:/data redis

So it is a misconfiguration of the official docker image (which should write to /tmp not /data) that produces this "time bomb" that you will most likely encounter only in production... overnight over some particularly quiet holiday weekend :/

How do I parse command line arguments in Java?

Argparse4j is best I have found. It mimics Python's argparse libary which is very convenient and powerful.

PHPmailer sending HTML CODE

// Excuse my beginner's english

There is msgHTML() method, which, also, call IsHTML().

Hrm... name IsHTML is confusing...

/**
 * Create a message from an HTML string.
 * Automatically makes modifications for inline images and backgrounds
 * and creates a plain-text version by converting the HTML.
 * Overwrites any existing values in $this->Body and $this->AltBody
 * @access public
 * @param string $message HTML message string
 * @param string $basedir baseline directory for path
 * @param bool $advanced Whether to use the advanced HTML to text converter
 * @return string $message
 */
public function msgHTML($message, $basedir = '', $advanced = false)

How to SELECT based on value of another SELECT

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,
       SUM(Value) AS "SUM(VALUE)",
       SUM(Value) / totals.total AS "% of Total"
FROM   table1,
       (
           SELECT Name,
                  SUM(Value) AS total
           FROM   table1
           GROUP BY Name
       ) AS totals
WHERE  table1.Name = totals.Name
AND    Year BETWEEN 2000 AND 2001
GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

Server unable to read htaccess file, denying access to be safe

I had same problem on Fedora, and found that problem was selinux. to test that it is problem run command: sudo setenforce 0

Otherwise or change in file /etc/sysconfig/selinux

SELINUX=enforcing
to
SELINUX=disabled

or add rules to selinux to allow http access

Why are hexadecimal numbers prefixed with 0x?

It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.

Example:

0x6400 translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600. When compiler reads 0x6400, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8 or whatever ..

For binary it would be:

0b00000001

Hope I have helped in some way.

Good day!

How to post query parameters with Axios?

As of 2021 insted of null i had to add {} in order to make it work!

axios.post(
        url,
        {},
        {
          params: {
            key,
            checksum
          }
        }
      )
      .then(response => {
        return success(response);
      })
      .catch(error => {
        return fail(error);
      });

How to secure database passwords in PHP?

Put the database password in a file, make it read-only to the user serving the files.

Unless you have some means of only allowing the php server process to access the database, this is pretty much all you can do.

What is the difference between method overloading and overriding?

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}

Altering user-defined table types in SQL Server

This is kind of a hack, but does seem to work. Below are the steps and an example of modifying a table type. One note is the sp_refreshsqlmodule will fail if the change you made to the table type is a breaking change to that object, typically a procedure.

  1. Use sp_rename to rename the table type, I typically just add z to the beginning of the name.
  2. Create a new table type with the original name and any modification you need to make to the table type.
  3. Step through each dependency and run sp_refreshsqlmodule on it.
  4. Drop the renamed table type.

EXEC sys.sp_rename 'dbo.MyTableType', 'zMyTableType';
GO
CREATE TYPE dbo.MyTableType AS TABLE(
    Id INT NOT NULL,
    Name VARCHAR(255) NOT NULL
);
GO
DECLARE @Name NVARCHAR(776);

DECLARE REF_CURSOR CURSOR FOR
SELECT referencing_schema_name + '.' + referencing_entity_name
FROM sys.dm_sql_referencing_entities('dbo.MyTableType', 'TYPE');

OPEN REF_CURSOR;

FETCH NEXT FROM REF_CURSOR INTO @Name;
WHILE (@@FETCH_STATUS = 0)
BEGIN
    EXEC sys.sp_refreshsqlmodule @name = @Name;
    FETCH NEXT FROM REF_CURSOR INTO @Name;
END;

CLOSE REF_CURSOR;
DEALLOCATE REF_CURSOR;
GO
DROP TYPE dbo.zMyTableType;
GO

WARNING:

This can be destructive to your database, so you'll want to test this on a development environment first.

android.app.Application cannot be cast to android.app.Activity

You can also try this one.

override fun registerWith( registry: PluginRegistry) {
        GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)       
    //registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
    }

I think this one is far better solution than creating a new class.

Get Root Directory Path of a PHP project

At this moment, PHP itself does not provide a way to get the project's root directory for sure.

But you can implement a very simple method yourself that will do exactly what you're looking for.

Solution

Create a new file in your project, let say D:/workspace/MySystem/Code/FilesManager.php (use whatever name and path suit you the best). Then, use the following code:

<?php

class FilesManager
{
  public static function rootDirectory()
  {
    // Change the second parameter to suit your needs
    return dirname(__FILE__, 2);
  }
}

Now you can do this in, let's say D:/workspace/MySystem/Code/a/b/c/Feature.php:

echo FilesManager::rootDirectory();

And the expected result should be:

"D:/workspace/MySystem"

The output will be the same no matter where your "feature" file is located in the project.

Explanation

dirname is used to return the parent directory of the first parameter. We use the magic constant __FILE__ to give it FilesManager.php's path. The second parameter tells how many times to go up in the hierarchy. In this case, we need to do it twice, but it really depends where you put your file in the hierarchy. You can omit the second parameter if you only need to got up once, meaning the file is located in the root. But then, you can return __DIR__ directly instead.

This solution is guaranteed to work, no matter where the root is located on your server. Unless you end up moving the utility class somewhere else in the hierarchy.

Additional note

I'd avoid using DOCUMENT_ROOT for the following reasons (according to this answer):

  • It makes your application dependent on the server.
  • The Apache setup may give an incorrect path to the root directory.

How to place two forms on the same page?

You can use this easiest method.

_x000D_
_x000D_
<form action="validator.php" method="post" id="form1">_x000D_
    <input type="text" name="user">_x000D_
    <input type="password" name="password">_x000D_
    <input type="submit" value="submit" form="form1">_x000D_
</form>_x000D_
_x000D_
<br />_x000D_
_x000D_
<form action="validator.php" method="post" id="form2">_x000D_
    <input type="text" name="user">_x000D_
    <input type="password" name="password">_x000D_
    <input type="submit" value="submit" form="form2">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to stop process from .BAT file?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate

wmic offer even more flexibility than taskkill .With wmic Path win32_process get you can see the available fileds you can filter.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

It may occur due to the clean solution.The dlls in the bin will be removed. 1.Clean Solution 2.Rebuild the solution 3.If the build process have failed,not all the necessary dlls will be stored in the bin. This is another scenario where the error occurs

Sending and receiving data over a network using TcpClient

First, I recommend that you use WCF, .NET Remoting, or some other higher-level communication abstraction. The learning curve for "simple" sockets is nearly as high as WCF, because there are so many non-obvious pitfalls when using TCP/IP directly.

If you decide to continue down the TCP/IP path, then review my .NET TCP/IP FAQ, particularly the sections on message framing and application protocol specifications.

Also, use asynchronous socket APIs. The synchronous APIs do not scale and in some error situations may cause deadlocks. The synchronous APIs make for pretty little example code, but real-world production-quality code uses the asynchronous APIs.

.htaccess not working on localhost with XAMPP

Edit the .htaccess file, so the first line reads 'Test.':

Test.

Set the default handler

DirectoryIndex index.php index.html index.htm

...

Datetime equal or greater than today in MySQL

SELECT * FROM users WHERE created >= NOW();

if the column is datetime type.

Create a symbolic link of directory in Ubuntu

This is the behavior of ln if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx to be the symlink, you should remove that directory first and run that same command.

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

There are some great solutions here, but I'll like to take it one step further regarding the local file.

In a scenario when Google does fail, it should load a local source but maybe a physical file on the server isn't necessarily the best option. I bring this up because I'm currently implementing the same solution, only I want to fall back to a local file that gets generated by a data source.

My reasons for this is that I want to have some piece of mind when it comes to keeping track of what I load from Google vs. what I have on the local server. If I want to change versions, I'll want to keep my local copy synced with what I'm trying to load from Google. In an environment where there are many developers, I think the best approach would be to automate this process so that all one would have to do is change a version number in a configuration file.

Here's my proposed solution that should work in theory:

  • In an application configuration file, I'll store 3 things: absolute URL for the library, the URL for the JavaScript API, and the version number
  • Write a class which gets the file contents of the library itself (gets the URL from app config), stores it in my datasource with the name and version number
  • Write a handler which pulls my local file out of the db and caches the file until the version number changes.
  • If it does change (in my app config), my class will pull the file contents based on the version number, save it as a new record in my datasource, then the handler will kick in and serve up the new version.

In theory, if my code is written properly, all I would need to do is change the version number in my app config then viola! You have a fallback solution which is automated, and you don't have to maintain physical files on your server.

What does everyone think? Maybe this is overkill, but it could be an elegant method of maintaining your AJAX libraries.

Acorn

How to limit depth for recursive file list?

tree -L 2 -u -g -p -d

Prints the directory tree in a pretty format up to depth 2 (-L 2). Print user (-u) and group (-g) and permissions (-p). Print only directories (-d). tree has a lot of other useful options.

Change image source with JavaScript

Under the TODOs, i am trying to implement your code in this posting. I am trying to take the large div on the left and make it change to reflect selections on the right. there are two selections, Ambient Temperature and Body Temperature

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title> Temperature Selection </title>_x000D_
<!-- css -->_x000D_
 <link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">_x000D_
 <link rel="stylesheet" href="css/main.css">_x000D_
_x000D_
<!-- end css -->_x000D_
<!-- Java script files -->_x000D_
<!-- Date.js date os javascript helper -->_x000D_
    <script src="js/date.js"> </script>_x000D_
_x000D_
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->_x000D_
 <script src="js/jquery-2.1.1.min.js"></script>_x000D_
_x000D_
<!-- Include all compiled plugins (below), or include individual files as needed -->_x000D_
 <script src="bootstrap-3/js/bootstrap.min.js"> </script>_x000D_
 <script src="js/library.js"> </script>_x000D_
 <script src="js/sfds.js"> </script>_x000D_
_x000D_
 <script src="js/main.js"> </script>_x000D_
_x000D_
<!-- End Java script files -->_x000D_
_x000D_
<!--TODO: need to integrate this code into the project:-->_x000D_
<script type="text/javascript">_x000D_
    function changeImage(a) {_x000D_
        document.getElementById("img").src=a;_x000D_
    }_x000D_
</script>_x000D_
 <script>_x000D_
 _x000D_
 _x000D_
 $(document).ready(function() {_x000D_
 _x000D_
  $("#ambient").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setTemperatureType(0);_x000D_
    $this.find('h2').text('Select Ambient Temperature 21 Degrees C');_x000D_
    <!--added on 05/20/2015-->_x000D_
   }else{_x000D_
    SFDS.setTemperatureType(1);_x000D_
    $this.addClass('clicked');_x000D_
    $this.find('h2').text('Ambient Temperature 21 Degrees C Selected');_x000D_
_x000D_
_x000D_
   }_x000D_
  });_x000D_
  _x000D_
  $("#body").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setTemperatureType(0);_x000D_
    $this.find('h2').text('Select Body Temperature 37 Degrees C');_x000D_
    <!--added on 05/20/2015-->_x000D_
   }else{_x000D_
    SFDS.setTemperatureType(1);_x000D_
    $this.addClass('clicked');_x000D_
    $this.find('h2').text('Body Temperature 37 Degrees C Selected');_x000D_
_x000D_
_x000D_
   }_x000D_
  });_x000D_
  _x000D_
  _x000D_
  _x000D_
 });_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="container-fluid">_x000D_
 <header>_x000D_
  <div class="row">_x000D_
   <div class="col-xs-6">_x000D_
    <div id="date"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
   <div class="col-xs-6">_x000D_
    <div id="time" class="text-right"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </header>_x000D_
 <div class="row">_x000D_
  <div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">_x000D_
   <div id="temperature" class="main_button center-block">_x000D_
    <div class="large_circle_button"> _x000D_
     <h2>Select<br/>Temperature</h2>_x000D_
     <img class="center-block large_button_image" src="images/thermometer.png" alt=""> _x000D_
                    <!-- TODO <img src='images/dropsterilewater.png'  onclick='changeImage("images/dropsterilewater.png");'>_x000D_
                                <img src='images/imagecansterilesaline.png'  onclick='changeImage("images/imagecansterilesaline.png");'>-->_x000D_
    </div>_x000D_
    <h1></h1>_x000D_
   </div>_x000D_
  </div>_x000D_
  <div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">_x000D_
   <div class="row">_x000D_
    <div class="col-xs-12">_x000D_
     <div id="ambient" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h2>Ambient<br/>Temperature<br/>21<sup>o</sup>C</h2>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/house.png" alt="" class="ambient_temp_image">_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
     </div>_x000D_
    </div>_x000D_
    <div class="col-xs-12">_x000D_
     <div id="body" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h2>Body<br/>Temperature<br/>37<sup>o</sup>C</h2>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/bodytempman.png" alt="" class="body_temp_image">_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
     </div>_x000D_
    </div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
_x000D_
    _x000D_
</div>_x000D_
<footer class="footer navbar-fixed-bottom">_x000D_
 <div class="container-fluid">_x000D_
  <div class="row cols-bottom">_x000D_
   <div class="col-sm-3">_x000D_
    <a href="main.html">_x000D_
    <div class="small_circle_button">     _x000D_
     <img src="images/buttonback.png" alt="back to home" class="settings"/> <!--  width="49" height="48" -->_x000D_
    </div>_x000D_
   </div></a><div class=" col-sm-6">_x000D_
    <div id="stop_button" >_x000D_
     <img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->_x000D_
    </div>_x000D_
     _x000D_
   </div><div class="col-sm-3">_x000D_
    <div id="parker" class="pull-right">_x000D_
     <img src="images/#" alt="logo" /> <!-- width="131" height="65" -->_x000D_
    </div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</footer>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Clear and reset form input fields

state={ 
  name:"",
  email:""
}

handalSubmit = () => {
  after api call 
  let resetFrom = {}
  fetch('url')
  .then(function(response) {
    if(response.success){
       resetFrom{
          name:"",
          email:""
      }
    }
  })
  this.setState({...resetFrom})
}

Embedding VLC plugin on HTML page

test.html is will be helpful for how to use VLC WebAPI.

test.html is located in the directory where VLC was installed.

e.g. C:\Program Files (x86)\VideoLAN\VLC\sdk\activex\test.html

The following code is a quote from the test.html.

HTML:

<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="640" height="360" id="vlc" events="True">
  <param name="MRL" value="" />
  <param name="ShowDisplay" value="True" />
  <param name="AutoLoop" value="False" />
  <param name="AutoPlay" value="False" />
  <param name="Volume" value="50" />
  <param name="toolbar" value="true" />
  <param name="StartTime" value="0" />
  <EMBED pluginspage="http://www.videolan.org"
    type="application/x-vlc-plugin"
    version="VideoLAN.VLCPlugin.2"
    width="640"
    height="360"
    toolbar="true"
    loop="false"
    text="Waiting for video"
    name="vlc">
  </EMBED>
</object>

JavaScript:

You can get vlc object from getVLC().
It works on IE 10 and Chrome.

function getVLC(name)
{
    if (window.document[name])
    {
        return window.document[name];
    }
    if (navigator.appName.indexOf("Microsoft Internet")==-1)
    {
        if (document.embeds && document.embeds[name])
            return document.embeds[name];
    }
    else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    {
        return document.getElementById(name);
    }
}

var vlc = getVLC("vlc");

// do something.
// e.g. vlc.playlist.play();

Expand and collapse with angular js

I just wrote a simple zippy/collapsable using Angular using ng-show, ng-click and ng-init. Its implemented to one level but can be expanded to multiple levels easily.

Assign a boolean variable to ng-show and toggle it on click of header.

Check it out here enter image description here

Drop all tables whose names begin with a certain string

CREATE PROCEDURE usp_GenerateDROP
    @Pattern AS varchar(255)
    ,@PrintQuery AS bit
    ,@ExecQuery AS bit
AS
BEGIN
    DECLARE @sql AS varchar(max)

    SELECT @sql = COALESCE(@sql, '') + 'DROP TABLE [' + TABLE_NAME + ']' + CHAR(13) + CHAR(10)
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME LIKE @Pattern

    IF @PrintQuery = 1 PRINT @sql
    IF @ExecQuery = 1 EXEC (@sql)
END

Simple pthread! C++

You should declare the thread main as:

void* print_message(void*) // takes one parameter, unnamed if you aren't using it

Calculate distance between two points in google maps V3

//p1 and p2 are google.maps.LatLng(x,y) objects

function calcDistance(p1, p2) {
          var d = (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
          console.log(d);              
}

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

I wasted a lot of time on this. Turns out that the default database library is not supported for Python 3. You have to use a different one.

Process to convert simple Python script into Windows executable

you may want to see if your app can run under IronPython. If so, you can compile it to an exe http://www.codeplex.com/IronPython

Internal and external fragmentation

Presumably from this site:

Internal Fragmentation Internal fragmentation occurs when the memory allocator leaves extra space empty inside of a block of memory that has been allocated for a client. This usually happens because the processor’s design stipulates that memory must be cut into blocks of certain sizes -- for example, blocks may be required to be evenly be divided by four, eight or 16 bytes. When this occurs, a client that needs 57 bytes of memory, for example, may be allocated a block that contains 60 bytes, or even 64. The extra bytes that the client doesn’t need go to waste, and over time these tiny chunks of unused memory can build up and create large quantities of memory that can’t be put to use by the allocator. Because all of these useless bytes are inside larger memory blocks, the fragmentation is considered internal.

External Fragmentation External fragmentation happens when the memory allocator leaves sections of unused memory blocks between portions of allocated memory. For example, if several memory blocks are allocated in a continuous line but one of the middle blocks in the line is freed (perhaps because the process that was using that block of memory stopped running), the free block is fragmented. The block is still available for use by the allocator later if there’s a need for memory that fits in that block, but the block is now unusable for larger memory needs. It cannot be lumped back in with the total free memory available to the system, as total memory must be contiguous for it to be useable for larger tasks. In this way, entire sections of free memory can end up isolated from the whole that are often too small for significant use, which creates an overall reduction of free memory that over time can lead to a lack of available memory for key tasks.

Convert Int to String in Swift

let intAsString = 45.description     // "45"
let stringAsInt = Int("45")          // 45

PHP if not statements

I think this is the best and easiest way to do it:

if (!(isset($action) && ($action == "add" || $action == "delete")))

Why is document.write considered a "bad practice"?

Another legitimate use of document.write comes from the HTML5 Boilerplate index.html example.

<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.3.min.js"><\/script>')</script>

I've also seen the same technique for using the json2.js JSON parse/stringify polyfill (needed by IE7 and below).

<script>window.JSON || document.write('<script src="json2.js"><\/script>')</script>

Excel formula to reference 'CELL TO THE LEFT'

When creating your conditional formatting, set the range to which it applies to what you want (the whole sheet), then enter a relative formula (remove the $ signs) as if you were only formatting the upper-left corner.

Excel will properly apply the formatting to the rest of the cells accordingly.

In this example, starting in B1, the left cell would be A1. Just use that--no advanced formula required.


If you're looking for something more advanced, you can play around with column(), row(), and indirect(...).

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

I kept running into this issue. In my case, @Jerreck's comment about case differences in the branch names was the cause of this error. Some Windows tools aren't aware of case sensitivity.

To turn off case-sensitivity in git, run this command:

git config --global core.ignorecase true

Note that this will impact more than branch names. For example, if you have "Foo.h" and "foo.h" in the same directory (not a great idea when building software for Windows) then I suspect you cannot turn off case sensitivity.

How to read PDF files using Java?

with Apache PDFBox it goes like this:

PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
    PDFTextStripper stripper = new PDFTextStripper();
    String text = stripper.getText(document);
    System.out.println("Text:" + text);
}
document.close();

Removing highcharts.com credits link

Add this to your css.

.highcharts-credits {
display: none !important;
}

Converting java.util.Properties to HashMap<String,String>

First thing,

Properties class is based on Hashtable and not Hashmap. Properties class basically extends Hashtable

There is no such constructor in HashMap class which takes a properties object and return you a hashmap object. So what you are doing is NOT correct. You should be able to cast the object of properties to hashtable reference.

to_string not declared in scope

//Try this if you can't use -std=c++11:-
int number=55;
char tempStr[32] = {0};
sprintf(tempStr, "%d", number);

Getting index value on razor foreach

Or you could simply do this:

@foreach(var myItem in Model.Members)
{    
    <span>@Model.Members.IndexOf(myItem)</span>
}

Fade Effect on Link Hover?

Nowadays people are just using CSS3 transitions because it's a lot easier than messing with JS, browser support is reasonably good and it's merely cosmetic so it doesn't matter if it doesn't work.

Something like this gets the job done:

a {
  color:blue;
  /* First we need to help some browsers along for this to work.
     Just because a vendor prefix is there, doesn't mean it will
     work in a browser made by that vendor either, it's just for
     future-proofing purposes I guess. */
  -o-transition:.5s;
  -ms-transition:.5s;
  -moz-transition:.5s;
  -webkit-transition:.5s;
  /* ...and now for the proper property */
  transition:.5s;
}
a:hover { color:red; }

You can also transition specific CSS properties with different timings and easing functions by separating each declaration with a comma, like so:

a {
  color:blue; background:white;
  -o-transition:color .2s ease-out, background 1s ease-in;
  -ms-transition:color .2s ease-out, background 1s ease-in;
  -moz-transition:color .2s ease-out, background 1s ease-in;
  -webkit-transition:color .2s ease-out, background 1s ease-in;
  /* ...and now override with proper CSS property */
  transition:color .2s ease-out, background 1s ease-in;
}
a:hover { color:red; background:yellow; }

Demo here

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

How to append binary data to a buffer in node.js

Updated Answer for Node.js ~>0.8

Node is able to concatenate buffers on its own now.

var newBuffer = Buffer.concat([buffer1, buffer2]);

Old Answer for Node.js ~0.6

I use a module to add a .concat function, among others:

https://github.com/coolaj86/node-bufferjs

I know it isn't a "pure" solution, but it works very well for my purposes.

A variable modified inside a while loop is not remembered

I use stderr to store within a loop, and read from it outside. Here var i is initially set and read inside the loop as 1.

# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value

f=/tmp/file1
g=/tmp/file2
i=1
cat $f $g | \
while read -r s;
do
  echo $s > /dev/null;  # some work
  echo $i > 2
  let i++
done;
read -r i < 2
echo $i

Or use the heredoc method to reduce the amount of code in a subshell. Note the iterative i value can be read outside the while loop.

i=1
while read -r s;
do
  echo $s > /dev/null
  let i++
done <<EOT
$(cat $f $g)
EOT
let i--
echo $i

Adding Google Play services version to your app's manifest?

I did following steps to recover from this:

1) Import google play services as project into your android sdk. In my system it is found at C:\adt-bundle-windows-x86_64-20140702\sdk\extras\google\google_play_services\libproject\google-play-services_lib

2) Your android application-> properties -> android

In the window

2.1) Click on Google APIs in project build target 2.2) Add google-play services in bottom frame and click on OK

Hope it gives clear instruction on what to do !!

Thanks.

SQL select statements with multiple tables

First select all record from person table, then join all these record with another table 'Address'...now u have record of all the persons who have their address in address table...so finally filter your record by zipcode.

 select * from Person as P inner join Address as A on 
    P.id = A.person_id Where A.zip='97229'

Changing the maximum length of a varchar column?

For MariaDB, use modify column:

ALTER TABLE table_name MODIFY COLUMN column_name VARCHAR (500);

It will work.

Determine version of Entity Framework I am using?

   internal static string GetEntityFrameworkVersion()
    {
        var version = "";
        var assemblies = System.AppDomain.CurrentDomain.GetAssemblies().Select(x => x.FullName).ToList();
        foreach(var asm in assemblies)
        {
            var fragments = asm.Split(new char[] { ',', '{', '}' }, StringSplitOptions.RemoveEmptyEntries).Select(x=> x.Trim()).ToList();
            if(string.Compare(fragments[0], EntityFramework, true)==0)
            {
                var subfragments = fragments[1].Split(new char[] { '='}, StringSplitOptions.RemoveEmptyEntries);
                version =subfragments[1];
                break;
            }
        }
        return version;
    }

Batch command date and time in file name

As Vicky already pointed out, %DATE% and %TIME% return the current date and time using the short date and time formats that are fully (endlessly) customizable.

One user may configure its system to return Fri040811 08.03PM while another user may choose 08/04/2011 20:30.

It's a complete nightmare for a BAT programmer.

Changing the format to a firm format may fix the problem, provided you restore back the previous format before leaving the BAT file. But it may be subject to nasty race conditions and complicate recovery in cancelled BAT files.

Fortunately, there is an alternative.

You may use WMIC, instead. WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table returns the date and time in a invariable way. Very convenient to directly parse it with a FOR /F command.

So, putting the pieces together, try this as a starting point...

SETLOCAL enabledelayedexpansion
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
  SET /A FD=%%F*1000000+%%D*100+%%A
  SET /A FT=10000+%%B*100+%%C
  SET FT=!FT:~-4!
  ECHO Archive_!FD!_!FT!.zip
 )

Is a LINQ statement faster than a 'foreach' loop?

Why should LINQ be faster? It also uses loops internally.

Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code.

indexOf Case Sensitive?

Just to sum it up, 3 solutions:

  • using toLowerCase() or toUpperCase
  • using StringUtils of apache
  • using regex

Now, what I was wondering was which one is the fastest? I'm guessing on average the first one.

XSLT counting elements with a given value

<xsl:variable name="count" select="count(/Property/long = $parPropId)"/>

Un-tested but I think that should work. I'm assuming the Property nodes are direct children of the root node and therefor taking out your descendant selector for peformance

What are the different NameID format used for?

It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:

  1. unspecified
  2. emailAddress – e.g. [email protected]
  3. X509SubjectName – e.g. CN=john,O=Company Ltd.,C=US
  4. WindowsDomainQualifiedName – e.g. CompanyDomain\John
  5. kerberos– e.g. john@realm
  6. entity – this one in used to identify entities that provide SAML-based services and looks like a URI
  7. persistent – this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.
  8. transient – opaque identifier which should be treated as temporary.

How to fix .pch file missing on build?

NOTE: Later versions of the IDE may use "pch" rather than "stdafx" in the default names for related files. It may be necessary to substitute pch for stdafx in the instructions below. I apologize. It's not my fault.

  1. Right-click on your project in the Solution Explorer.
  2. Click Properties at the bottom of the drop-down menu.
  3. At the top left of the Properties Pages, select All Configurations from the drop-down menu.
  4. Open the C/C++ tree and select Precompiled Headers
  5. Precompiled Header: Select Use (/Yu)
  6. Fill in the Precompiled Header File field. Standard is stdafx.h
  7. Click Okay

  8. If you do not have stdafx.h in your Header Files put it there. Edit it to #include all the headers you want precompiled.

  9. Put a file named stdafx.cpp into your project. Put #include "stdafx.h" at the top of it, and nothing else.
  10. Right-click on stdafx.cpp in Solution Explorer. Select Properties and All configurations again as in step 4 ...
  11. ... but this time select Precompiled Header Create (/Yc). This will only bind to the one file stdafx.cpp.
  12. Put #include "stdafx.h" at the very top of all your source files.

Lucky 13. Cross your fingers and hit Build.

Leave out quotes when copying from cell

  • if formula having multi line (means having line break in formula) then copy paste will work in that way
  • if can remove multi line then no quotes will appear while copy paste.
  • else use CLEAN function as said by @greg in previous answer

Iterating over every two elements in a list

The title of this question is misleading, you seem to be looking for consecutive pairs, but if you want to iterate over the set of all possible pairs than this will work :

for i,v in enumerate(items[:-1]):
        for u in items[i+1:]:

How to do a scatter plot with empty circles in Python?

Here's another way: this adds a circle to the current axes, plot or image or whatever :

from matplotlib.patches import Circle  # $matplotlib/patches.py

def circle( xy, radius, color="lightsteelblue", facecolor="none", alpha=1, ax=None ):
    """ add a circle to ax= or current axes
    """
        # from .../pylab_examples/ellipse_demo.py
    e = Circle( xy=xy, radius=radius )
    if ax is None:
        ax = pl.gca()  # ax = subplot( 1,1,1 )
    ax.add_artist(e)
    e.set_clip_box(ax.bbox)
    e.set_edgecolor( color )
    e.set_facecolor( facecolor )  # "none" not None
    e.set_alpha( alpha )

alt text

(The circles in the picture get squashed to ellipses because imshow aspect="auto" ).

Finding a substring within a list in Python

This prints all elements that contain sub:

for s in filter (lambda x: sub in x, list): print (s)

How to call stopservice() method of Service class from the calling activity class

I actually used pretty much the same code as you above. My service registration in the manifest is the following

<service android:name=".service.MyService" android:enabled="true">
            <intent-filter android:label="@string/menuItemStartService" >
                <action android:name="it.unibz.bluedroid.bluetooth.service.MY_SERVICE"/>
            </intent-filter>
        </service>

In the service class I created an according constant string identifying the service name like:

public class MyService extends ForeGroundService {
    public static final String MY_SERVICE = "it.unibz.bluedroid.bluetooth.service.MY_SERVICE";
   ...
}

and from the according Activity I call it with

startService(new Intent(MyService.MY_SERVICE));

and stop it with

stopService(new Intent(MyService.MY_SERVICE));

It works perfectly. Try to check your configuration and if you don't find anything strange try to debug whether your stopService get's called properly.

jquery .live('click') vs .click()

.live() is used if elements are being added after the initial page load. Say you have a button which gets added by an AJAX call after the page gets loaded. This new button will not be accessible using .click(), so you'll have to use .live('click')

pandas dataframe create new columns and fill with calculated values from same df

You can do this easily manually for each column like this:

df['A_perc'] = df['A']/df['sum']

If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):

ds.div(ds['sum'], axis=0)

And if you want this in one step added to the same dataframe:

>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
          A         B         C         D       sum    A_perc    B_perc  \
1  0.151722  0.935917  1.033526  0.941962  3.063127  0.049532  0.305543   
2  0.033761  1.087302  1.110695  1.401260  3.633017  0.009293  0.299283   
3  0.761368  0.484268  0.026837  1.276130  2.548603  0.298739  0.190013   

     C_perc    D_perc  sum_perc  
1  0.337409  0.307517         1  
2  0.305722  0.385701         1  
3  0.010530  0.500718         1  

How many characters can you store with 1 byte?

Yes, 1 byte does encode a character (inc spaces etc) from the ASCII set. However in data units assigned to character encoding it can and often requires in practice up to 4 bytes. This is because English is not the only character set. And even in English documents other languages and characters are often represented. The numbers of these are very many and there are very many other encoding sets, which you may have heard of e.g. BIG-5, UTF-8, UTF-32. Most computers now allow for these uses and ensure the least amount of garbled text (which usually means a missing encoding set.) 4 bytes is enough to cover these possible encodings. I byte per character does not allow for this and in use it is larger often 4 bytes per possible character for all encodings, not just ASCII. The final character may only need a byte to function or be represented on screen, but requires 4 bytes to be located in the rather vast global encoding "works".

React Native Change Default iOS Simulator Device

If you want to change default device and only have to run react-native run-ios you can search in finder for keyword "runios" then open folder and fixed index.js file change 'iphone X' to your device in need.

[1]: https://i.stack.imgur.com/BCtR1.png

JPA or JDBC, how are they different?

In layman's terms:

  • JDBC is a standard for Database Access
  • JPA is a standard for ORM

JDBC is a standard for connecting to a DB directly and running SQL against it - e.g SELECT * FROM USERS, etc. Data sets can be returned which you can handle in your app, and you can do all the usual things like INSERT, DELETE, run stored procedures, etc. It is one of the underlying technologies behind most Java database access (including JPA providers).

One of the issues with traditional JDBC apps is that you can often have some crappy code where lots of mapping between data sets and objects occur, logic is mixed in with SQL, etc.

JPA is a standard for Object Relational Mapping. This is a technology which allows you to map between objects in code and database tables. This can "hide" the SQL from the developer so that all they deal with are Java classes, and the provider allows you to save them and load them magically. Mostly, XML mapping files or annotations on getters and setters can be used to tell the JPA provider which fields on your object map to which fields in the DB. The most famous JPA provider is Hibernate, so it's a good place to start for concrete examples.

Other examples include OpenJPA, toplink, etc.

Under the hood, Hibernate and most other providers for JPA write SQL and use JDBC to read and write from and to the DB.

Stop handler.postDelayed()

You can use:

 Handler handler = new Handler()
 handler.postDelayed(new Runnable())

Or you can use:

 handler.removeCallbacksAndMessages(null);

Docs

public final void removeCallbacksAndMessages (Object token)

Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Or you could also do like the following:

Handler handler =  new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
    // do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);

Then:

handler.removeCallbacks(myRunnable);

Docs

public final void removeCallbacks (Runnable r)

Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.

public final void removeCallbacks (Runnable r, Object token)

Edit:

Change this:

@Override
public void onClick(View v) {
    Handler handler =  new Handler();
    Runnable myRunnable = new Runnable() {

To:

@Override
public void onClick(View v) {
    handler = new Handler();
    myRunnable = new Runnable() { /* ... */}

Because you have the below. Declared before onCreate but you re-declared and then initialized it in onClick leading to a NPE.

Handler handler; // declared before onCreate
Runnable myRunnable;

Is there a simple way to convert C++ enum to string?

This is a modification to @user3360260 answer. It has the following new features

  • MyEnum fromString(const string&) support
  • compiles with VisualStudio 2012
  • the enum is an actual POD type (not just const declarations), so you can assign it to a variable.
  • added C++ "range" feature (in form of vector) to allow "foreach" iteration over enum

Usage:

SMART_ENUM(MyEnum, ONE=1, TWO, THREE, TEN=10, ELEVEN)
MyEnum foo = MyEnum::TWO;
cout << MyEnum::toString(foo);  // static method
cout << foo.toString();         // member method
cout << MyEnum::toString(MyEnum::TWO);
cout << MyEnum::toString(10);
MyEnum foo = myEnum::fromString("TWO");

// C++11 iteration over all values
for( auto x : MyEnum::allValues() )
{
  cout << x.toString() << endl;
}

Here's the code

#define SMART_ENUM(EnumName, ...)                                   \
class EnumName                                                      \
{                                                                   \
public:                                                             \
    EnumName() : value(0) {}                                        \
    EnumName(int x) : value(x) {}                                   \
public:                                                             \
    enum {__VA_ARGS__};                                             \
private:                                                            \
    static void initMap(std::map<int, std::string>& tmp)                     \
    {                                                               \
        using namespace std;                                        \
                                                                    \
        int val = 0;                                                \
        string buf_1, buf_2, str = #__VA_ARGS__;                    \
        replace(str.begin(), str.end(), '=', ' ');                  \
        stringstream stream(str);                                   \
        vector<string> strings;                                     \
        while (getline(stream, buf_1, ','))                         \
            strings.push_back(buf_1);                               \
        for(vector<string>::iterator it = strings.begin();          \
                                                it != strings.end(); \
                                                ++it)                \
        {                                                           \
            buf_1.clear(); buf_2.clear();                           \
            stringstream localStream(*it);                          \
            localStream>> buf_1 >> buf_2;                           \
            if(buf_2.size() > 0)                                    \
                val = atoi(buf_2.c_str());                          \
            tmp[val++] = buf_1;                                     \
        }                                                           \
    }                                                               \
    int value;                                                      \
public:                                                             \
    operator int () const { return value; }                         \
    std::string toString(void) const {                              \
            return toString(value);                                 \
    }                                                               \
    static std::string toString(int aInt)                           \
    {                                                               \
        return nameMap()[aInt];                                     \
    }                                                               \
    static EnumName fromString(const std::string& s)                \
    {                                                               \
        auto it = find_if(nameMap().begin(), nameMap().end(), [s](const std::pair<int,std::string>& p) { \
            return p.second == s;                                   \
        });                                                         \
        if (it == nameMap().end()) {                                \
        /*value not found*/                                         \
            throw EnumName::Exception();                            \
        } else {                                                    \
            return EnumName(it->first);                             \
        }                                                           \
    }                                                               \
    class Exception : public std::exception {};                     \
    static std::map<int,std::string>& nameMap() {                   \
      static std::map<int,std::string> nameMap0;                    \
      if (nameMap0.size() ==0) initMap(nameMap0);                   \
      return nameMap0;                                              \
    }                                                               \
    static std::vector<EnumName> allValues() {                      \
      std::vector<EnumName> x{ __VA_ARGS__ };                       \
      return x;                                                     \
    }                                                               \
    bool operator<(const EnumName a) const { return (int)*this < (int)a; } \
};         

Note that the conversion toString is a fast has lookup, while the conversion fromString is a slow linear search. But strings are so expensive anyways(and the associated file IO), I didn't feel the need to optimize or use a bimap.

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

simple to fix you re is :

// example.d.ts
declare module 'foo';

if you want to declarate interface of object (Recommend for big project) you can use :

// example.d.ts
declare module 'foo'{
    // example
    export function getName(): string
}

How to use that? simple..

const x = require('foo') // or import x from 'foo'
x.getName() // intellisense can read this

SQL Server - stop or break execution of a SQL script

Back in the day we used the following...worked best:

RAISERROR ('Error! Connection dead', 20, 127) WITH LOG

No newline at end of file

If you add a new line of text at the end of the existing file which does not already have a newline character at the end, the diff will show the old last line as having been modified, even though conceptually it wasn’t.

This is at least one good reason to add a newline character at the end.

Example

A file contains:

A() {
    // do something
}

Hexdump:

00000000: 4128 2920 7b0a 2020 2020 2f2f 2064 6f20  A() {.    // do 
00000010: 736f 6d65 7468 696e 670a 7d              something.}

You now edit it to

A() {
    // do something
}
// Useful comment

Hexdump:

00000000: 4128 2920 7b0a 2020 2020 2f2f 2064 6f20  A() {.    // do 
00000010: 736f 6d65 7468 696e 670a 7d0a 2f2f 2055  something.}.// U
00000020: 7365 6675 6c20 636f 6d6d 656e 742e 0a    seful comment..

The git diff will show:

-}
\ No newline at end of file
+}
+// Useful comment.

In other words, it shows a larger diff than conceptually occurred. It shows that you deleted the line } and added the line }\n. This is, in fact, what happened, but it’s not what conceptually happened, so it can be confusing.

How to prompt for user input and read command-line arguments

If it's a 3.x version then just simply use:

variantname = input()

For example, you want to input 8:

x = input()
8

x will equal 8 but it's going to be a string except if you define it otherwise.

So you can use the convert command, like:

a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07

Group By Multiple Columns

group x by new { x.Col, x.Col}

How to convert a table to a data frame

I figured it out already:

as.data.frame.matrix(mytable) 

does what I need -- apparently, the table needs to somehow be converted to a matrix in order to be appropriately translated into a data frame. I found more details on this as.data.frame.matrix() function for contingency tables at the Computational Ecology blog.

Best Way to Refresh Adapter/ListView on Android

If you are using LoaderManager try with this statement:

getLoaderManager().restartLoader(0, null, this);

How to SELECT by MAX(date)?

This would work perfectely, if you are using current timestamp

SELECT * FROM reports WHERE date_entered = (SELECT max(date_entered) FROM REPORTS)

This would also work, if you are not using current timestamp but you are using date and time column seperately

SELECT * FROM reports WHERE date_entered = (SELECT max(date_entered) FROM REPORTS) ORDER BY time DESC LIMIT 1

Using Chrome, how to find to which events are bound to an element

Using Chrome 15.0.865.0 dev. There's an "Event Listeners" section on the Elements panel:

enter image description here

And an "Event Listeners Breakpoints" on the Scripts panel. Use a Mouse -> click breakpoint and then "step into next function call" while keeping an eye on the call stack to see what userland function handles the event. Ideally, you'd replace the minified version of jQuery with an unminified one so that you don't have to step in all the time, and use step over when possible.

enter image description here

How to identify platform/compiler from preprocessor macros?

See: http://predef.sourceforge.net/index.php

This project provides a reasonably comprehensive listing of pre-defined #defines for many operating systems, compilers, language and platform standards, and standard libraries.

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

Take a char input from the Scanner

You should use your custom input reader for faster results instead of extracting first character from reading String. Link for Custom ScanReader and explanation: https://gist.github.com/nik1010/5a90fa43399c539bb817069a14c3c5a8

Code for scanning Char :

BufferedInputStream br=new BufferedInputStream(System.in);
char a= (char)br.read();

How to find a number in a string using JavaScript?

Use a regular expression.

var r = /\d+/;
var s = "you can enter maximum 500 choices";
alert (s.match(r));

The expression \d+ means "one or more digits". Regular expressions by default are greedy meaning they'll grab as much as they can. Also, this:

var r = /\d+/;

is equivalent to:

var r = new RegExp("\d+");

See the details for the RegExp object.

The above will grab the first group of digits. You can loop through and find all matches too:

var r = /\d+/g;
var s = "you can enter 333 maximum 500 choices";
var m;
while ((m = r.exec(s)) != null) {
  alert(m[0]);
}

The g (global) flag is key for this loop to work.

Getting list of lists into pandas DataFrame

Even without pop the list we can do with set_index

pd.DataFrame(table).T.set_index(0).T
Out[11]: 
0 Heading1 Heading2
1        1        2
2        3        4

Update from_records

table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]

pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]: 
   Heading1  Heading2
0         1         2
1         3         4

How to pause for specific amount of time? (Excel/VBA)

Use the Wait method:

Application.Wait Now + #0:00:01#

or (for Excel 2010 and later):

Application.Wait Now + #12:00:01 AM#

How to use cURL to send Cookies?

If you have made that request in your application already, and see it logged in Google Dev Tools, you can use the copy cURL command from the context menu when right-clicking on the request in the network tab. Copy -> Copy as cURL. It will contain all headers, cookies, etc..

Why Doesn't C# Allow Static Methods to Implement an Interface?

Static classes should be able to do this so they can be used generically. I had to instead implement a Singleton to achieve the desired results.

I had a bunch of Static Business Layer classes that implemented CRUD methods like "Create", "Read", "Update", "Delete" for each entity type like "User", "Team", ect.. Then I created a base control that had an abstract property for the Business Layer class that implemented the CRUD methods. This allowed me to automate the "Create", "Read", "Update", "Delete" operations from the base class. I had to use a Singleton because of the Static limitation.

How do I automatically play a Youtube video (IFrame API) muted?

Update 2021 to loop and autoplay video on desktop/mobile devices (tested on iPhone X - Safari).

I am using the onPlayerStateChange event and if the video end, I play the video again. Refference to onPlayerStateChange event in YouTube API.

_x000D_
_x000D_
<div id="player"></div>
<script>
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var player;

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '100%',
      width: '100%',
      playerVars: {
        autoplay: 1,
        loop: 1,
        controls: 0,
        showinfo: 0,
        autohide: 1,
        playsinline: 1,
        mute: 1,
        modestbranding: 1,
        vq: 'hd1080'
      },
      videoId: 'ScMzIvxBSi4',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  function onPlayerReady(event) {
    event.target.mute();

    setTimeout(function() {
      event.target.playVideo();
    }, 0);
  }

  function onPlayerStateChange(event) {
    if (event.target.getPlayerState() == 0) {
      setTimeout(function() {
        event.target.playVideo();
      }, 0);
    }
  }
</script>
_x000D_
_x000D_
_x000D_

How to parse XML using shellscript?

This really is beyond the capabilities of shell script. Shell script and the standard Unix tools are okay at parsing line oriented files, but things change when you talk about XML. Even simple tags can present a problem:

<MYTAG>Data</MYTAG>

<MYTAG>
     Data
</MYTAG>

<MYTAG param="value">Data</MYTAG>

<MYTAG><ANOTHER_TAG>Data
</ANOTHER_TAG><MYTAG>

Imagine trying to write a shell script that can read the data enclosed in . The three very, very simply XML examples all show different ways this can be an issue. The first two examples are the exact same syntax in XML. The third simply has an attribute attached to it. The fourth contains the data in another tag. Simple sed, awk, and grep commands cannot catch all possibilities.

You need to use a full blown scripting language like Perl, Python, or Ruby. Each of these have modules that can parse XML data and make the underlying structure easier to access. I've use XML::Simple in Perl. It took me a few tries to understand it, but it did what I needed, and made my programming much easier.

How to extract numbers from a string and get an array of ints?

I found this expression simplest

String[] extractednums = msg.split("\\\\D++");

How to dismiss AlertDialog in android

Just set the view as null that will close the AlertDialog simple.

Why do we use __init__ in Python classes?

It seems like you need to use __init__ in Python if you want to correctly initialize mutable attributes of your instances.

See the following example:

>>> class EvilTest(object):
...     attr = []
... 
>>> evil_test1 = EvilTest()
>>> evil_test2 = EvilTest()
>>> evil_test1.attr.append('strange')
>>> 
>>> print "This is evil:", evil_test1.attr, evil_test2.attr
This is evil: ['strange'] ['strange']
>>> 
>>> 
>>> class GoodTest(object):
...     def __init__(self):
...         self.attr = []
... 
>>> good_test1 = GoodTest()
>>> good_test2 = GoodTest()
>>> good_test1.attr.append('strange')
>>> 
>>> print "This is good:", good_test1.attr, good_test2.attr
This is good: ['strange'] []

This is quite different in Java where each attribute is automatically initialized with a new value:

import java.util.ArrayList;
import java.lang.String;

class SimpleTest
{
    public ArrayList<String> attr = new ArrayList<String>();
}

class Main
{
    public static void main(String [] args)
    {
        SimpleTest t1 = new SimpleTest();
        SimpleTest t2 = new SimpleTest();

        t1.attr.add("strange");

        System.out.println(t1.attr + " " + t2.attr);
    }
}

produces an output we intuitively expect:

[strange] []

But if you declare attr as static, it will act like Python:

[strange] [strange]

Flutter : Vertically center column

You control how a row or column aligns its children using the mainAxisAlignment and crossAxisAlignment properties. For a row, the main axis runs horizontally and the cross axis runs vertically. For a column, the main axis runs vertically and the cross axis runs horizontally.

 mainAxisAlignment: MainAxisAlignment.center,
 crossAxisAlignment: CrossAxisAlignment.center,

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

I found a short cut rather than going through vs code appData/webCompiler, I added it as a dependency to my project with this cmd npm i caniuse-lite browserslist. But you might install it globally to avoid adding it to each project.

After installation, you could remove it from your project package.json and do npm i.

Update:

In case, Above solution didn't fix it. You could run npm update, as this would upgrade deprecated/outdated packages.

Note:

After you've run the npm update, there may be missing dependencies. Trace the error and install the missing dependencies. Mine was nodemon, which I fix by npm i nodemon -g

How to get on scroll events?

// @HostListener('scroll', ['$event']) // for scroll events of the current element
@HostListener('window:scroll', ['$event']) // for window scroll events
onScroll(event) {
  ...
}

or

<div (scroll)="onScroll($event)"></div>

Convert Object to JSON string

Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.

What does ^M character mean in Vim?

It probably means you've got carriage returns (different operating systems use different ways of signaling the end of line).

Use dos2unix to fix the files or set the fileformats in vim:

set ffs=unix,dos

How to change color of the back arrow in the new material theme?

The simplest (and best) way to change the color of the back/up-arrow. Best part is that there are no side-effects (unlike the other answers)!

  • Create a style with parent Widget.AppCompat.DrawerArrowToggle, define the color and any other attributes you'd like.
  • Set the style on the drawerArrowStyle attribute in the apps Theme.

Create style:

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <!--        Set that the nav buttons will animate-->
    <item name="spinBars">true</item>
    <!--        Set the color of the up arrow / hamburger button-->
    <item name="color">@color/white</item>
</style>

Set the style in App Theme:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <!--  Change global up-arrow color with no side-effects    -->
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

To change the ToolBar text color (and other attributes), create this style:

<style name="ToolbarStyle" parent="Widget.AppCompat.Toolbar">
    <item name="android:textColor">@color/white</item>
    <item name="titleTextColor">@color/white</item>
    <item name="colorControlNormal">@color/white</item> <!-- colorControlNormal is Probably not necessary    -->
</style>

Then set that style on the AppTheme:

<!-- Base application theme. -->
<style name="AppTheme.MyProduceApp" parent="Theme.MaterialComponents.Light.NoActionBar.Bridge">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <!--  Style the toolbar (mostly the color of the text) -->
    <item name="toolbarStyle">@style/ToolbarStyle</item>
    <!--  Change color of up-arrow    -->
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

Redirect all output to file in Bash

You can use exec command to redirect all stdout/stderr output of any commands later.

sample script:

exec 2> your_file2 > your_file1
your other commands.....

How to dismiss keyboard for UITextView with return key?

swift

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        textView.resignFirstResponder()
    }
    return true
}

and configure

Spin or rotate an image on hover

It's very simple.

  1. You add an image.
  2. You create a css property to this image.

    img { transition: all 0.3s ease-in-out 0s; }
    
  3. You add an animation like that:

    img:hover
    {
        cursor: default;
        transform: rotate(360deg);
        transition: all 0.3s ease-in-out 0s;
    }
    

npm throws error without sudo

sudo chown -R `whoami` /usr/local/lib

String.equals versus ==

== operator compares the reference of an object in Java. You can use string's equals method .

String s = "Test";
if(s.equals("Test"))
{
    System.out.println("Equal");
}

Finding row index containing maximum value using R

How about the following, where y is the name of your matrix and you are looking for the maximum in the entire matrix:

row(y)[y==max(y)]

if you want to extract the row:

y[row(y)[y==max(y)],] # this returns unsorted rows.

To return sorted rows use:

y[sort(row(y)[y==max(y)]),]

The advantage of this approach is that you can change the conditional inside to anything you need. Also, using col(y) and location of the hanging comma you can also extract columns.

y[,col(y)[y==max(y)]]

To find just the row for the max in a particular column, say column 2 you could use:

seq(along=y[,2])[y[,2]==max(y[,2])]

again the conditional is flexible to look for different requirements.

See Phil Spector's excellent "An introduction to S and S-Plus" Chapter 5 for additional ideas.

First char to upper case

String toCamelCase(String string) {
    StringBuffer sb = new StringBuffer(string);
    sb.replace(0, 1, string.substring(0, 1).toUpperCase());
    return sb.toString();

}

How to get text of an input text box during onKeyPress?

Try to concatenate the event charCode to the value you get. Here is a sample of my code:

<input type="text" name="price" onkeypress="return (cnum(event,this))" maxlength="10">
<p id="demo"></p>

js:

function cnum(event, str) {
    var a = event.charCode;
    var ab = str.value + String.fromCharCode(a);
    document.getElementById('demo').innerHTML = ab;
}

The value in ab will get the latest value in the input field.

Convert Bitmap to File

Most of the answers are too lengthy or too short not fulfilling the purpose. For those how are looking for Java or Kotlin code to Convert bitmap to File Object. Here is the detailed article I have written on the topic. Convert Bitmap to File in Android

public static File bitmapToFile(Context context,Bitmap bitmap, String fileNameToSave) { // File name like "image.png"
        //create a file to write bitmap data
        File file = null;
        try {
            file = new File(Environment.getExternalStorageDirectory() + File.separator + fileNameToSave);
            file.createNewFile();

//Convert bitmap to byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 0 , bos); // YOU can also save it in JPEG
            byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bitmapdata);
            fos.flush();
            fos.close();
            return file;
        }catch (Exception e){
            e.printStackTrace();
            return file; // it will return null
        }
    }

Load HTML page dynamically into div with jQuery

There's a jQuery plugin out there called pjax it states: "It's ajax with real permalinks, page titles, and a working back button that fully degrades."

The plugin uses HTML5 pushState and AJAX to dynamically change pages without a full load. If pushState isn't supported, PJAX performs a full page load, ensuring backwards compatibility.

What pjax does is that it listens on specified page elements such as <a>. Then when the <a href=""></a> element is invoked, the target page is fetched with either the X-PJAX header, or a specified fragment.

Example:

<script type="text/javascript">
  $(document).pjax('a', '#pjax-container');
</script>

Putting this code in the page header will listen on all links in the document and set the element that you are both fetching from the new page and replacing on the current page.

(meaning you want to replace #pjax-container on the current page with #pjax-container from the remote page)

When <a> is invoked, it will fetch the link with the request header X-PJAX and will look for the contents of #pjax-container in the result. If the result is #pjax-container, the container on the current page will be replaced with the new result.

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="jquery.min.js"></script>
  <script type="text/javascript" src="jquery.pjax.js"></script> 
  <script type="text/javascript">
    $(document).pjax('a', '#pjax-container');
  </script> 
</head>
<body>
  <h1>My Site</h1>
  <div class="container" id="pjax-container">
    Go to <a href="/page2">next page</a>.
  </div>
</body>
</html>

If #pjax-container is not the first element found in the response, PJAX will not recognize the content and perform a full page load on the requested link. To fix this, the server backend code would need to be set to only send #pjax-container.

Example server side code of page2:

//if header X-PJAX == true in request headers, send
<div class="container" id="pjax-container">
  Go to <a href="/page1">next page</a>.
</div>
//else send full page

If you can't change server-side code, then the fragment option is an alternative.

$(document).pjax('a', '#pjax-container', { 
  fragment: '#pjax-container' 
});

Note that fragment is an older pjax option and appears to fetch the child element of requested element.

How to check if a variable is a dictionary in Python?

How would you check if a variable is a dictionary in Python?

This is an excellent question, but it is unfortunate that the most upvoted answer leads with a poor recommendation, type(obj) is dict.

(Note that you should also not use dict as a variable name - it's the name of the builtin object.)

If you are writing code that will be imported and used by others, do not presume that they will use the dict builtin directly - making that presumption makes your code more inflexible and in this case, create easily hidden bugs that would not error the program out.

I strongly suggest, for the purposes of correctness, maintainability, and flexibility for future users, never having less flexible, unidiomatic expressions in your code when there are more flexible, idiomatic expressions.

is is a test for object identity. It does not support inheritance, it does not support any abstraction, and it does not support the interface.

So I will provide several options that do.

Supporting inheritance:

This is the first recommendation I would make, because it allows for users to supply their own subclass of dict, or a OrderedDict, defaultdict, or Counter from the collections module:

if isinstance(any_object, dict):

But there are even more flexible options.

Supporting abstractions:

from collections.abc import Mapping

if isinstance(any_object, Mapping):

This allows the user of your code to use their own custom implementation of an abstract Mapping, which also includes any subclass of dict, and still get the correct behavior.

Use the interface

You commonly hear the OOP advice, "program to an interface".

This strategy takes advantage of Python's polymorphism or duck-typing.

So just attempt to access the interface, catching the specific expected errors (AttributeError in case there is no .items and TypeError in case items is not callable) with a reasonable fallback - and now any class that implements that interface will give you its items (note .iteritems() is gone in Python 3):

try:
    items = any_object.items()
except (AttributeError, TypeError):
    non_items_behavior(any_object)
else: # no exception raised
    for item in items: ...

Perhaps you might think using duck-typing like this goes too far in allowing for too many false positives, and it may be, depending on your objectives for this code.

Conclusion

Don't use is to check types for standard control flow. Use isinstance, consider abstractions like Mapping or MutableMapping, and consider avoiding type-checking altogether, using the interface directly.

Laravel Soft Delete posts

Updated Version (Version 5.0 & Later):

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model {

    use SoftDeletes;

    protected $table = 'posts';

    // ...
}

When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, specify the softDelete property on the model (Documentation).

For (Version 4.2):

use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required

class Post extends Eloquent {

    use SoftDeletingTrait;

    protected $table = 'posts';

    // ...
}

Prior to Version 4.2 (But not 4.2 & Later)

For example (Using a posts table and Post model):

class Post extends Eloquent {

    protected $table = 'posts';
    protected $softDelete = true;
    
    // ...
}

To add a deleted_at column to your table, you may use the softDeletes method from a migration:

For example (Migration class' up method for posts table) :

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('posts', function(Blueprint $table)
    {
        $table->increments('id');
        // more fields
        $table->softDeletes(); // <-- This will add a deleted_at field
        $table->timeStamps();
    });
}

Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results. To soft delete a model you may use:

$model = Contents::find( $id );
$model->delete();

Deleted (soft) models are identified by the timestamp and if deleted_at field is NULL then it's not deleted and using the restore method actually makes the deleted_at field NULL. To permanently delete a model you may use forceDelete method.

How to make an HTTP get request with parameters

The WebRequest object seems like too much work for me. I prefer to use the WebClient control.

To use this function you just need to create two NameValueCollections holding your parameters and request headers.

Consider the following function:

    private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
    {
        string ResponseText = null;
        using (WebClient client = new WebClient())
        {
            try
            {
                if (RequestHeaders != null)
                {
                    if (RequestHeaders.Count > 0)
                    {
                        foreach (string header in RequestHeaders.AllKeys)
                            client.Headers.Add(header, RequestHeaders[header]);
                    }
                }
                if (QueryStringParameters != null)
                {
                    if (QueryStringParameters.Count > 0)
                    {
                        foreach (string parm in QueryStringParameters.AllKeys)
                            client.QueryString.Add(parm, QueryStringParameters[parm]);
                    }
                }
                byte[] ResponseBytes = client.DownloadData(URL);
                ResponseText = Encoding.UTF8.GetString(ResponseBytes);
            }
            catch (WebException exception)
            {
                if (exception.Response != null)
                {
                    var responseStream = exception.Response.GetResponseStream();

                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            Response.Write(reader.ReadToEnd());
                        }
                    }
                }
            }
        }
        return ResponseText;
    }

Add your querystring parameters (if required) as a NameValueCollection like so.

        NameValueCollection QueryStringParameters = new NameValueCollection();
        QueryStringParameters.Add("id", "123");
        QueryStringParameters.Add("category", "A");

Add your http headers (if required) as a NameValueCollection like so.

        NameValueCollection RequestHttpHeaders = new NameValueCollection();
        RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");

How to return result of a SELECT inside a function in PostgreSQL?

Hi please check the below link

https://www.postgresql.org/docs/current/xfunc-sql.html

EX:

CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;

jquery function setInterval

// simple example using the concept of setInterval

$(document).ready(function(){
var g = $('.jumping');
function blink(){
  g.animate({ 'left':'50px' 
  }).animate({
     'left':'20px'
        },1000)
}
setInterval(blink,1500);
});

How to get the device's IMEI/ESN programmatically in android?

Kotlin Code for getting DeviceId ( IMEI ) with handling permission & comparability check for all android versions :

 val  telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
        == PackageManager.PERMISSION_GRANTED) {
        // Permission is  granted
        val imei : String? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)  telephonyManager.imei
        // older OS  versions
        else  telephonyManager.deviceId

        imei?.let {
            Log.i("Log", "DeviceId=$it" )
        }

    } else {  // Permission is not granted

    }

Also add this permission to AndroidManifest.xml :

<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <!-- IMEI-->

Relative div height

When you set a percentage height on an element who's parent elements don't have heights set, the parent elements have a default

height: auto;

You are asking the browser to calculate a height from an undefined value. Since that would equal a null-value, the result is that the browser does nothing with the height of child elements.

Besides using a JavaScript solution you could use this deadly easy table method:

#parent3 {
    display: table;
    width: 100%;
}

#parent3 .between {
    display: table-row;
}

#parent3 .child {
    display: table-cell;
}

Preview on http://jsbin.com/IkEqAfi/1

  • Example 1: Not working
  • Example 2: Fix height
  • Example 3: Table method

But: Bare in mind, that the table method only works properly in all modern Browsers and the Internet Explorer 8 and higher. As Fallback you could use JavaScript.

Any way to generate ant build.xml file automatically from Eclipse?

I have been trying to do the same myself. What I found was that the "Export Ant Buildfile" gets kicked off in the org.eclipse.ant.internal.ui.datatransfer.AntBuildfileExportPage.java file. This resides in the org.eclipse.ant.ui plugin.

To view the source, use the Plug-in Development perspective and open the Plug-ins view. Then right-click on the org.eclipse.ant.ui plugin and select import as > source project.

My plan is to create a Java program to programmatically kick off the ant buildfile generation and call this in an Ant file every time I build by adding the ant file to the builders of my projects (Right-click preferences on a projet, under the builders tab).

Remove HTML Tags from an NSString on the iPhone

Another one way:

Interface:

-(NSString *) stringByStrippingHTML:(NSString*)inputString;

Implementation

(NSString *) stringByStrippingHTML:(NSString*)inputString
{ 
NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:[inputString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
NSString *str= [attrString string]; 

//you can add here replacements as your needs:
    [str stringByReplacingOccurrencesOfString:@"[" withString:@""];
    [str stringByReplacingOccurrencesOfString:@"]" withString:@""];
    [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    return str;
}

Realization

cell.exampleClass.text = [self stringByStrippingHTML:[exampleJSONParsingArray valueForKey: @"key"]];

or simple

NSString *myClearStr = [self stringByStrippingHTML:rudeStr];

How to play a local video with Swift?

gbk's solution in swift 3

PlayerView

import AVFoundation
import UIKit

class PlayerView: UIView {

override class var layerClass: AnyClass {
    return AVPlayerLayer.self
}

var player:AVPlayer? {
    set {
        if let layer = layer as? AVPlayerLayer {
            layer.player = player
        }
    }
    get {
        if let layer = layer as? AVPlayerLayer {
            return layer.player
        } else {
            return nil
        }
    }
}
}

VideoPlayer

import AVFoundation
import Foundation

protocol VideoPlayerDelegate {
    func downloadedProgress(progress:Double)
    func readyToPlay()
    func didUpdateProgress(progress:Double)
    func didFinishPlayItem()
    func didFailPlayToEnd()
}

let videoContext:UnsafeMutableRawPointer? = nil

class VideoPlayer : NSObject {



private var assetPlayer:AVPlayer?
private var playerItem:AVPlayerItem?
private var urlAsset:AVURLAsset?
private var videoOutput:AVPlayerItemVideoOutput?

private var assetDuration:Double = 0
private var playerView:PlayerView?

private var autoRepeatPlay:Bool = true
private var autoPlay:Bool = true

var delegate:VideoPlayerDelegate?

var playerRate:Float = 1 {
    didSet {
        if let player = assetPlayer {
            player.rate = playerRate > 0 ? playerRate : 0.0
        }
    }
}

var volume:Float = 1.0 {
    didSet {
        if let player = assetPlayer {
            player.volume = volume > 0 ? volume : 0.0
        }
    }
}

// MARK: - Init

convenience init(urlAsset: URL, view:PlayerView, startAutoPlay:Bool = true, repeatAfterEnd:Bool = true) {
    self.init()

    playerView = view
    autoPlay = startAutoPlay
    autoRepeatPlay = repeatAfterEnd

    if let playView = playerView, let playerLayer = playView.layer as? AVPlayerLayer {
        playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    }
    initialSetupWithURL(url: urlAsset)
    prepareToPlay()
}

override init() {
    super.init()
}

// MARK: - Public

func isPlaying() -> Bool {
    if let player = assetPlayer {
        return player.rate > 0
    } else {
        return false
    }
}

func seekToPosition(seconds:Float64) {
    if let player = assetPlayer {
        pause()
        if let timeScale = player.currentItem?.asset.duration.timescale {
            player.seek(to: CMTimeMakeWithSeconds(seconds, timeScale), completionHandler: { (complete) in
                self.play()
            })
        }
    }
}

func pause() {
    if let player = assetPlayer {
        player.pause()
    }
}

func play() {
    if let player = assetPlayer {
        if (player.currentItem?.status == .readyToPlay) {
            player.play()
            player.rate = playerRate
        }
    }
}

func cleanUp() {
    if let item = playerItem {
        item.removeObserver(self, forKeyPath: "status")
        item.removeObserver(self, forKeyPath: "loadedTimeRanges")
    }
    NotificationCenter.default.removeObserver(self)
    assetPlayer = nil
    playerItem = nil
    urlAsset = nil
}

// MARK: - Private

private func prepareToPlay() {
    let keys = ["tracks"]
    if let asset = urlAsset {
        asset.loadValuesAsynchronously(forKeys: keys, completionHandler: {
            DispatchQueue.main.async {
                self.startLoading()
            }
        })
    }
}

private func startLoading(){
    var error:NSError?
    guard let asset = urlAsset else {return}
    let status:AVKeyValueStatus = asset.statusOfValue(forKey: "tracks", error: &error)

    if status == AVKeyValueStatus.loaded {
        assetDuration = CMTimeGetSeconds(asset.duration)

        let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
        videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
        playerItem = AVPlayerItem(asset: asset)

        if let item = playerItem {
            item.addObserver(self, forKeyPath: "status", options: .initial, context: videoContext)
            item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new, .old], context: videoContext)

            NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(didFailedToPlayToEnd), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)

            if let output = videoOutput {
                item.add(output)

                item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithmVarispeed
                assetPlayer = AVPlayer(playerItem: item)

                if let player = assetPlayer {
                    player.rate = playerRate
                }

                addPeriodicalObserver()
                if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
                    layer.player = assetPlayer
                    print("player created")
                }
            }
        }
    }
}

private func addPeriodicalObserver() {
    let timeInterval = CMTimeMake(1, 1)

    if let player = assetPlayer {
        player.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main, using: { (time) in
            self.playerDidChangeTime(time: time)
        })
    }
}

private func playerDidChangeTime(time:CMTime) {
    if let player = assetPlayer {
        let timeNow = CMTimeGetSeconds(player.currentTime())
        let progress = timeNow / assetDuration

        delegate?.didUpdateProgress(progress: progress)
    }
}

@objc private func playerItemDidReachEnd() {
    delegate?.didFinishPlayItem()

    if let player = assetPlayer {
        player.seek(to: kCMTimeZero)
        if autoRepeatPlay == true {
            play()
        }
    }
}

@objc private func didFailedToPlayToEnd() {
    delegate?.didFailPlayToEnd()
}

private func playerDidChangeStatus(status:AVPlayerStatus) {
    if status == .failed {
        print("Failed to load video")
    } else if status == .readyToPlay, let player = assetPlayer {
        volume = player.volume
        delegate?.readyToPlay()

        if autoPlay == true && player.rate == 0.0 {
            play()
        }
    }
}

private func moviewPlayerLoadedTimeRangeDidUpdated(ranges:Array<NSValue>) {
    var maximum:TimeInterval = 0
    for value in ranges {
        let range:CMTimeRange = value.timeRangeValue
        let currentLoadedTimeRange = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration)
        if currentLoadedTimeRange > maximum {
            maximum = currentLoadedTimeRange
        }
    }
    let progress:Double = assetDuration == 0 ? 0.0 : Double(maximum) / assetDuration

    delegate?.downloadedProgress(progress: progress)
}

deinit {
    cleanUp()
}

private func initialSetupWithURL(url: URL) {
    let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
    urlAsset = AVURLAsset(url: url, options: options)
}

// MARK: - Observations

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if context == videoContext {
        if let key = keyPath {
            if key == "status", let player = assetPlayer {
                playerDidChangeStatus(status: player.status)
            } else if key == "loadedTimeRanges", let item = playerItem {
                moviewPlayerLoadedTimeRangeDidUpdated(ranges: item.loadedTimeRanges)
            }
        }
    }
}
}

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

You're most likely closing the session inside of the RoleDao. If you close the session then try to access a field on an object that was lazy-loaded, you will get this exception. You should probably open and close the session/transaction in your test.

How to stop an unstoppable zombie job on Jenkins without restarting the server?

The first proposed solution is pretty close. If you use stop() instead of interrupt() it even kills runaway threads, that run endlessly in a groovy system script. This will kill any build, that runs for a job. Here is the code:

Thread.getAllStackTraces().keySet().each() {
    if (it.name.contains('YOUR JOBNAME')) {  
      println "Stopping $it.name"
      it.stop()
    }
}

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

src absolute path problem

You should be referencing it as localhost. Like this:

<img src="http:\\localhost\site\img\mypicture.jpg"/>

How to represent a DateTime in Excel

Some versions of Excel don't have date-time formats available in the standard pick lists, but you can just enter a custom format string such as yyyy-mm-dd hh:mm:ss by:

  1. Right click -> Format Cells
  2. Number tab
  3. Choose Category Custom
  4. Enter your custom format string into the "Type" field

This works on my Excel 2010

MVC 4 @Scripts "does not exist"

For me this solved the problem, in NuGet package manager console write following:

update-package microsoft.aspnet.mvc -reinstall

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

Understanding that the Angular documents call checking the $$phase an anti-pattern, I tried to get $timeout and _.defer to work.

The timeout and deferred methods create a flash of unparsed {{myVar}} content in the dom like a FOUT. For me this was not acceptable. It leaves me without much to be told dogmatically that something is a hack, and not have a suitable alternative.

The only thing that works every time is:

if(scope.$$phase !== '$digest'){ scope.$digest() }.

I don't understand the danger of this method, or why it's described as a hack by people in the comments and the angular team. The command seems precise and easy to read:

"Do the digest unless one is already happening"

In CoffeeScript it's even prettier:

scope.$digest() unless scope.$$phase is '$digest'

What's the issue with this? Is there an alternative that won't create a FOUT? $safeApply looks fine but uses the $$phase inspection method, too.

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

Could you try this out?

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

Note: Setting Hidden to False will make the row visible

Run Excel Macro from Outside Excel Using VBScript From Command Line

I think you are trying to do this? (TRIED AND TESTED)

This code will open the file Test.xls and run the macro TestMacro which will in turn write to the text file TestResult.txt

Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\Test.xls", 0, True)
xlApp.Run "TestMacro"
xlBook.Close
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Echo "Finished."
WScript.Quit

Java 8 LocalDate Jackson format

As of 2020 and Jackson 2.10.1 there's no need for any special code, it's just a matter of telling Jackson what you want:

ObjectMapper objectMapper = new ObjectMapper();

// Register module that knows how to serialize java.time objects
// Provided by jackson-datatype-jsr310
objectMapper.registerModule(new JavaTimeModule());

// Ask Jackson to serialize dates as String (ISO-8601 by default)
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

This has already been mentioned in this answer, I'm adding a unit test verifying the functionality:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.Data;
import org.junit.jupiter.api.Test;

import java.time.LocalDate;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class LocalDateSerializationTest {

    @Data
    static class TestBean {
        // Accept default ISO-8601 format
        LocalDate birthDate;
        // Use custom format
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
        LocalDate birthDateWithCustomFormat;
    }

    @Test
    void serializeDeserializeTest() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        // Register module that knows how to serialize java.time objects
        objectMapper.registerModule(new JavaTimeModule());

        // Ask Jackson to serialize dates as String (ISO-8601 by default)
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        // The JSON string after serialization
        String json = "{\"birthDate\":\"2000-01-02\",\"birthDateWithCustomFormat\":\"03/02/2001\"}";

        // The object after deserialization
        TestBean object = new TestBean();
        object.setBirthDate(LocalDate.of(2000, 1, 2));
        object.setBirthDateWithCustomFormat(LocalDate.of(2001, 2, 3));

        // Assert serialization
        assertEquals(json, objectMapper.writeValueAsString(object));

        // Assert deserialization
        assertEquals(object, objectMapper.readValue(json, TestBean.class));
    }
}

TestBean uses Lombok to generate the boilerplate for the bean.

What is the best way to know if all the variables in a Class are null?

This can be done fairly easily using a Lombok generated equals and a static EMPTY object:

import lombok.Data;

public class EmptyCheck {
    public static void main(String[] args) {
        User user1 = new User();

        User user2 = new User();
        user2.setName("name");

        System.out.println(user1.isEmpty()); // prints true
        System.out.println(user2.isEmpty()); // prints false
    }

    @Data
    public static class User {
        private static final User EMPTY = new User();

        private String id;
        private String name;
        private int age;

        public boolean isEmpty() {
            return this.equals(EMPTY);
        }
    }
}

Prerequisites:

  • Default constructor should not be implemented with custom behavior as that is used to create the EMPTY object
  • All fields of the class should have an implemented equals (built-in Java types are usually not a problem, in case of custom types you can use Lombok)

Advantages:

  • No reflection involved
  • As new fields added to the class, this does not require any maintenance as due to Lombok they will be automatically checked in the equals implementation
  • Unlike some other answers this works not just for null checks but also for primitive types which have a non-null default value (e.g. if field is int it checks for 0, in case of boolean for false, etc.)

How do I find out if first character of a string is a number?

regular expression starts with number->'^[0-9]' 
Pattern pattern = Pattern.compile('^[0-9]');
 Matcher matcher = pattern.matcher(String);

if(matcher.find()){

System.out.println("true");
}

How to fix Warning Illegal string offset in PHP

Please check that your key exists in the array or not, instead of simply trying to access it.

Replace:

$myVar = $someArray['someKey']

With something like:

if (isset($someArray['someKey'])) {
    $myVar = $someArray['someKey']
}

or something like:

if(is_array($someArray['someKey'])) {
    $theme_img = 'recent_works_iso_thumbnail';
}else {
    $theme_img = 'recent_works_iso_thumbnail';
}

Set default value of javascript object attributes

Or you can try this

dict = {
 'somekey': 'somevalue'
};

val = dict['anotherkey'] || 'anotherval';

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

If you know what types your stack will be used with, you can instantiate them expicitly in the cpp file, and keep all relevant code there.

It is also possible to export these across DLLs (!) but it's pretty tricky to get the syntax right (MS-specific combinations of __declspec(dllexport) and the export keyword).

We've used that in a math/geom lib that templated double/float, but had quite a lot of code. (I googled around for it at the time, don't have that code today though.)

Plot a bar using matplotlib using a dictionary

Why not just:

names, counts = zip(*D.items())
plt.bar(names, counts)

enter image description here

How to get all elements inside "div" that starts with a known text

var $list = $('#divname input[id^="q17_"]');   // get all input controls with id q17_

// once you have $list you can do whatever you want

var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {

    var id = $(this).prop("id");      // get id
    var cbx = '';
    if ($(this).is(':checkbox') || $(this).is(':radio')) {
        // Need to see if this control is checked
    }
    else { 
        // Nope, not a checked control - so do something else
    }

});

Specifying number of decimal places in Python

This standard library solution likely has not been mentioned because the question is so dated. While these answers may scale to the other use cases beyond currency where differing levels of decimals are required, it seems you need it for currency.

I recommend you use the standard library locale.currency object. It seems to have been created to address this problem of currency representation.

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

locale.currency(1.23)
>>>'$1.23'
locale.currency(1.53251)
>>>'$1.23'
locale.currency(1)
>>>'$1.00'

locale.currency(mealPrice)

Currency generalizes to other countries as well.

sql like operator to get the numbers only

With SQL 2012 and later, you could use TRY_CAST/TRY_CONVERT to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL -- note though that this will match scientific notation too (1+E34). (If you use decimal, then scientific notation won't match)

Change Spinner dropdown icon

We can manage it by hiding the icon as i did:

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <Spinner android:id="@+id/fragment_filter_sp_users"
             android:layout_width="match_parent"
             android:background="@color/colorTransparent"
             android:layout_height="wrap_content"/>

    <ImageView
            android:layout_gravity="end|bottom"
            android:contentDescription="@null"
            android:layout_marginBottom="@dimen/_5sdp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_arrow_bottom"
    />
</FrameLayout>

Logging framework incompatibility

You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.

How to make ConstraintLayout work with percentage values?

It may be useful to have a quick reference here.

Placement of views

Use a guideline with app:layout_constraintGuide_percent like this:

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5"/>

And then you can use this guideline as anchor points for other views.

or

Use bias with app:layout_constraintHorizontal_bias and/or app:layout_constraintVertical_bias to modify view location when the available space allows

<Button
    ...
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintHorizontal_bias="0.25"
    ...
    />

Size of views

Another percent based value is height and/or width of elements, with app:layout_constraintHeight_percent and/or app:layout_constraintWidth_percent:

<Button
    ...
    android:layout_width="0dp"
    app:layout_constraintWidth_percent="0.5"
    ...
    />

Bitbucket fails to authenticate on git pull

You need to reset the password as shown below.

On macOS:

git config --global credential.helper osxkeychain

On Windows 10:

git config --global credential.helper store

After executing this, it prompts you for the user name and password for your repo.

Why would $_FILES be empty when uploading files to PHP?

I was struggling with the same problem and testing everything, not getting error reporting and nothing seemed to be wrong. I had error_reporting(E_ALL) But suddenly I realized that I had not checked the apache log and voilà! There was a syntax error on the script...! (a missing "}" )

So, even though this is something evident to be checked, it can be forgotten... In my case (linux) it is at:

/var/log/apache2/error.log

Select NOT IN multiple columns

You should probably use NOT EXISTS for multiple columns.

Drop Down Menu/Text Field in one

I'd like to add a jQuery autocomplete based solution that does the job.

Step 1: Make the list fixed height and scrollable

Get the code from https://jqueryui.com/autocomplete/ "Scrollable" example, setting max height to the list of results so it behaves as a select box.

Step 2: Open the list on focus:

Display jquery ui auto-complete list on focus event

Step 3: Set minimum chars to 0 so it opens no matter how many chars are in the input

Final result:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Scrollable results</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  .ui-autocomplete {
    max-height: 100px;
    overflow-y: auto;
    /* prevent horizontal scrollbar */
    overflow-x: hidden;
  }
  /* IE 6 doesn't support max-height
   * we use height instead, but this forces the menu to always be this tall
   */
  * html .ui-autocomplete {
    height: 100px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
//      source: availableTags, // uncomment this and comment the following to have normal autocomplete behavior
      source: function (request, response) {
          response( availableTags);
      },
      minLength: 0
    }).focus(function(){
//        $(this).data("uiAutocomplete").search($(this).val()); // uncomment this and comment the following to have autocomplete behavior when opening
        $(this).data("uiAutocomplete").search('');
    });
  } );
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>


</body>
</html>

Check jsfiddle here:

https://jsfiddle.net/bao7fhm3/1/

Notepad++ Setting for Disabling Auto-open Previous Files

Go to: Settings > Preferences > Backup > and Uncheck Remember current session for next launch

In older versions (6.5-), this option is located on Settings > Preferences > MISC.

Disable validation of HTML5 form elements

Instead of trying to do an end run around the browser's validation, you could put the http:// in as placeholder text. This is from the very page you linked:

Placeholder Text

The first improvement HTML5 brings to web forms is the ability to set placeholder text in an input field. Placeholder text is displayed inside the input field as long as the field is empty and not focused. As soon as you click on (or tab to) the input field, the placeholder text disappears.

You’ve probably seen placeholder text before. For example, Mozilla Firefox 3.5 now includes placeholder text in the location bar that reads “Search Bookmarks and History”:

enter image description here

When you click on (or tab to) the location bar, the placeholder text disappears:

enter image description here

Ironically, Firefox 3.5 does not support adding placeholder text to your own web forms. C’est la vie.

Placeholder Support

IE  FIREFOX SAFARI  CHROME  OPERA   IPHONE  ANDROID
·   3.7+    4.0+    4.0+    ·       ·       ·

Here’s how you can include placeholder text in your own web forms:

<form>
  <input name="q" placeholder="Search Bookmarks and History">
  <input type="submit" value="Search">
</form>

Browsers that don’t support the placeholder attribute will simply ignore it. No harm, no foul. See whether your browser supports placeholder text.

It wouldn't be exactly the same since it wouldn't provide that "starting point" for the user, but it's halfway there at least.

Deleting all files from a folder using PHP?

Assuming you have a folder with A LOT of files reading them all and then deleting in two steps is not that performing. I believe the most performing way to delete files is to just use a system command.

For example on linux I use :

exec('rm -f '. $absolutePathToFolder .'*');

Or this if you want recursive deletion without the need to write a recursive function

exec('rm -f -r '. $absolutePathToFolder .'*');

the same exact commands exists for any OS supported by PHP. Keep in mind this is a PERFORMING way of deleting files. $absolutePathToFolder MUST be checked and secured before running this code and permissions must be granted.

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

When you say 2^8 you get 256, but the numbers in computers terms begins from the number 0. So, then you got the 255, you can probe it in a internet mask for the IP or in the IP itself.

255 is the maximum value of a 8 bit integer : 11111111 = 255

Does that help?

Youtube iframe wmode issue

Adding ?wmode=opaque to the URL seems to solve this problem for me, although I have not tested it in IE yet.

For those of you having troubles with the previously proposed solution, note that an inital ampersand will only work if you are already supplying other arguments to the URL. The first argument must have an initial question mark: http://www.example.com?first=foo&second=bar

How to create a dotted <hr/> tag?

You can do:

<hr style="border: 1px dashed black;" />

Demo: http://jsfiddle.net/JMfC9/

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

How to convert a Django QuerySet to a list

You can directly convert using the list keyword. For example:

obj=emp.objects.all()
list1=list(obj)

Using the above code you can directly convert a query set result into a list.

Here list is keyword and obj is result of query set and list1 is variable in that variable we are storing the converted result which in list.

Linq with group by having count

For anyone looking to do this in vb (as I was and couldn't find anything)

From c In db.Company 
Select c.Name Group By Name Into Group 
Where Group.Count > 1

Elasticsearch difference between MUST and SHOULD bool query

Since this is a popular question, I would like to add that in Elasticsearch version 2 things changed a bit.

Instead of filtered query, one should use bool query in the top level.

If you don't care about the score of must parts, then put those parts into filter key. No scoring means faster search. Also, Elasticsearch will automatically figure out, whether to cache them, etc. must_not is equally valid for caching.

Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

Also, mind that "gte": "now" cannot be cached, because of millisecond granularity. Use two ranges in a must clause: one with now/1h and another with now so that the first can be cached for a while and the second for precise filtering accelerated on a smaller result set.

How to know Hive and Hadoop versions from command prompt?

Yes you can get version of your hive by using "hive command":

hive --service version

You can get a list of available service names by using following "hive command":

hive --service help

Disable Copy or Paste action for text box?

See this example. You need to bind the event key propagation

$(document).ready(function () {
    $('#confirmEmail').keydown(function (e) {
        if (e.ctrlKey && (e.keyCode == 88 || e.keyCode == 67 || e.keyCode == 86)) {
            return false;
        }
    });
});

Socket send and receive byte array

First, do not use DataOutputStream unless it’s really necessary. Second:

Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);

Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.

Push origin master error on new repository

I had the same error, as Bombe said I had no local branch named master in my config, although git branch did list a branch named master...

To fix it just add this to your .git/config

[branch "master"]
    remote = origin
    merge = refs/heads/master

Kinda hacky but does the job

align divs to the bottom of their container

I don't like absolute positioning, either, because there is almost always some collateral damage, i.e. unintended side effects. Especially when you are working with a responsive design. There seems to be an alternative - the sandbag technique. By inserting a "helper" element, either in the markup of via CSS, we can push elements down to the bottom of the container. See http://community.sitepoint.com/t/css-floating-divs-to-the-bottom-inside-a-div/20932 for examples.

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

select DocumentFormat.OpenXml under references , view it's properties, and set the Copy Local option to True so that it copies it to the output folder. That worked for me.

Where does gcc look for C and C++ header files?

g++ -print-search-dirs
gcc -print-search-dirs

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Usually, deleting the current emulator that doesn't work anymore and creating it again will solve the issue. I've had it 5 minutes ago and that's how I solved it.

Unexpected token ILLEGAL in webkit

It doesn't apply to this particular code example, but as Google food, since I got the same error message:

<script>document.write('<script src="…"></script>');</script>

will give this error but

<script>document.write('<script src="…"><'+'/script>');</script>

will not.

Further explanation here: Why split the <script> tag when writing it with document.write()?

onCreateOptionsMenu inside Fragments

Set setHasMenuOptions(true) works if application has a theme with Actionbar such as Theme.MaterialComponents.DayNight.DarkActionBar or Activity has it's own Toolbar, otherwise onCreateOptionsMenu in fragment does not get called.

If you want to use standalone Toolbar you either need to get activity and set your Toolbar as support action bar with

(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)

which lets your fragment onCreateOptionsMenu to be called.

Other alternative is, you can inflate your Toolbar's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU) and item listener with

toolbar.setOnMenuItemClickListener {
   // do something
   true
}

Android: how to refresh ListView contents?

Another easy way:

//In your ListViewActivity:
public void refreshListView() {
    listAdapter = new ListAdapter(this);
    setListAdapter(listAdapter);
}

Javascript Cookie with no expiration date

If you don't set an expiration date the cookie will expire at the end of the user's session. I recommend using the date right before unix epoch time will extend passed a 32-bit integer. To put that in the cookie you would use document.cookie = "randomCookie=true; expires=Tue, 19 Jan 2038 03:14:07 UTC;, assuming that randomCookie is the cookie you are setting and true is it's respective value.

Why am I getting the message, "fatal: This operation must be run in a work tree?"

In addition, apparently, this error will happen if you clone into NTFS Ram Drive.

How to use 'find' to search for files created on a specific date?

find location -ctime time_period

Examples of time_period:

  • More than 30 days ago: -ctime +30

  • Less than 30 days ago: -ctime -30

  • Exactly 30 days ago: -ctime 30

How to create materialized views in SQL Server?

Although purely from engineering perspective, indexed views sound like something everybody could use to improve performance but the real life scenario is very different. I have been unsuccessful is using indexed views where I most need them because of too many restrictions on what can be indexed and what cannot.

If you have outer joins in the views, they cannot be used. Also, common table expressions are not allowed... In fact if you have any ordering in subselects or derived tables (such as with partition by clause), you are out of luck too.

That leaves only very simple scenarios to be utilizing indexed views, something in my opinion can be optimized by creating proper indexes on underlying tables anyway.

I will be thrilled to hear some real life scenarios where people have actually used indexed views to their benefit and could not have done without them

How to update Android Studio automatically?

I am having a similar problem while updating from 2.3.2 to 2.3.3.

Go to the bin folder of your Android Studio installation folder: e.g.

cd opt/android-studio/bin

Provide run permission for studio.sh file: chmod +x studio.sh

Run Android Studio from here: ./studio.sh

and try "update and restart" from android studio.

Reading binary file and looping over each byte

This post itself is not a direct answer to the question. What it is instead is a data-driven extensible benchmark that can be used to compare many of the answers (and variations of utilizing new features added in later, more modern, versions of Python) that have been posted to this question — and should therefore be helpful in determining which has the best performance.

In a few cases I've modified the code in the referenced answer to make it compatible with the benchmark framework.

First, here are the results for what currently are the latest versions of Python 2 & 3:

Fastest to slowest execution speeds with 32-bit Python 2.7.16
  numpy version 1.16.5
  Test file size: 1,024 KiB
  100 executions, best of 3 repetitions

1                  Tcll (array.array) :   3.8943 secs, rel speed   1.00x,   0.00% slower (262.95 KiB/sec)
2  Vinay Sajip (read all into memory) :   4.1164 secs, rel speed   1.06x,   5.71% slower (248.76 KiB/sec)
3            codeape + iter + partial :   4.1616 secs, rel speed   1.07x,   6.87% slower (246.06 KiB/sec)
4                             codeape :   4.1889 secs, rel speed   1.08x,   7.57% slower (244.46 KiB/sec)
5               Vinay Sajip (chunked) :   4.1977 secs, rel speed   1.08x,   7.79% slower (243.94 KiB/sec)
6           Aaron Hall (Py 2 version) :   4.2417 secs, rel speed   1.09x,   8.92% slower (241.41 KiB/sec)
7                     gerrit (struct) :   4.2561 secs, rel speed   1.09x,   9.29% slower (240.59 KiB/sec)
8                     Rick M. (numpy) :   8.1398 secs, rel speed   2.09x, 109.02% slower (125.80 KiB/sec)
9                           Skurmedel :  31.3264 secs, rel speed   8.04x, 704.42% slower ( 32.69 KiB/sec)

Benchmark runtime (min:sec) - 03:26

Fastest to slowest execution speeds with 32-bit Python 3.8.0
  numpy version 1.17.4
  Test file size: 1,024 KiB
  100 executions, best of 3 repetitions

1  Vinay Sajip + "yield from" + "walrus operator" :   3.5235 secs, rel speed   1.00x,   0.00% slower (290.62 KiB/sec)
2                       Aaron Hall + "yield from" :   3.5284 secs, rel speed   1.00x,   0.14% slower (290.22 KiB/sec)
3         codeape + iter + partial + "yield from" :   3.5303 secs, rel speed   1.00x,   0.19% slower (290.06 KiB/sec)
4                      Vinay Sajip + "yield from" :   3.5312 secs, rel speed   1.00x,   0.22% slower (289.99 KiB/sec)
5      codeape + "yield from" + "walrus operator" :   3.5370 secs, rel speed   1.00x,   0.38% slower (289.51 KiB/sec)
6                          codeape + "yield from" :   3.5390 secs, rel speed   1.00x,   0.44% slower (289.35 KiB/sec)
7                                      jfs (mmap) :   4.0612 secs, rel speed   1.15x,  15.26% slower (252.14 KiB/sec)
8              Vinay Sajip (read all into memory) :   4.5948 secs, rel speed   1.30x,  30.40% slower (222.86 KiB/sec)
9                        codeape + iter + partial :   4.5994 secs, rel speed   1.31x,  30.54% slower (222.64 KiB/sec)
10                                        codeape :   4.5995 secs, rel speed   1.31x,  30.54% slower (222.63 KiB/sec)
11                          Vinay Sajip (chunked) :   4.6110 secs, rel speed   1.31x,  30.87% slower (222.08 KiB/sec)
12                      Aaron Hall (Py 2 version) :   4.6292 secs, rel speed   1.31x,  31.38% slower (221.20 KiB/sec)
13                             Tcll (array.array) :   4.8627 secs, rel speed   1.38x,  38.01% slower (210.58 KiB/sec)
14                                gerrit (struct) :   5.0816 secs, rel speed   1.44x,  44.22% slower (201.51 KiB/sec)
15                 Rick M. (numpy) + "yield from" :  11.8084 secs, rel speed   3.35x, 235.13% slower ( 86.72 KiB/sec)
16                                      Skurmedel :  11.8806 secs, rel speed   3.37x, 237.18% slower ( 86.19 KiB/sec)
17                                Rick M. (numpy) :  13.3860 secs, rel speed   3.80x, 279.91% slower ( 76.50 KiB/sec)

Benchmark runtime (min:sec) - 04:47

I also ran it with a much larger 10 MiB test file (which took nearly an hour to run) and got performance results which were comparable to those shown above.

Here's the code used to do the benchmarking:

from __future__ import print_function
import array
import atexit
from collections import deque, namedtuple
import io
from mmap import ACCESS_READ, mmap
import numpy as np
from operator import attrgetter
import os
import random
import struct
import sys
import tempfile
from textwrap import dedent
import time
import timeit
import traceback

try:
    xrange
except NameError:  # Python 3
    xrange = range


class KiB(int):
    """ KibiBytes - multiples of the byte units for quantities of information. """
    def __new__(self, value=0):
        return 1024*value


BIG_TEST_FILE = 1  # MiBs or 0 for a small file.
SML_TEST_FILE = KiB(64)
EXECUTIONS = 100  # Number of times each "algorithm" is executed per timing run.
TIMINGS = 3  # Number of timing runs.
CHUNK_SIZE = KiB(8)
if BIG_TEST_FILE:
    FILE_SIZE = KiB(1024) * BIG_TEST_FILE
else:
    FILE_SIZE = SML_TEST_FILE  # For quicker testing.

# Common setup for all algorithms -- prefixed to each algorithm's setup.
COMMON_SETUP = dedent("""
    # Make accessible in algorithms.
    from __main__ import array, deque, get_buffer_size, mmap, np, struct
    from __main__ import ACCESS_READ, CHUNK_SIZE, FILE_SIZE, TEMP_FILENAME
    from functools import partial
    try:
        xrange
    except NameError:  # Python 3
        xrange = range
""")


def get_buffer_size(path):
    """ Determine optimal buffer size for reading files. """
    st = os.stat(path)
    try:
        bufsize = st.st_blksize # Available on some Unix systems (like Linux)
    except AttributeError:
        bufsize = io.DEFAULT_BUFFER_SIZE
    return bufsize

# Utility primarily for use when embedding additional algorithms into benchmark.
VERIFY_NUM_READ = """
    # Verify generator reads correct number of bytes (assumes values are correct).
    bytes_read = sum(1 for _ in file_byte_iterator(TEMP_FILENAME))
    assert bytes_read == FILE_SIZE, \
           'Wrong number of bytes generated: got {:,} instead of {:,}'.format(
                bytes_read, FILE_SIZE)
"""

TIMING = namedtuple('TIMING', 'label, exec_time')

class Algorithm(namedtuple('CodeFragments', 'setup, test')):

    # Default timeit "stmt" code fragment.
    _TEST = """
        #for b in file_byte_iterator(TEMP_FILENAME):  # Loop over every byte.
        #    pass  # Do stuff with byte...
        deque(file_byte_iterator(TEMP_FILENAME), maxlen=0)  # Data sink.
    """

    # Must overload __new__ because (named)tuples are immutable.
    def __new__(cls, setup, test=None):
        """ Dedent (unindent) code fragment string arguments.
        Args:
          `setup` -- Code fragment that defines things used by `test` code.
                     In this case it should define a generator function named
                     `file_byte_iterator()` that will be passed that name of a test file
                     of binary data. This code is not timed.
          `test` -- Code fragment that uses things defined in `setup` code.
                    Defaults to _TEST. This is the code that's timed.
        """
        test =  cls._TEST if test is None else test  # Use default unless one is provided.

        # Uncomment to replace all performance tests with one that verifies the correct
        # number of bytes values are being generated by the file_byte_iterator function.
        #test = VERIFY_NUM_READ

        return tuple.__new__(cls, (dedent(setup), dedent(test)))


algorithms = {

    'Aaron Hall (Py 2 version)': Algorithm("""
        def file_byte_iterator(path):
            with open(path, "rb") as file:
                callable = partial(file.read, 1024)
                sentinel = bytes() # or b''
                for chunk in iter(callable, sentinel):
                    for byte in chunk:
                        yield byte
    """),

    "codeape": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                while True:
                    chunk = f.read(chunksize)
                    if chunk:
                        for b in chunk:
                            yield b
                    else:
                        break
    """),

    "codeape + iter + partial": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                for chunk in iter(partial(f.read, chunksize), b''):
                    for b in chunk:
                        yield b
    """),

    "gerrit (struct)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                fmt = '{}B'.format(FILE_SIZE)  # Reads entire file at once.
                for b in struct.unpack(fmt, f.read()):
                    yield b
    """),

    'Rick M. (numpy)': Algorithm("""
        def file_byte_iterator(filename):
            for byte in np.fromfile(filename, 'u1'):
                yield byte
    """),

    "Skurmedel": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                byte = f.read(1)
                while byte:
                    yield byte
                    byte = f.read(1)
    """),

    "Tcll (array.array)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                arr = array.array('B')
                arr.fromfile(f, FILE_SIZE)  # Reads entire file at once.
                for b in arr:
                    yield b
    """),

    "Vinay Sajip (read all into memory)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                bytes_read = f.read()  # Reads entire file at once.
            for b in bytes_read:
                yield b
    """),

    "Vinay Sajip (chunked)": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                chunk = f.read(chunksize)
                while chunk:
                    for b in chunk:
                        yield b
                    chunk = f.read(chunksize)
    """),

}  # End algorithms

#
# Versions of algorithms that will only work in certain releases (or better) of Python.
#
if sys.version_info >= (3, 3):
    algorithms.update({

        'codeape + iter + partial + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    for chunk in iter(partial(f.read, chunksize), b''):
                        yield from chunk
        """),

        'codeape + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while True:
                        chunk = f.read(chunksize)
                        if chunk:
                            yield from chunk
                        else:
                            break
        """),

        "jfs (mmap)": Algorithm("""
            def file_byte_iterator(filename):
                with open(filename, "rb") as f, \
                     mmap(f.fileno(), 0, access=ACCESS_READ) as s:
                    yield from s
        """),

        'Rick M. (numpy) + "yield from"': Algorithm("""
            def file_byte_iterator(filename):
            #    data = np.fromfile(filename, 'u1')
                yield from np.fromfile(filename, 'u1')
        """),

        'Vinay Sajip + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    chunk = f.read(chunksize)
                    while chunk:
                        yield from chunk  # Added in Py 3.3
                        chunk = f.read(chunksize)
        """),

    })  # End Python 3.3 update.

if sys.version_info >= (3, 5):
    algorithms.update({

        'Aaron Hall + "yield from"': Algorithm("""
            from pathlib import Path

            def file_byte_iterator(path):
                ''' Given a path, return an iterator over the file
                    that lazily loads the file.
                '''
                path = Path(path)
                bufsize = get_buffer_size(path)

                with path.open('rb') as file:
                    reader = partial(file.read1, bufsize)
                    for chunk in iter(reader, bytes()):
                        yield from chunk
        """),

    })  # End Python 3.5 update.

if sys.version_info >= (3, 8, 0):
    algorithms.update({

        'Vinay Sajip + "yield from" + "walrus operator"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while chunk := f.read(chunksize):
                        yield from chunk  # Added in Py 3.3
        """),

        'codeape + "yield from" + "walrus operator"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while chunk := f.read(chunksize):
                        yield from chunk
        """),

    })  # End Python 3.8.0 update.update.


#### Main ####

def main():
    global TEMP_FILENAME

    def cleanup():
        """ Clean up after testing is completed. """
        try:
            os.remove(TEMP_FILENAME)  # Delete the temporary file.
        except Exception:
            pass

    atexit.register(cleanup)

    # Create a named temporary binary file of pseudo-random bytes for testing.
    fd, TEMP_FILENAME = tempfile.mkstemp('.bin')
    with os.fdopen(fd, 'wb') as file:
         os.write(fd, bytearray(random.randrange(256) for _ in range(FILE_SIZE)))

    # Execute and time each algorithm, gather results.
    start_time = time.time()  # To determine how long testing itself takes.

    timings = []
    for label in algorithms:
        try:
            timing = TIMING(label,
                            min(timeit.repeat(algorithms[label].test,
                                              setup=COMMON_SETUP + algorithms[label].setup,
                                              repeat=TIMINGS, number=EXECUTIONS)))
        except Exception as exc:
            print('{} occurred timing the algorithm: "{}"\n  {}'.format(
                    type(exc).__name__, label, exc))
            traceback.print_exc(file=sys.stdout)  # Redirect to stdout.
            sys.exit(1)
        timings.append(timing)

    # Report results.
    print('Fastest to slowest execution speeds with {}-bit Python {}.{}.{}'.format(
            64 if sys.maxsize > 2**32 else 32, *sys.version_info[:3]))
    print('  numpy version {}'.format(np.version.full_version))
    print('  Test file size: {:,} KiB'.format(FILE_SIZE // KiB(1)))
    print('  {:,d} executions, best of {:d} repetitions'.format(EXECUTIONS, TIMINGS))
    print()

    longest = max(len(timing.label) for timing in timings)  # Len of longest identifier.
    ranked = sorted(timings, key=attrgetter('exec_time')) # Sort so fastest is first.
    fastest = ranked[0].exec_time
    for rank, timing in enumerate(ranked, 1):
        print('{:<2d} {:>{width}} : {:8.4f} secs, rel speed {:6.2f}x, {:6.2f}% slower '
              '({:6.2f} KiB/sec)'.format(
                    rank,
                    timing.label, timing.exec_time, round(timing.exec_time/fastest, 2),
                    round((timing.exec_time/fastest - 1) * 100, 2),
                    (FILE_SIZE/timing.exec_time) / KiB(1),  # per sec.
                    width=longest))
    print()
    mins, secs = divmod(time.time()-start_time, 60)
    print('Benchmark runtime (min:sec) - {:02d}:{:02d}'.format(int(mins),
                                                               int(round(secs))))

main()

bash, extract string before a colon

This works for me you guys can try it out

INPUT='ubuntu:x:1000:1000:Ubuntu:/home/ubuntu:/bin/bash'
SUBSTRING=$(echo $INPUT| cut -d: -f1)
echo $SUBSTRING

What is `related_name` used for in Django?

prefetch_related use for prefetch data for Many to many and many to one relationship data. select_related is to select data from a single value relationship. Both of these are used to fetch data from their relationships from a model. For example, you build a model and a model that has a relationship with other models. When a request comes you will also query for their relationship data and Django has very good mechanisms To access data from their relationship like book.author.name but when you iterate a list of models for fetching their relationship data Django create each request for every single relationship data. To overcome this we do have prefetchd_related and selected_related

How to get the number of characters in a string

There are several ways to get a string length:

package main

import (
    "bytes"
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    b := "?????"
    len1 := len([]rune(b))
    len2 := bytes.Count([]byte(b), nil) -1
    len3 := strings.Count(b, "") - 1
    len4 := utf8.RuneCountInString(b)
    fmt.Println(len1)
    fmt.Println(len2)
    fmt.Println(len3)
    fmt.Println(len4)

}

Fatal error: Call to undefined function socket_create()

For a typical XAMPP install on windows you probably have the php_sockets.dll in your C:\xampp\php\ext directory. All you got to do is go to php.ini in the C:\xampp\php directory and change the ;extension=php_sockets.dll to extension=php_sockets.dll.

javax vs java package

java.* packages are the core Java language packages, meaning that programmers using the Java language had to use them in order to make any worthwhile use of the java language.

javax.* packages are optional packages, which provides a standard, scalable way to make custom APIs available to all applications running on the Java platform.

Maximum length for MySQL type text

TINYTEXT: 256 bytes
TEXT: 65,535 bytes
MEDIUMTEXT: 16,777,215 bytes
LONGTEXT: 4,294,967,295 bytes

Java RegEx meta character (.) and ordinary dot?

Escape special characters with a backslash. \., \*, \+, \\d, and so on. If you are unsure, you may escape any non-alphabetical character whether it is special or not. See the javadoc for java.util.regex.Pattern for further information.

Measuring elapsed time with the Time module

You need to import time and then use time.time() method to know current time.

import time

start_time=time.time() #taking current time as starting time

#here your code

elapsed_time=time.time()-start_time #again taking current time - starting time 

Why is IoC / DI not common in Python?

I agree with @Jorg in the point that DI/IoC is possible, easier and even more beautiful in Python. What's missing is the frameworks supporting it, but there are a few exceptions. To point a couple of examples that come to my mind:

  • Django comments let you wire your own Comment class with your custom logic and forms. [More Info]

  • Django let you use a custom Profile object to attach to your User model. This is not completely IoC but is a good approach. Personally I'd like to replace the hole User model as the comments framework does. [More Info]

How to save user input into a variable in html and js

I found this to work best for me https://jsfiddle.net/Lu92akv6/ [I found this to work for me try this fiddle][1]

_x000D_
_x000D_
document.getElementById("btnmyNumber").addEventListener("click", myFunctionVar);_x000D_
function myFunctionVar() {_x000D_
  var numberr = parseInt(document.getElementById("myNumber").value, 10);_x000D_
  // alert(numberr);_x000D_
  if ( numberr > 1) {_x000D_
_x000D_
    document.getElementById("minusE5").style.display = "none";_x000D_
_x000D_
_x000D_
_x000D_
}}
_x000D_
   <form onsubmit="return false;">_x000D_
       <input class="button button3" type="number" id="myNumber" value="" min="0" max="30">_x000D_
       <input type="submit" id="btnmyNumber">_x000D_
_x000D_
       </form>
_x000D_
_x000D_
_x000D_

How do I create a HTTP Client Request with a cookie?

This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution


Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.

// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request

var http = require('http');

var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'

var client = http.createClient(80, 'www.example.com');

var headers = {
    'Host': 'www.example.com',
    'Cookie': cookie,
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data,'utf8')
};

var request = client.request('POST', '/', headers);

// listening to the response is optional, I suppose
request.on('response', function(response) {
  response.on('data', function(chunk) {
    // do what you do
  });
  response.on('end', function() {
    // do what you do
  });
});
// you'd also want to listen for errors in production

request.write(data);

request.end();

What you send in the Cookie value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

i had the same issue. go to Sql Server Configuration management->SQL Server network config->protocols for 'servername' and check named pipes is enabled.

Handling errors in Promise.all

if you get to use the q library https://github.com/kriskowal/q it has q.allSettled() method that can solve this problem you can handle every promise depending on its state either fullfiled or rejected so

existingPromiseChain = existingPromiseChain.then(function() {
var arrayOfPromises = state.routes.map(function(route){
  return route.handler.promiseHandler();
});
return q.allSettled(arrayOfPromises)
});

existingPromiseChain = existingPromiseChain.then(function(arrayResolved) {
//so here you have all your promises the fulfilled and the rejected ones
// you can check the state of each promise
arrayResolved.forEach(function(item){
   if(item.state === 'fulfilled'){ // 'rejected' for rejected promises
     //do somthing
   } else {
     // do something else
   }
})
// do stuff with my array of resolved promises, eventually ending with a res.send();
});

Match whitespace but not newlines

What you are looking for is the POSIX blank character class. In Perl it is referenced as:

[[:blank:]]

in Java (don't forget to enable UNICODE_CHARACTER_CLASS):

\p{Blank}

Compared to the similar \h, POSIX blank is supported by a few more regex engines (reference). A major benefit is that its definition is fixed in Annex C: Compatibility Properties of Unicode Regular Expressions and standard across all regex flavors that support Unicode. (In Perl, for example, \h chooses to additionally include the MONGOLIAN VOWEL SEPARATOR.) However, an argument in favor of \h is that it always detects Unicode characters (even if the engines don't agree on which), while POSIX character classes are often by default ASCII-only (as in Java).

But the problem is that even sticking to Unicode doesn't solve the issue 100%. Consider the following characters which are not considered whitespace in Unicode:

The aforementioned Mongolian vowel separator isn't included for what is probably a good reason. It, along with 200C and 200D, occur within words (AFAIK), and therefore breaks the cardinal rule that all other whitespace obeys: you can tokenize with it. They're more like modifiers. However, ZERO WIDTH SPACE, WORD JOINER, and ZERO WIDTH NON-BREAKING SPACE (if it used as other than a byte-order mark) fit the whitespace rule in my book. Therefore, I include them in my horizontal whitespace character class.

In Java:

static public final String HORIZONTAL_WHITESPACE = "[\\p{Blank}\\u200B\\u2060\\uFFEF]"

Converting from longitude\latitude to Cartesian coordinates

You can do it this way on Java.

public List<Double> convertGpsToECEF(double lat, double longi, float alt) {

    double a=6378.1;
    double b=6356.8;
    double N;
    double e= 1-(Math.pow(b, 2)/Math.pow(a, 2));
    N= a/(Math.sqrt(1.0-(e*Math.pow(Math.sin(Math.toRadians(lat)), 2))));
    double cosLatRad=Math.cos(Math.toRadians(lat));
    double cosLongiRad=Math.cos(Math.toRadians(longi));
    double sinLatRad=Math.sin(Math.toRadians(lat));
    double sinLongiRad=Math.sin(Math.toRadians(longi));
    double x =(N+0.001*alt)*cosLatRad*cosLongiRad;
    double y =(N+0.001*alt)*cosLatRad*sinLongiRad;
    double z =((Math.pow(b, 2)/Math.pow(a, 2))*N+0.001*alt)*sinLatRad;

    List<Double> ecef= new ArrayList<>();
    ecef.add(x);
    ecef.add(y);
    ecef.add(z);

    return ecef;


}

AndroidStudio gradle proxy

For Android Studio 1.4, I had to do the following ...

In the project explorer window, open the "Gradle Scripts" folder.

Edit the gradle.properties file.

Append the following to the bottom, replacing the below values with your own where appropriate ...

systemProp.http.proxyHost=?.?.?.?
systemProp.http.proxyPort=8080
# Next line in form DOMAIN/USERNAME for NTLM or just USERNAME for non-NTLM
systemProp.http.proxyUser=DOMAIN/USERNAME
systemProp.http.proxyPassword=PASSWORD
systemProp.http.nonProxyHosts=localhost
# Next line is required for NTLM auth only
systemProp.http.auth.ntlm.domain=DOMAIN

systemProp.https.proxyHost=?.?.?.?
systemProp.https.proxyPort=8080
# Next line in form DOMAIN/USERNAME for NTLM or just USERNAME for non-NTLM
systemProp.https.proxyUser=DOMAIN/USERNAME
systemProp.https.proxyPassword=PASSWORD
systemProp.https.nonProxyHosts=localhost
# Next line is required for NTLM auth only
systemProp.https.auth.ntlm.domain=DOMAIN

Details of what gradle properties you can set are here... https://docs.gradle.org/current/userguide/userguide_single.html#sec%3aaccessing_the_web_via_a_proxy

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

Screenshot sizes for publishing android app on Google Play

It has to be any one of the given sizes and a minimum of 2 but up to 8 screenshots are accepted in Google Playstore.

How to get share counts using graph API

You can use the https://graph.facebook.com/v3.0/{Place_your_Page_ID here}/feed?fields=id,shares,share_count&access_token={Place_your_access_token_here} to get the shares count.

Determine what attributes were changed in Rails after_save callback?

In case you can do this on before_save instead of after_save, you'll be able to use this:

self.changed

it returns an array of all changed columns in this record.

you can also use:

self.changes

which returns a hash of columns that changed and before and after results as arrays

How Do I Make Glyphicons Bigger? (Change Size?)

Increase the font-size of glyphicon to increase all icons size.

.glyphicon {
    font-size: 50px;
}

To target only one icon,

.glyphicon.glyphicon-globe {
    font-size: 75px;
}

How to properly make a http web GET request

Simpliest way for my opinion

  var web = new WebClient();
  var url = $"{hostname}/LoadDataSync?systemID={systemId}";
  var responseString = web.DownloadString(url);

OR

 var bytes = web.DownloadData(url);

List submodules in a Git repository

I use this one:

git submodule status | cut -d' ' -f3-4 

Output (path + version):

tools/deploy_utils (0.2.4)

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

First of all you need to download the file from here https://gradle.org/releases

unzip the file and copy folder something like this gradle-3.3(if version is 3.3) and past it to C:\Android\Android Studio\gradle

Now open the Android Studio and from the left top corner Open File > Settings > Build,Execution,Deployment > Gradle

Now give the the path of folder gradle-3.3 in Gradle Home

How to use PHP OPCache?

I am going to drop in my two cents for what I use opcache.

I have made an extensive framework with a lot of fields and validation methods and enums to be able to talk to my database.

Without opcache

When using this script without opcache and I push 9000 requests in 2.8 seconds to the apache server it maxes out at 90-100% cpu for 70-80 seconds until it catches up with all the requests.

Total time taken: 76085 milliseconds(76 seconds)

With opcache enabled

With opcache enabled it runs at 25-30% cpu time for about 25 seconds and never passes 25% cpu use.

Total time taken: 26490 milliseconds(26 seconds)

I have made an opcache blacklist file to disable the caching of everything except the framework which is all static and doesnt need changing of functionality. I choose explicitly for just the framework files so that I could develop without worrying about reloading/validating the cache files. Having everything cached saves a second on the total of the requests 25546 milliseconds

This significantly expands the amount of data/requests I can handle per second without the server even breaking a sweat.

How to set TextView textStyle such as bold, italic

Try this:

TextView textview = (TextView)findViewById(R.id.textview_idname);
textview.setTypeface(null,Typeface.BOLD);