Programs & Examples On #Scripting bridge

Scripting Bridge is a Cocoa framework that enables developers to communicate with scriptable applications in Objective-C.

Order columns through Bootstrap4

even this will work:

<div class="container">
            <div class="row">
                <div class="col-4 col-sm-4 col-md-6 order-1">
                    1
                </div>
                <div class="col-4 col-sm-4  col-md-6 order-3">
                    2
                </div>
                <div class="col-4 col-sm-4  col-md-12 order-2">
                    3
                </div>
            </div>
          </div>

Load CSV data into MySQL in Python

I think you have to do mydb.commit() all the insert into.

Something like this

import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='',
    db='mydb')
cursor = mydb.cursor()

csv_data = csv.reader(file('students.csv'))
for row in csv_data:

    cursor.execute('INSERT INTO testcsv(names, \
          classes, mark )' \
          'VALUES("%s", "%s", "%s")', 
          row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"

Animate text change in UILabel

UILabel Extension Solution

extension UILabel{

  func animation(typing value:String,duration: Double){
    let characters = value.map { $0 }
    var index = 0
    Timer.scheduledTimer(withTimeInterval: duration, repeats: true, block: { [weak self] timer in
        if index < value.count {
            let char = characters[index]
            self?.text! += "\(char)"
            index += 1
        } else {
            timer.invalidate()
        }
    })
  }


  func textWithAnimation(text:String,duration:CFTimeInterval){
    fadeTransition(duration)
    self.text = text
  }

  //followed from @Chris and @winnie-ru
  func fadeTransition(_ duration:CFTimeInterval) {
    let animation = CATransition()
    animation.timingFunction = CAMediaTimingFunction(name:
        CAMediaTimingFunctionName.easeInEaseOut)
    animation.type = CATransitionType.fade
    animation.duration = duration
    layer.add(animation, forKey: CATransitionType.fade.rawValue)
  }

}

Simply Called function by

uiLabel.textWithAnimation(text: "text you want to replace", duration: 0.2)

Thanks for all the tips guys. Hope this will help in long term

Pseudo-terminal will not be allocated because stdin is not a terminal

Also with option -T from manual

Disable pseudo-tty allocation

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.

Syntax:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

Fitting a density curve to a histogram in R

If I understand your question correctly, then you probably want a density estimate along with the histogram:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE)            # prob=TRUE for probabilities not counts
lines(density(X))             # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted")   # add another "smoother" density

Edit a long while later:

Here is a slightly more dressed-up version:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2) 

along with the graph it produces:

enter image description here

PHP to write Tab Characters inside a file?

This should do:

$chunk = "abc\tdef\tghi";

Here is a link to an article with more extensive examples.

Error "library not found for" after putting application in AdMob

  1. Cleaned Build Folder
  2. Restarted XCode

Went away...

SQLAlchemy: print the actual query

We can use compile method for this purpose. From the docs:

from sqlalchemy.sql import text
from sqlalchemy.dialects import postgresql

stmt = text("SELECT * FROM users WHERE users.name BETWEEN :x AND :y")
stmt = stmt.bindparams(x="m", y="z")

print(stmt.compile(dialect=postgresql.dialect(),compile_kwargs={"literal_binds": True}))

Result:

SELECT * FROM users WHERE users.name BETWEEN 'm' AND 'z'

Warning from docs:

Never use this technique with string content received from untrusted input, such as from web forms or other user-input applications. SQLAlchemy’s facilities to coerce Python values into direct SQL string values are not secure against untrusted input and do not validate the type of data being passed. Always use bound parameters when programmatically invoking non-DDL SQL statements against a relational database.

Ruby: kind_of? vs. instance_of? vs. is_a?

It is more Ruby-like to ask objects whether they respond to a method you need or not, using respond_to?. This allows both minimal interface and implementation unaware programming.

It is not always applicable of course, thus there is still a possibility to ask about more conservative understanding of "type", which is class or a base class, using the methods you're asking about.

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

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Retrofit 2 - Dynamic URL

You can use this :

@GET("group/{id}/users")

Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

For more information see documentation https://square.github.io/retrofit/

When do I use super()?

When you want the super class constructor to be called - to initialize the fields within it. Take a look at this article for an understanding of when to use it:

http://download.oracle.com/javase/tutorial/java/IandI/super.html

How to declare a constant map in Golang?

And as suggested above by Siu Ching Pong -Asuka Kenji with the function which in my opinion makes more sense and leaves you with the convenience of the map type without the function wrapper around:

   // romanNumeralDict returns map[int]string dictionary, since the return
       // value is always the same it gives the pseudo-constant output, which
       // can be referred to in the same map-alike fashion.
       var romanNumeralDict = func() map[int]string { return map[int]string {
            1000: "M",
            900:  "CM",
            500:  "D",
            400:  "CD",
            100:  "C",
            90:   "XC",
            50:   "L",
            40:   "XL",
            10:   "X",
            9:    "IX",
            5:    "V",
            4:    "IV",
            1:    "I",
          }
        }

        func printRoman(key int) {
          fmt.Println(romanNumeralDict()[key])
        }

        func printKeyN(key, n int) {
          fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
        }

        func main() {
          printRoman(1000)
          printRoman(50)
          printKeyN(10, 3)
        }

Try this at play.golang.org.

How to do a join in linq to sql with method syntax?

To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:

public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
    using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
    {
        var result = entityFrameworkObjectContext.SomeClass
            .Join(entityFrameworkObjectContext.SomeOtherClass,
                sc => sc.property1,
                soc => soc.property2,
                (sc, soc) => new {sc, soc})
            .Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
            .Select(s => new ThirdNonEntityClass 
            {
                dataValue1 = s.sc.dataValueA,
                dataValue2 = s.soc.dataValueB
            })
            .ToList();
    }

    return result;

}    

Pay special attention to the intermediate object that is created in the Where and Select clauses.

Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.

I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.

Switch statement equivalent in Windows batch file

This is simpler to read:

IF "%ID%"=="0" REM do something
IF "%ID%"=="1" REM do something else
IF "%ID%"=="2" REM do another thing
IF %ID% GTR 2  REM default case...

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

ORDER BY using Criteria API

You need to create an alias for the mother.kind. You do this like so.

Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();

What is a thread exit code?

As Sayse mentioned, exit code 259 (0x103) has special meaning, in this case the process being debugged is still running.

I saw this a lot with debugging web services, because the thread continues to run after executing each web service call (as it is still listening for further calls).

Browse for a directory in C#

You could just use the FolderBrowserDialog class from the System.Windows.Forms namespace.

concatenate two strings

You can use concatenation operator and instead of declaring two variables only use one variable

String finalString =  cursor.getString(numcol) + cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));

jQuery click event not working in mobile browsers

Vohuman's answer lead me to my own implementation:

$(document).on("vclick", ".className", function() {
  // Whatever you want to do
});

Instead of:

$(document).ready(function($) {
  $('.className').click(function(){
    // Whatever you want to do
  });
});

I hope this helps!

How do I get the current mouse screen coordinates in WPF?

You may use combination of TimerDispatcher (WPF Timer analog) and Windows "Hooks" to catch cursor position from operational system.

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetCursorPos(out POINT pPoint);

Point is a light struct. It contains only X, Y fields.

    public MainWindow()
    {
        InitializeComponent();

        DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
        dt.Tick += new EventHandler(timer_tick);
        dt.Interval = new TimeSpan(0,0,0,0, 50);
        dt.Start();
    }

    private void timer_tick(object sender, EventArgs e)
    {
        POINT pnt;
        GetCursorPos(out pnt);
        current_x_box.Text = (pnt.X).ToString();
        current_y_box.Text = (pnt.Y).ToString();
    }

    public struct POINT
    {
        public int X;
        public int Y;

        public POINT(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }

This solution is also resolving the problem with too often or too infrequent parameter reading so you can adjust it by yourself. But remember about WPF method overload with one arg which is representing ticks not milliseconds.

TimeSpan(50); //ticks

How to commit to remote git repository

Have you tried git push? gitref.org has a nice section dealing with remote repositories.

You can also get help from the command line using the --help option. For example:

% git push --help
GIT-PUSH(1)                             Git Manual                             GIT-PUSH(1)



NAME
       git-push - Update remote refs along with associated objects

SYNOPSIS
       git push [--all | --mirror | --tags] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
                  [--repo=<repository>] [-f | --force] [-v | --verbose] [-u | --set-upstream]
                  [<repository> [<refspec>...]]
...

Can I change the checkbox size using CSS?

I just came out with this:

_x000D_
_x000D_
input[type="checkbox"] {display:none;}_x000D_
input[type="checkbox"] + label:before {content:"?";}_x000D_
input:checked + label:before {content:"?";}_x000D_
label:hover {color:blue;}
_x000D_
<input id="check" type="checkbox" /><label for="check">Checkbox</label>
_x000D_
_x000D_
_x000D_

Of course, thanks to this, you can change the value of content to your needs and use an image if you wish or use another font...

The main interest here is that:

  1. The checkbox size stays proportional to the text size

  2. You can control the aspect, the color, the size of the checkbox

  3. No extra HTML needed !

  4. Only 3 lines of CSS needed (the last one is just to give you ideas)

Edit: As pointed out in the comment, the checkbox won't be accessible by key navigation. You should probably add tabindex=0 as a property for your label to make it focusable.

UIAlertController custom font, size, color

I work for Urban Outfitters. We have an open source pod, URBNAlert, that we used in all of our apps. It's based off of UIAlertController, but is highly customizable.

Source is here: https://github.com/urbn/URBNAlert

Or simply install by the pod by placing URBNAlert in your Podfile

Heres some sample code:

URBNAlertViewController *uac = [[URBNAlertViewController alloc] initWithTitle:@"The Title of my message can be up to 2 lines long. It wraps and centers." message:@"And the message that is a bunch of text. And the message that is a bunch of text. And the message that is a bunch of text."];

// You can customize style elements per alert as well. These will override the global style just for this alert.
uac.alertStyler.blurTintColor = [[UIColor orangeColor] colorWithAlphaComponent:0.4];
uac.alertStyler.backgroundColor = [UIColor orangeColor];
uac.alertStyler.textFieldEdgeInsets = UIEdgeInsetsMake(0.0, 15.0, 0.0, 15.0);
uac.alertStyler.titleColor = [UIColor purpleColor];
uac.alertStyler.titleFont = [UIFont fontWithName:@"Chalkduster" size:30];
uac.alertStyler.messageColor = [UIColor blackColor];
uac.alertStyler.alertMinWidth = @150;
uac.alertStyler.alertMaxWidth = @200;
// many more styling options available 

[uac addAction:[URBNAlertAction actionWithTitle:@"Ok" actionType:URBNAlertActionTypeNormal actionCompleted:^(URBNAlertAction *action) {
      // Do something
}]];

[uac addAction:[URBNAlertAction actionWithTitle:@"Cancel" actionType:URBNAlertActionTypeCancel actionCompleted:^(URBNAlertAction *action) {
      // Do something
}]];

[uac show];

Oracle: not a valid month

You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;

05/12/2015

how much memory can be accessed by a 32 bit machine?

Yes, on a 32bit machine the maximum amount of memory usable is around 4GB. Actually, depending on the OS it might be less due to parts of the address space being reserved: On Windows you can only use 3.5GB for example.

On 64bit you can indeed address 2^64 bytes of memory. Not that you'll ever have those - but then again, a long time ago the same thing was said about ever needing more than 640kb of memory...

Display TIFF image in all web browser

Tiff images can be displayed directly onto IE and safari only.. no support of tiff images on chrome and firefox. you can encode the image and then display it on browser by decoding the encoded image to some other format. Hope this works for you

iOS: How to store username/password within an app?

If you need an ARC version of the wrapper here is the link https://gist.github.com/1170641 Thanks to

Javascript decoding html entities

Using jQuery the easiest will be:

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';

var output = $("<div />").html(text).text();
console.log(output);

DEMO: http://jsfiddle.net/LKGZx/

fcntl substitute on Windows

Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker

It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.

The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

You can use RTRIM or cast your value to VARCHAR:

SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)

Or

SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

According to Google Developers article, you can:

How to execute INSERT statement using JdbcTemplate class from Spring Framework

Use jdbcTemplate.update(String sql, Object... args) method:

jdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
    var1, var2
);

or jdbcTemplate.update(String sql, Object[] args, int[] argTypes), if you need to map arguments to SQL types manually:

jdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
    new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2}
);

How can I check if the current date/time is past a set date/time?

Check PHP's strtotime-function to convert your set date/time to a timestamp: http://php.net/manual/en/function.strtotime.php

If strtotime can't handle your date/time format correctly ("4:00PM" will probably work but not "at 4PM"), you'll need to use string-functions, e.g. substr to parse/correct your format and retrieve your timestamp through another function, e.g. mktime.

Then compare the resulting timestamp with the current date/time (if ($calulated_timestamp > time()) { /* date in the future */ }) to see whether the set date/time is in the past or the future.

I suggest to read the PHP-doc on date/time-functions and get back here with some of your source-code once you get stuck.

jQuery UI Slider (setting programmatically)

It depends on if you want to change the sliders in the current range or change the range of the sliders.

If it is the values in the current range you want to change, then the .slider() method is the one you should use, but the syntax is a bit different than you used:

$("#slider").slider('value',50);

or if you have a slider with two handles it would be:

$("#slider").slider('values',0,50); // sets first handle (index 0) to 50
$("#slider").slider('values',1,80); // sets second handle (index 1) to 80

If it is the range you want to change it would be:

$("#slider").slider('option',{min: 0, max: 500});

How to listen to the window scroll event in a VueJS component?

I've been in the need for this feature many times, therefore I've extracted it into a mixin. It can be used like this:

import windowScrollPosition from 'path/to/mixin.js'

new Vue({
  mixins: [ windowScrollPosition('position') ]
})

This creates a reactive position property (can be named whatever we like) on the Vue instance. The property contains the window scroll position as an [x,y] array.

Feel free to play around with this CodeSandbox demo.

Here's the code of the mixin. It's thoroughly commentated, so it should not be too hard to get an idea how it works:

function windowScrollPosition(propertyName) {
  return {
    data() {
      return {
        // Initialize scroll position at [0, 0]
        [propertyName]: [0, 0]
      }
    },
    created() {
      // Only execute this code on the client side, server sticks to [0, 0]
      if (!this.$isServer) {
        this._scrollListener = () => {
          // window.pageX/YOffset is equivalent to window.scrollX/Y, but works in IE
          // We round values because high-DPI devies can provide some really nasty subpixel values
          this[propertyName] = [
            Math.round(window.pageXOffset),
            Math.round(window.pageYOffset)
          ]
        }

        // Call listener once to detect initial position
        this._scrollListener()

        // When scrolling, update the position
        window.addEventListener('scroll', this._scrollListener)
      }
    },
    beforeDestroy() {
      // Detach the listener when the component is gone
      window.removeEventListener('scroll', this._scrollListener)
    }
  }
}

How to find when a web page was last updated

For checking the Last Modified header, you can use httpie (docs).

Installation

pip install httpie --user

Usage

$ http -h https://martin-thoma.com/author/martin-thoma/ | grep 'Last-Modified\|Date'
Date: Fri, 06 Jan 2017 10:06:43 GMT
Last-Modified: Fri, 06 Jan 2017 07:42:34 GMT

The Date is important as this reports the server time, not your local time. Also, not every server sends Last-Modified (e.g. superuser seems not to do it).

Responsive Images with CSS

.erb-image-wrapper img{
    max-width:100% !important;
    height:auto;
    display:block;
}

Worked for me.
Thanks for MrMisterMan for his assistance.

$ is not a function - jQuery error

It's really hard to tell, but one of the 9001 ads on the page may be clobbering the $ object.

jQuery provides the global jQuery object (which is present on your page). You can do the following to "get" $ back:

jQuery(document).ready(function ($) {
    // Your code here
});

If you think you're having jQuery problems, please use the debug (non-production) versions of the library.

Also, it's probably not best to be editing a live site like that ...

In Javascript, how to conditionally add a member to an object?

In pure Javascript, I cannot think of anything more idiomatic than your first code snippet.

If, however, using the jQuery library is not out of the question, then $.extend() should meet your requirements because, as the documentation says:

Undefined properties are not copied.

Therefore, you can write:

var a = $.extend({}, {
    b: conditionB ? 5 : undefined,
    c: conditionC ? 5 : undefined,
    // and so on...
});

And obtain the results you expect (if conditionB is false, then b will not exist in a).

User Control - Custom Properties

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Raise an error manually in T-SQL to jump to BEGIN CATCH block

You're looking for RAISERROR.

From MSDN:

Generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct.

CodeProject has a good article that also describes in-depth the details of how it works and how to use it.

Where is the WPF Numeric UpDown control?

Simply use the IntegerUpDown control in the Extended.Wpf.Toolkit You can use it like this:

  1. Add to your XAML the following namespace:

    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"

  2. In your XAML where you want the control use:

    <xctk:IntegerUpDown Name="myUpDownControl" />

C# : changing listbox row color?

First use this Namespace:

using System.Drawing;

Add this anywhere on your form:

listBox.DrawMode = DrawMode.OwnerDrawFixed;
listBox.DrawItem += listBox_DrawItem;

Here is the Event Handler:

private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
     e.DrawBackground();

     Graphics g = e.Graphics;
     g.FillRectangle(new SolidBrush(Color.White), e.Bounds);
     ListBox lb = (ListBox)sender;
     g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), new PointF(e.Bounds.X, e.Bounds.Y));

     e.DrawFocusRectangle();
}

Using :: in C++

One use for the 'Unary Scope Resolution Operator' or 'Colon Colon Operator' is for local and global variable selection of identical names:

    #include <iostream>
    using namespace std;
    
    int variable = 20;
    
    int main()
    {
    float variable = 30;
    
    cout << "This is local to the main function: " << variable << endl;
    cout << "This is global to the main function: " << ::variable << endl;
    
    return 0;
    }

The resulting output would be:

This is local to the main function: 30

This is global to the main function: 20

Other uses could be: Defining a function from outside of a class, to access a static variable within a class or to use multiple inheritance.

Android soft keyboard covers EditText field

I had the same issue where the softkeyboard was on top of the EditText views which were placed on the bottom of the screen. I was able to find a solution by adding a single line to my AndroidManifest.xml file's relevant activity.

android:windowSoftInputMode="adjustResize|stateHidden"

This is how the whole activity tag looks like:

<activity
        android:name="com.my.MainActivity"
        android:screenOrientation="portrait"
        android:label="@string/title_activity_main"
        android:windowSoftInputMode="adjustResize|stateHidden" >
    </activity>

Here the most important value is the adjustResize. This will shift the whole UI up to give room for the softkeyboard.

How to subtract 2 hours from user's local time?

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);

NodeJS - What does "socket hang up" actually mean?

I think "socket hang up" is a fairly general error indicating that the connection has been terminated from the server end. In other words, the sockets being used to maintain the connection between the client and the server have been disconnected. (While I'm sure many of the points mentioned above are helpful to various people, I think this is the more general answer.)

In my case, I was sending a request with a payload in excess of 20K. This was rejected by the server. I verified this by removing text and retrying until the request succeeded. After determining the maximum acceptable length, I verified that adding a single character caused the error to manifest. I also confirmed that the client wasn't the issue by sending the same request from a Python app and from Postman. So anyway, I'm confident that, in my case, the length of the payload was my specific problem.

Once again, the source of the problem is anecdotal. The general problem is "Server Says No".

Open firewall port on CentOS 7

If you have multiple ports to allow in Centos 7 FIrewalld then we can use the following command.

#firewall-cmd --add-port={port number/tcp,port number/tcp} --permanent

#firewall-cmd --reload


And check the Port opened or not after reloading the firewall.


#firewall-cmd --list-port


For other configuration [Linuxwindo.com][1]

Understanding inplace=True

inplace=True is used depending if you want to make changes to the original df or not.

df.drop_duplicates()

will only make a view of dropped values but not make any changes to df

df.drop_duplicates(inplace  = True)

will drop values and make changes to df.

Hope this helps.:)

How to make an empty div take space

If they need to be floated, you could always just set the min-height to 1px so they don't collapse.

failed to load ad : 3

I hadn't published a version of my app with ads yet.

I was seeing error code 3: ERROR_CODE_NO_FILL after I switched from emulators with a debug version to a real device with the release version (installed through adb shell commands).

I waited 12+ hours and I could see ad requests on the AdMob portal, but no matches (match rate of 0%). I went to the Play Console > Store Presence > Pricing & distribution and switched the radio button for Contains ads to Yes, it has ads. I even tried uploading my app bundle (without publishing) to the Play Console. Neither of these worked.

Various AdMob help articles (including the one linked below) mention that if you've been seeing test ads (ads labeled with "Test Ad"), then your code is working and real ads should work as expected (once they build up inventory).

With that in mind, I went ahead and published my app to the Play Store and once the update was live, I downloaded it via the Play Store app on my real phone and the ads loaded no problem and my match rate is now sitting at 66% on AdMob. From the AdMob FAQ article, it sounds like it typically takes a few hours and could have taken up to 24 hours for ads to start showing.

ad mob FAQ re: how long does it take ads to show

Source: https://support.google.com/admob/answer/2993019?hl=en

Why don’t my SVG images scale using the CSS "width" property?

  1. If the svg file has a height and width already defined width="100" height="100" in the svg file then add this x="0px" y="0px" width="100" height="100" viewBox="0 0 100 100" while keeping the already defined width="100" height="100".
  2. Then you can scale the svg in your css file by using a selector in your case img so you could then do this: img{height: 20px; width: 20px;} and the image will scale.

import error: 'No module named' *does* exist

I had the same issue. I solved it by running the command in a different python version. I tried python3 filename.py. Earlier i was using Python 2.7.

Another possibility is that the file from which something is imported may contain BOM (Byte Order Mark). It can be solved by opening the file in some editor which supports multiple encoding like VSCode (Notepad++) and saving in a different encoding statndard like ANSI, UTF-8(without BOM).

How do I name the "row names" column in r

The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

How can I detect keydown or keypress event in angular.js?

You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress (also Enter key, backspace key, alter key ,control key)

<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>

PHP and MySQL Select a Single Value

When you use mysql_fetch_object, you get an object (of class stdClass) with all fields for the row inside of it.

Use mysql_fetch_field instead of mysql_fetch_object, that will give you the first field of the result set (id in your case). The docs are here

How to "log in" to a website using Python's Requests module?

Some pages may require more than login/pass. There may even be hidden fields. The most reliable way is to use inspect tool and look at the network tab while logging in, to see what data is being passed on.

Shortcut to open file in Vim

I like the :FuzzyFinderTextMate (or Ctrl + F) on my setup. See http://weblog.jamisbuck.org/2008/10/10/coming-home-to-vim

How can I check if a directory exists?

Use the following code to check if a folder exists. It works on both Windows & Linux platforms.

#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char* argv[])
{
    const char* folder;
    //folder = "C:\\Users\\SaMaN\\Desktop\\Ppln";
    folder = "/tmp";
    struct stat sb;

    if (stat(folder, &sb) == 0 && S_ISDIR(sb.st_mode)) {
        printf("YES\n");
    } else {
        printf("NO\n");
    }
}

What is a C++ delegate?

You have an incredible number of choices to achieve delegates in C++. Here are the ones that came to my mind.


Option 1 : functors:

A function object may be created by implementing operator()

struct Functor
{
     // Normal class/struct members

     int operator()(double d) // Arbitrary return types and parameter list
     {
          return (int) d + 1;
     }
};

// Use:
Functor f;
int i = f(3.14);

Option 2: lambda expressions (C++11 only)

// Syntax is roughly: [capture](parameter list) -> return type {block}
// Some shortcuts exist
auto func = [](int i) -> double { return 2*i/1.15; };
double d = func(1);

Option 3: function pointers

int f(double d) { ... }
typedef int (*MyFuncT) (double d);
MyFuncT fp = &f;
int a = fp(3.14);

Option 4: pointer to member functions (fastest solution)

See Fast C++ Delegate (on The Code Project).

struct DelegateList
{
     int f1(double d) { }
     int f2(double d) { }
};

typedef int (DelegateList::* DelegateType)(double d);

DelegateType d = &DelegateList::f1;
DelegateList list;
int a = (list.*d)(3.14);

Option 5: std::function

(or boost::function if your standard library doesn't support it). It is slower, but it is the most flexible.

#include <functional>
std::function<int(double)> f = [can be set to about anything in this answer]
// Usually more useful as a parameter to another functions

Option 6: binding (using std::bind)

Allows setting some parameters in advance, convenient to call a member function for instance.

struct MyClass
{
    int DoStuff(double d); // actually a DoStuff(MyClass* this, double d)
};

std::function<int(double d)> f = std::bind(&MyClass::DoStuff, this, std::placeholders::_1);
// auto f = std::bind(...); in C++11

Option 7: templates

Accept anything as long as it matches the argument list.

template <class FunctionT>
int DoSomething(FunctionT func)
{
    return func(3.14);
}

How do I vertically align text in a paragraph?

If you use Bootstrap, try to assign margin-bottom 0 to the paragraph and after assign the property align-items-center to container, for example, like this:

<div class="row align-items-center">
     <p class="col-sm-1 mb-0">
          ....
     </p>
</div>

Bootstrap by default assign a calculate margin bottom, so mb-0 disabled this.

I hope it helps

Git diff says subproject is dirty

This is the case because the pointer you have for the submodule isn’t what is actually in the submodule directory. To fix this, you must run git submodule update again:

Can you change a path without reloading the controller in AngularJS?

If you need to change the path, add this after your .config in your app file. Then you can do $location.path('/sampleurl', false); to prevent reloading

app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location) {
    var original = $location.path;
    $location.path = function (path, reload) {
        if (reload === false) {
            var lastRoute = $route.current;
            var un = $rootScope.$on('$locationChangeSuccess', function () {
                $route.current = lastRoute;
                un();
            });
        }
        return original.apply($location, [path]);
    };
}])

Credit goes to https://www.consolelog.io/angularjs-change-path-without-reloading for the most elegant solution I've found.

What is the best way to conditionally apply attributes in AngularJS?

You can prefix attributes with ng-attr to eval an Angular expression. When the result of the expressions undefined this removes the value from the attribute.

<a ng-attr-href="{{value || undefined}}">Hello World</a>

Will produce (when value is false)

<a ng-attr-href="{{value || undefined}}" href>Hello World</a>

So don't use false because that will produce the word "false" as the value.

<a ng-attr-href="{{value || false}}" href="false">Hello World</a>

When using this trick in a directive. The attributes for the directive will be false if they are missing a value.

For example, the above would be false.

function post($scope, $el, $attr) {
      var url = $attr['href'] || false;
      alert(url === false);
}

What is the difference between a URI, a URL and a URN?

In order to answer this I'll lean on an answer I modified to another question. A good example of a URI is how you identify an Amazon S3 resource. Let's take:

s3://www-example-com/index.html [fig. 1]

which I created as a cached copy of

http://www.example.com/index.html [fig. 2]

in Amazon's S3-US-West-2 datacenter.

Even if StackOverflow would allow me to hyperlink to the s3:// protocol scheme, it wouldn't do you any good in locating the resource. Because it Identifies a Resource, fig. 1 is a valid URI. It is also a valid URN, because Amazon requires that the bucket (their term for the authority portion of the URI) be unique across datacenters. It is helpful in locating it, but it does not indicate the datacenter. Therefore it does not work as a URL.

So, how do URI, URL, and URN differ in this case?

NOTE: RFC 3986 defines URIs as scheme://authority/path?query#fragment

How to call on a function found on another file?

Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.

Perhaps declare it above your first while?

Disable a Maven plugin defined in a parent POM

I know this thread is really old but the solution from @Ivan Bondarenko helped me in my situation.

I had the following in my pom.xml.

<build>
    ...
    <plugins>
         <plugin>
                <groupId>com.consol.citrus</groupId>
                <artifactId>citrus-remote-maven-plugin</artifactId>
                <version>${citrus.version}</version>
                <executions>
                    <execution>
                        <id>generate-citrus-war</id>
                        <goals>
                            <goal>test-war</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    </plugins>
</build>

What I wanted, was to disable the execution of generate-citrus-war for a specific profile and this was the solution:

<profile>
    <id>it</id>
    <build>
        <plugins>
            <plugin>
                <groupId>com.consol.citrus</groupId>
                <artifactId>citrus-remote-maven-plugin</artifactId>
                <version>${citrus.version}</version>
                <executions>
                    <!-- disable generating the war for this profile -->
                    <execution>
                        <id>generate-citrus-war</id>
                        <phase/>
                    </execution>

                    <!-- do something else -->
                    <execution>
                        ...
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</profile>

Open Popup window using javascript

To create a popup you'll need the following script:

<script language="javascript" type="text/javascript">

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


</script>

Then, you link to it by:

  <a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>

If you want you can call the function directly from document.ready also. Or maybe from another function.

Get a Div Value in JQuery

myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
   alert ( myDivObj.innerHTML ); 
}else{
   alert ( "Alien Found" );
}

Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]

function showDivText(){
            divObj = document.getElementById("myDiv");
            if ( divObj ){
                if ( divObj.textContent ){ // FF
                    alert ( divObj.textContent );
                }else{  // IE           
                    alert ( divObj.innerText );  //alert ( divObj.innerHTML );
                } 
            }  
        }

M_PI works with math.h but not with cmath in Visual Studio

As suggested by user7860670, right-click on the project, select properties, navigate to C/C++ -> Preprocessor and add _USE_MATH_DEFINES to the Preprocessor Definitions.

That's what worked for me.

How to use Bootstrap in an Angular project?

An integration with Angular2 is also available through the ng2-bootstrap project : https://github.com/valor-software/ng2-bootstrap.

To install it simply put these files in your main HTML page:

<script src="https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/x.x.x/ng2-bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

Then you can use it into your components this way:

import {Component} from 'angular2/core';
import {Alert} from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  selector: 'my-app',
  directives: [Alert],
  template: `<alert type="info">ng2-bootstrap hello world!</alert>`
})
export class AppComponent {
}

In Angular, I need to search objects in an array

A dirty and easy solution could look like

$scope.showdetails = function(fish_id) {
    angular.forEach($scope.fish, function(fish, key) {
        fish.more = fish.id == fish_id;
    });
};

Ajax success event not working

I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified

dataType: "json"

once I did, unlike the "accepted answer", that actually fixed the problem.

Flatten an irregular list of lists

The think that following would probably work in python 3:

def get_flat_iter(xparent):
    try:
        r = xparent
        if hasattr(xx, '__iter__'):
            iparent = iter(xparent)
            if iparent != xparent:
                r = map(a, xparent)
    finally:
         pass
    return r

irregular_list = [1, [2, [3, 4]]]
flat_list = list(irregular_list)
print(flat_list) # [1, 2, 3, 4]

How to calculate percentage with a SQL statement

This is, I believe, a general solution, though I tested it using IBM Informix Dynamic Server 11.50.FC3. The following query:

SELECT grade,
       ROUND(100.0 * grade_sum / (SELECT COUNT(*) FROM grades), 2) AS pct_of_grades
    FROM (SELECT grade, COUNT(*) AS grade_sum
            FROM grades
            GROUP BY grade
         )
    ORDER BY grade;

gives the following output on the test data shown below the horizontal rule. The ROUND function may be DBMS-specific, but the rest (probably) is not. (Note that I changed 100 to 100.0 to ensure that the calculation occurs using non-integer - DECIMAL, NUMERIC - arithmetic; see the comments, and thanks to Thunder.)

grade  pct_of_grades
CHAR(1) DECIMAL(32,2)
A       32.26
B       16.13
C       12.90
D       12.90
E       9.68
F       16.13

CREATE TABLE grades
(
    id VARCHAR(10) NOT NULL,
    grade CHAR(1) NOT NULL CHECK (grade MATCHES '[ABCDEF]')
);

INSERT INTO grades VALUES('1001', 'A');
INSERT INTO grades VALUES('1002', 'B');
INSERT INTO grades VALUES('1003', 'F');
INSERT INTO grades VALUES('1004', 'C');
INSERT INTO grades VALUES('1005', 'D');
INSERT INTO grades VALUES('1006', 'A');
INSERT INTO grades VALUES('1007', 'F');
INSERT INTO grades VALUES('1008', 'C');
INSERT INTO grades VALUES('1009', 'A');
INSERT INTO grades VALUES('1010', 'E');
INSERT INTO grades VALUES('1001', 'A');
INSERT INTO grades VALUES('1012', 'F');
INSERT INTO grades VALUES('1013', 'D');
INSERT INTO grades VALUES('1014', 'B');
INSERT INTO grades VALUES('1015', 'E');
INSERT INTO grades VALUES('1016', 'A');
INSERT INTO grades VALUES('1017', 'F');
INSERT INTO grades VALUES('1018', 'B');
INSERT INTO grades VALUES('1019', 'C');
INSERT INTO grades VALUES('1020', 'A');
INSERT INTO grades VALUES('1021', 'A');
INSERT INTO grades VALUES('1022', 'E');
INSERT INTO grades VALUES('1023', 'D');
INSERT INTO grades VALUES('1024', 'B');
INSERT INTO grades VALUES('1025', 'A');
INSERT INTO grades VALUES('1026', 'A');
INSERT INTO grades VALUES('1027', 'D');
INSERT INTO grades VALUES('1028', 'B');
INSERT INTO grades VALUES('1029', 'A');
INSERT INTO grades VALUES('1030', 'C');
INSERT INTO grades VALUES('1031', 'F');

Non-Static method cannot be referenced from a static context with methods and variables

You need to make both your method - printMenu() and getUserChoice() static, as you are directly invoking them from your static main method, without creating an instance of the class, those methods are defined in. And you cannot invoke a non-static method without any reference to an instance of the class they are defined in.

Alternatively you can change the method invocation part to:

BookStoreApp2 bookStoreApp = new BookStoreApp2();
bookStoreApp.printMenu();
bookStoreApp.getUserChoice();

How do I open a new fragment from another fragment?

@Override
public void onListItemClick(ListView l, View v, int pos, long id) {
    super.onListItemClick(l, v, pos, id);
    UserResult nextFrag= new UserResult();
    this.getFragmentManager().beginTransaction()
    .replace(R.id.content_frame, nextFrag, null)
    .addToBackStack(null)
    .commit();  
}

What is difference between Lightsail and EC2?

Testing¹ reveals that Lightsail instances in fact are EC2 instances, from the t2 class of burstable instances.

EC2, of course, has many more instance families and classes other than the t2, almost all of which are more "powerful" (or better equipped for certain tasks) than these, but also much more expensive. But for meaningful comparisons, the 512 MiB Lightsail instance appears to be completely equivalent in specifications to the similarly-priced t2.nano, the 1GiB is a t2.micro, the 2 GiB is a t2.small, etc.

Lightsail is a lightweight, simplified product offering -- hard disks are fixed size EBS SSD volumes, instances are still billable when stopped, security group rules are much less flexible, and only a very limited subset of EC2 features and options are accessible.

It also has a dramatically simplified console, and even though the machines run in EC2, you can't see them in the EC2 section of the AWS console. The instances run in a special VPC, but this aspect is also provisioned automatically, and invisible in the console. Lightsail supports optionally peering this hidden VPC with your default VPC in the same AWS region, allowing Lightsail instances to access services like EC2 and RDS in the default VPC within the same AWS account.²

Bandwidth is unlimited, but of course free bandwidth is not -- however, Lightsail instances do include a significant monthly bandwidth allowance before any bandwidth-related charges apply.³ Lightsail also has a simplified interface to Route 53 with limited functionality.

But if those sound like drawbacks, they aren't. The point of Lightsail seems to be simplicity. The flexibility of EC2 (and much of AWS) leads inevitably to complexity. The target market for Lightsail appears to be those who "just want a simple VPS" without having to navigate the myriad options available in AWS services like EC2, EBS, VPC, and Route 53. There is virtually no learning curve, here. You don't even technically need to know how to use SSH with a private key -- the Lightsail console even has a built-in SSH client -- but there is no requirement that you use it. You can access these instances normally, with a standard SSH client.


¹Lightsail instances, just like "regular" EC2 (VPC and Classic) instances, have access to the instance metadata service, which allows an instance to discover things about itself, such as its instance type and availability zone. Lightsail instances are identified in the instance metadata as t2 machines.

²The Lightsail docs are not explicit about the fact that peering only works with your Default VPC, but this appears to be the case. If your AWS account was created in 2013 or before, then you may not actually have a VPC with the "Default VPC" designation. This can be resolved by submitting a support request, as I explained in Can't establish VPC peering connection from Amazon Lightsail (at Server Fault).

³The bandwidth allowance applies to both inbound and outbound traffic; after this total amount of traffic is exceeded, inbound traffic continues to be free, but outbound traffic becomes billable. See "What does data transfer cost?" in the Lightsail FAQ.

Switching between GCC and Clang/LLVM using CMake

CMake honors the environment variables CC and CXX upon detecting the C and C++ compiler to use:

$ export CC=/usr/bin/clang
$ export CXX=/usr/bin/clang++
$ cmake ..
-- The C compiler identification is Clang
-- The CXX compiler identification is Clang

The compiler specific flags can be overridden by putting them into a make override file and pointing the CMAKE_USER_MAKE_RULES_OVERRIDE variable to it. Create a file ~/ClangOverrides.txt with the following contents:

SET (CMAKE_C_FLAGS_INIT                "-Wall -std=c99")
SET (CMAKE_C_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_C_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_C_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

SET (CMAKE_CXX_FLAGS_INIT                "-Wall")
SET (CMAKE_CXX_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_CXX_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

The suffix _INIT will make CMake initialize the corresponding *_FLAGS variable with the given value. Then invoke cmake in the following way:

$ cmake -DCMAKE_USER_MAKE_RULES_OVERRIDE=~/ClangOverrides.txt ..

Finally to force the use of the LLVM binutils, set the internal variable _CMAKE_TOOLCHAIN_PREFIX. This variable is honored by the CMakeFindBinUtils module:

$ cmake -D_CMAKE_TOOLCHAIN_PREFIX=llvm- ..

Putting this all together you can write a shell wrapper which sets up the environment variables CC and CXX and then invokes cmake with the mentioned variable overrides.

Also see this CMake FAQ on make override files.

What is Dependency Injection?

What is Dependency Injection (DI)?

As others have said, Dependency Injection(DI) removes the responsibility of direct creation, and management of the lifespan, of other object instances upon which our class of interest (consumer class) is dependent (in the UML sense). These instances are instead passed to our consumer class, typically as constructor parameters or via property setters (the management of the dependency object instancing and passing to the consumer class is usually performed by an Inversion of Control (IoC) container, but that's another topic).

DI, DIP and SOLID

Specifically, in the paradigm of Robert C Martin's SOLID principles of Object Oriented Design, DI is one of the possible implementations of the Dependency Inversion Principle (DIP). The DIP is the D of the SOLID mantra - other DIP implementations include the Service Locator, and Plugin patterns.

The objective of the DIP is to decouple tight, concrete dependencies between classes, and instead, to loosen the coupling by means of an abstraction, which can be achieved via an interface, abstract class or pure virtual class, depending on the language and approach used.

Without the DIP, our code (I've called this 'consuming class') is directly coupled to a concrete dependency and is also often burdened with the responsibility of knowing how to obtain, and manage, an instance of this dependency, i.e. conceptually:

"I need to create/use a Foo and invoke method `GetBar()`"

Whereas after application of the DIP, the requirement is loosened, and the concern of obtaining and managing the lifespan of the Foo dependency has been removed:

"I need to invoke something which offers `GetBar()`"

Why use DIP (and DI)?

Decoupling dependencies between classes in this way allows for easy substitution of these dependency classes with other implementations which also fulfil the prerequisites of the abstraction (e.g. the dependency can be switched with another implementation of the same interface). Moreover, as others have mentioned, possibly the most common reason to decouple classes via the DIP is to allow a consuming class to be tested in isolation, as these same dependencies can now be stubbed and/or mocked.

One consequence of DI is that the lifespan management of dependency object instances is no longer controlled by a consuming class, as the dependency object is now passed into the consuming class (via constructor or setter injection).

This can be viewed in different ways:

  • If lifespan control of dependencies by the consuming class needs to be retained, control can be re-established by injecting an (abstract) factory for creating the dependency class instances, into the consumer class. The consumer will be able to obtain instances via a Create on the factory as needed, and dispose of these instances once complete.
  • Or, lifespan control of dependency instances can be relinquished to an IoC container (more about this below).

When to use DI?

  • Where there likely will be a need to substitute a dependency for an equivalent implementation,
  • Any time where you will need to unit test the methods of a class in isolation of its dependencies,
  • Where uncertainty of the lifespan of a dependency may warrant experimentation (e.g. Hey, MyDepClass is thread safe - what if we make it a singleton and inject the same instance into all consumers?)

Example

Here's a simple C# implementation. Given the below Consuming class:

public class MyLogger
{
   public void LogRecord(string somethingToLog)
   {
      Console.WriteLine("{0:HH:mm:ss} - {1}", DateTime.Now, somethingToLog);
   }
}

Although seemingly innocuous, it has two static dependencies on two other classes, System.DateTime and System.Console, which not only limit the logging output options (logging to console will be worthless if no one is watching), but worse, it is difficult to automatically test given the dependency on a non-deterministic system clock.

We can however apply DIP to this class, by abstracting out the the concern of timestamping as a dependency, and coupling MyLogger only to a simple interface:

public interface IClock
{
    DateTime Now { get; }
}

We can also loosen the dependency on Console to an abstraction, such as a TextWriter. Dependency Injection is typically implemented as either constructor injection (passing an abstraction to a dependency as a parameter to the constructor of a consuming class) or Setter Injection (passing the dependency via a setXyz() setter or a .Net Property with {set;} defined). Constructor Injection is preferred, as this guarantees the class will be in a correct state after construction, and allows the internal dependency fields to be marked as readonly (C#) or final (Java). So using constructor injection on the above example, this leaves us with:

public class MyLogger : ILogger // Others will depend on our logger.
{
    private readonly TextWriter _output;
    private readonly IClock _clock;

    // Dependencies are injected through the constructor
    public MyLogger(TextWriter stream, IClock clock)
    {
        _output = stream;
        _clock = clock;
    }

    public void LogRecord(string somethingToLog)
    {
        // We can now use our dependencies through the abstraction 
        // and without knowledge of the lifespans of the dependencies
        _output.Write("{0:yyyy-MM-dd HH:mm:ss} - {1}", _clock.Now, somethingToLog);
    }
}

(A concrete Clock needs to be provided, which of course could revert to DateTime.Now, and the two dependencies need to be provided by an IoC container via constructor injection)

An automated Unit Test can be built, which definitively proves that our logger is working correctly, as we now have control over the dependencies - the time, and we can spy on the written output:

[Test]
public void LoggingMustRecordAllInformationAndStampTheTime()
{
    // Arrange
    var mockClock = new Mock<IClock>();
    mockClock.Setup(c => c.Now).Returns(new DateTime(2015, 4, 11, 12, 31, 45));
    var fakeConsole = new StringWriter();

    // Act
    new MyLogger(fakeConsole, mockClock.Object)
        .LogRecord("Foo");

    // Assert
    Assert.AreEqual("2015-04-11 12:31:45 - Foo", fakeConsole.ToString());
}

Next Steps

Dependency injection is invariably associated with an Inversion of Control container(IoC), to inject (provide) the concrete dependency instances, and to manage lifespan instances. During the configuration / bootstrapping process, IoC containers allow the following to be defined:

  • mapping between each abstraction and the configured concrete implementation (e.g. "any time a consumer requests an IBar, return a ConcreteBar instance")
  • policies can be set up for the lifespan management of each dependency, e.g. to create a new object for each consumer instance, to share a singleton dependency instance across all consumers, to share the same dependency instance only across the same thread, etc.
  • In .Net, IoC containers are aware of protocols such as IDisposable and will take on the responsibility of Disposing dependencies in line with the configured lifespan management.

Typically, once IoC containers have been configured / bootstrapped, they operate seamlessly in the background allowing the coder to focus on the code at hand rather than worrying about dependencies.

The key to DI-friendly code is to avoid static coupling of classes, and not to use new() for the creation of Dependencies

As per above example, decoupling of dependencies does require some design effort, and for the developer, there is a paradigm shift needed to break the habit of newing dependencies directly, and instead trusting the container to manage dependencies.

But the benefits are many, especially in the ability to thoroughly test your class of interest.

Note : The creation / mapping / projection (via new ..()) of POCO / POJO / Serialization DTOs / Entity Graphs / Anonymous JSON projections et al - i.e. "Data only" classes or records - used or returned from methods are not regarded as Dependencies (in the UML sense) and not subject to DI. Using new to project these is just fine.

Programmatically Check an Item in Checkboxlist where text is equal to what I want

I tried adding dynamically created ListItem and assigning the selected value.

foreach(var item in yourListFromDB)
{
 ListItem listItem = new ListItem();
 listItem.Text = item.name;
 listItem.Value = Convert.ToString(item.value);
 listItem.Selected=item.isSelected;                 
  checkedListBox1.Items.Add(listItem);
}
checkedListBox1.DataBind();

avoid using binding the DataSource as it will not bind the checked/unchecked from DB.

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

This error message can happen if you have duplicate entries/entities and run SaveChanges().

PHP Constants Containing Arrays?

If you are using PHP 5.6 or above, use Andrea Faulds answer

I am using it like this. I hope, it will help others.

config.php

class app{
    private static $options = array(
        'app_id' => 'hello',
    );
    public static function config($key){
        return self::$options[$key];
    }
}

In file, where I need constants.

require('config.php');
print_r(app::config('app_id'));

Cycles in an Undirected Graph

You can solve it using DFS. Time complexity: O(n)

The essence of the algorithm is that if a connected component/graph does NOT contain a CYCLE, it will always be a TREE.See here for proof

Let us assume the graph has no cycle, i.e. it is a tree. And if we look at a tree, each edge from a node:

1.either reaches to its one and only parent, which is one level above it.

2.or reaches to its children, which are one level below it.

So if a node has any other edge which is not among the two described above, it will obviously connect the node to one of its ancestors other than its parent. This will form a CYCLE.

Now that the facts are clear, all you have to do is run a DFS for the graph (considering your graph is connected, otherwise do it for all unvisited vertices), and IF you find a neighbor of the node which is VISITED and NOT its parent, then my friend there is a CYCLE in the graph, and you're DONE.

You can keep track of parent by simply passing the parent as parameter when you do DFS for its neighbors. And Since you only need to examine n edges at the most, the time complexity will be O(n).

Hope the answer helped.

django no such table:

Updated answer for Django migrations without south plugin:

Like T.T suggested in his answer, my previous answer was for south migration plugin, when Django hasn't any schema migration features. Now (works in Django 1.9+):

T.T wrote:

You can try this!

python manage.py makemigrations

python manage.py migrate --run-syncdb

Outdated for south migrations plugin

As I can see you done it all in wrong order, to fix it up your should complete this checklist (I assume you can't delete sqlite3 database file to start over):

  1. Grab any SQLite GUI tool (i.e. http://sqliteadmin.orbmu2k.de/)
  2. Change your model definition to match database definition (best approach is to comment new fields)
  3. Delete migrations folder in your model
  4. Delete rows in south_migrationhistory table where app_name match your application name (probably homework)
  5. Invoke: ./manage.py schemamigration <app_name> --initial
  6. Create tables by ./manage.py migrate <app_name> --fake (--fake will skip SQL execute because table already exists in your database)
  7. Make changes to your app's model
  8. Invoke ./manage.py schemamigration <app_name> --auto
  9. Then apply changes to database: ./manage.py migrate <app_name>

Steps 7,8,9 repeat whenever your model needs any changes.

What is this: [Ljava.lang.Object;?

If you are here because of the Liquibase error saying:

Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short

and you are using

not {
  indexExists()
}

precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342

We can try to execute an above check using bare sqlCheck(Postgres):

SELECT COUNT(i.relname)
FROM
    pg_class t,
    pg_class i,
    pg_index ix
WHERE
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and t.relkind = 'r'
    and t.relname = 'tableName'
    and i.relname = 'indexName';

where tableName - is an index table name and indexName - is an index name

How to view files in binary from bash?

As a fallback there's always od -xc filename

Get HTML source of WebElement in Selenium WebDriver using Python

It looks outdated, but let it be here anyway. The correct way to do it in your case:

elem = wd.find_element_by_css_selector('#my-id')
html = wd.execute_script("return arguments[0].innerHTML;", elem)

or

html = elem.get_attribute('innerHTML')

Both are working for me (selenium-server-standalone-2.35.0).

Get viewport/window height in ReactJS

This answer is similar to Jabran Saeed's, except it handles window resizing as well. I got it from here.

constructor(props) {
  super(props);
  this.state = { width: 0, height: 0 };
  this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}

componentDidMount() {
  this.updateWindowDimensions();
  window.addEventListener('resize', this.updateWindowDimensions);
}

componentWillUnmount() {
  window.removeEventListener('resize', this.updateWindowDimensions);
}

updateWindowDimensions() {
  this.setState({ width: window.innerWidth, height: window.innerHeight });
}

Bootstrap datetimepicker is not a function

The problem is that you have not included bootstrap.min.css. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>                       
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

DEMO

Converting rows into columns and columns into rows using R

Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

library(tidyverse)

starting_df %>% 
  rownames_to_column() %>% 
  gather(variable, value, -rowname) %>% 
  spread(rowname, value)

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

smiths %>% 
    gather(variable, value, -subject) %>% 
    spread(subject, value)

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor if there are mixed column types unless stringsAsFactors = FALSE is added, whereas the tidyverse option converts everything to a character by default if there are mixed column types.

How do I connect to an MDF database file?

Alternative solution, where you can have the database in the folder you want inside the solution. That worked for me:

.ConnectionString(@"Data Source=LocalDB)\MSSQLLocalDB;
                    AttachDbFilename="+AppDomain.CurrentDomain.BaseDirectory+"Folder1\\Folder2\\SampleDatabase.mdf" + ";
                    Integrated Security=True;")

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

How to upload files to server using Putty (ssh)

You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.

How do you convert a byte array to a hexadecimal string, and vice versa?

There is also XmlWriter.WriteBinHex (see the MSDN page). This is very useful if you need to put the hexadecimal string into an XML stream.

Here is a standalone method to see how it works:

    public static string ToBinHex(byte[] bytes)
    {
        XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
        xmlWriterSettings.ConformanceLevel = ConformanceLevel.Fragment;
        xmlWriterSettings.CheckCharacters = false;
        xmlWriterSettings.Encoding = ASCIIEncoding.ASCII;
        MemoryStream memoryStream = new MemoryStream();
        using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
        {
            xmlWriter.WriteBinHex(bytes, 0, bytes.Length);
        }
        return Encoding.ASCII.GetString(memoryStream.ToArray());
    }

Bower: ENOGIT Git is not installed or not in the PATH

You are missing the ENVIRONMENT PATH. Follow these steps:

  1. Search for 'Edit the system environment variables'.
  2. Click on 'Environment Variables'.
  3. In the 'System variables' section, scroll down and click on the variable 'Path'. Click 'Edit'.
  4. Append this text to the end of the 'Variable value'.

;%PROGRAMFILES%\Git\bin;%PROGRAMFILES%\Git\cmd

How to stop process from .BAT file?

To terminate a process you know the name of, try:

taskkill /IM notepad.exe

This will ask it to close, but it may refuse, offer to "save changes", etc. If you want to forcibly kill it, try:

taskkill /F /IM notepad.exe

How can I access my localhost from my Android device?

Run CMD as administrator

and on CMD screen type ipconfig and the screen will appear with text

as this photo enter image description here

and you can access your localhost using this ip you have to be connected to same network as your pc connected to

How do I execute a bash script in Terminal?

If you are in a directory or folder where the script file is available then simply change the file permission in executable mode by doing

chmod +x your_filename.sh

After that you will run the script by using the following command.

$ sudo ./your_filename.sh

Above the "." represent the current directory. Note! If you are not in the directory where the bash script file is present then you change the directory where the file is located by using

cd Directory_name/write the complete path

command. Otherwise your script can not run.

Uses of content-disposition in an HTTP response header

Well, it seems that the Content-Disposition header was originally created for e-mail, not the web. (Link to relevant RFC.)

I'm guessing that web browsers may respond to

Response.AppendHeader("content-disposition", "inline; filename=" + fileName);

when saving, but I'm not sure.

How do you write to a folder on an SD card in Android?

Add Permission to Android Manifest

Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.company.package"
    android:versionCode="1"
    android:versionName="0.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- ... -->
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 

Check availability of external storage

You should always check for availability first. A snippet from the official android documentation on external storage.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

Use a Filewriter

At last but not least forget about the FileOutputStream and use a FileWriter instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.

// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file
writer.write("This\n is\n an\n example\n"); 
writer.flush();
writer.close();

How to directly initialize a HashMap (in a literal way)?

This is one way.

Map<String, String> h = new HashMap<String, String>() {{
    put("a","b");
}};

However, you should be careful and make sure that you understand the above code (it creates a new class that inherits from HashMap). Therefore, you should read more here: http://www.c2.com/cgi/wiki?DoubleBraceInitialization , or simply use Guava:

Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);

ImmutableMap.of works for up to 5 entries. Otherwise, use the builder: source.

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

Unzipping files in Python

zipfile is a somewhat low-level library. Unless you need the specifics that it provides, you can get away with shutil's higher-level functions make_archive and unpack_archive.

make_archive is already described in this answer. As for unpack_archive:

import shutil
shutil.unpack_archive(filename, extract_dir)

unpack_archive detects the compression format automatically from the "extension" of filename (.zip, .tar.gz, etc), and so does make_archive. Also, filename and extract_dir can be any path-like objects (e.g. pathlib.Path instances) since Python 3.7.

Import CSV to mysql table

Instead of writing a script to pull in information from a CSV file, you can link MYSQL directly to it and upload the information using the following SQL syntax.

To import an Excel file into MySQL, first export it as a CSV file. Remove the CSV headers from the generated CSV file along with empty data that Excel may have put at the end of the CSV file.

You can then import it into a MySQL table by running:

load data local infile 'uniq.csv' into table tblUniq fields terminated by ','
  enclosed by '"'
  lines terminated by '\n'
    (uniqName, uniqCity, uniqComments)

as read on: Import CSV file directly into MySQL

EDIT

For your case, you'll need to write an interpreter first, for finding the first row, and assigning them as column names.


EDIT-2

From MySQL docs on LOAD DATA syntax:

The IGNORE number LINES option can be used to ignore lines at the start of the file. For example, you can use IGNORE 1 LINES to skip over an initial header line containing column names:

LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test IGNORE 1 LINES;

Therefore, you can use the following statement:

LOAD DATA LOCAL INFILE 'uniq.csv'
INTO TABLE tblUniq
FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(uniqName, uniqCity, uniqComments)

How do I pass a class as a parameter in Java?

This kind of thing is not easy. Here is a method that calls a static method:

public static Object callStaticMethod(
    // class that contains the static method
    final Class<?> clazz,
    // method name
    final String methodName,
    // optional method parameters
    final Object... parameters) throws Exception{
    for(final Method method : clazz.getMethods()){
        if(method.getName().equals(methodName)){
            final Class<?>[] paramTypes = method.getParameterTypes();
            if(parameters.length != paramTypes.length){
                continue;
            }
            boolean compatible = true;
            for(int i = 0; i < paramTypes.length; i++){
                final Class<?> paramType = paramTypes[i];
                final Object param = parameters[i];
                if(param != null && !paramType.isInstance(param)){
                    compatible = false;
                    break;
                }

            }
            if(compatible){
                return method.invoke(/* static invocation */null,
                    parameters);
            }
        }
    }
    throw new NoSuchMethodException(methodName);
}

Update: Wait, I just saw the gwt tag on the question. You can't use reflection in GWT

Converting from Integer, to BigInteger

The method you want is BigInteger#valueOf(long val).

E.g.,

BigInteger bi = BigInteger.valueOf(myInteger.intValue());

Making a String first is unnecessary and undesired.

Tips for using Vim as a Java IDE?

I found the following summary very useful: http://www.techrepublic.com/article/configure-vi-for-java-application-development/5054618. The description of :make was for ant not maven, but otherwise a nice summary.

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

How to center an element in the middle of the browser window?

I had a lot of problems with centring and alignment until I found Flexbox as a recommendation in a guide.

A Complete Guide to Flexbox

I'll post a snippet (that works with Chrome) here for convenience:

<head>
    <style type="text/css">
        html
        {
            width: 100%;
            height: 100%;
        }

        body
        {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>

<body>
    This is text!
</body>

For more details, please refer to the article.

How to make child element higher z-index than parent?

Try using this code, it worked for me:

z-index: unset;

How to print to console when using Qt

Writing to stdout

If you want something that, like std::cout, writes to your application's standard output, you can simply do the following (credit to CapelliC):

QTextStream(stdout) << "string to print" << endl;

If you want to avoid creating a temporary QTextStream object, follow Yakk's suggestion in the comments below of creating a function to return a static handle for stdout:

inline QTextStream& qStdout()
{
    static QTextStream r{stdout};
    return r;
}

...

foreach(QString x, strings)
    qStdout() << x << endl;

Remember to flush the stream periodically to ensure the output is actually printed.

Writing to stderr

Note that the above technique can also be used for other outputs. However, there are more readable ways to write to stderr (credit to Goz and the comments below his answer):

qDebug() << "Debug Message";    // CAN BE REMOVED AT COMPILE TIME!
qWarning() << "Warning Message";
qCritical() << "Critical Error Message";
qFatal("Fatal Error Message");  // WILL KILL THE PROGRAM!

qDebug() is closed if QT_NO_DEBUG_OUTPUT is turned on at compile-time.

(Goz notes in a comment that for non-console apps, these can print to a different stream than stderr.)


NOTE: All of the Qt print methods assume that const char* arguments are ISO-8859-1 encoded strings with terminating \0 characters.

How to convert DateTime? to DateTime

Try this

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;

How to make a phone call programmatically?

Tried this on my phone and it works perfectly.

Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:900..." ));
startActivity(intent);

Add this permission in manifest file.

<uses-permission android:name="android.permission.CALL_PHONE" />

Way to get number of digits in an int?

We can achieve this using a recursive loop

    public static int digitCount(int numberInput, int i) {
        while (numberInput > 0) {
        i++;
        numberInput = numberInput / 10;
        digitCount(numberInput, i);
        }
        return i;
    }

    public static void printString() {
        int numberInput = 1234567;
        int digitCount = digitCount(numberInput, 0);

        System.out.println("Count of digit in ["+numberInput+"] is ["+digitCount+"]");
    }

Regular expression to match characters at beginning of line only

There's are ambiguities in the question.

What is your input string? Is it the entire file? Or is it 1 line at a time? Some of the answers are assuming the latter. I want to answer the former.

What would you like to return from your regular expression? The fact that you want a true / false on whether a match was made? Or do you want to extract the entire line whose start begins with CTR? I'll answer you only want a true / false match.

To do this, we just need to determine if the CTR occurs at either the start of a file, or immediately following a new line.

/(?:^|\n)CTR/

How do I sort a vector of pairs based on the second element of the pair?

You can use boost like this:

std::sort(a.begin(), a.end(), 
          boost::bind(&std::pair<int, int>::second, _1) <
          boost::bind(&std::pair<int, int>::second, _2));

I don't know a standard way to do this equally short and concise, but you can grab boost::bind it's all consisting of headers.

C pointer to array/array of pointers disambiguation

Use the cdecl program, as suggested by K&R.

$ cdecl
Type `help' or `?' for help
cdecl> explain int* arr1[8];
declare arr1 as array 8 of pointer to int
cdecl> explain int (*arr2)[8]
declare arr2 as pointer to array 8 of int
cdecl> explain int *(arr3[8])
declare arr3 as array 8 of pointer to int
cdecl>

It works the other way too.

cdecl> declare x as pointer to function(void) returning pointer to float
float *(*x)(void )

Changing every value in a hash in Ruby

If you are curious which inplace variant is the fastest here it is:

Calculating -------------------------------------
inplace transform_values! 1.265k (± 0.7%) i/s -      6.426k in   5.080305s
      inplace update      1.300k (± 2.7%) i/s -      6.579k in   5.065925s
  inplace map reduce    281.367  (± 1.1%) i/s -      1.431k in   5.086477s
      inplace merge!      1.305k (± 0.4%) i/s -      6.630k in   5.080751s
        inplace each      1.073k (± 0.7%) i/s -      5.457k in   5.084044s
      inplace inject    697.178  (± 0.9%) i/s -      3.519k in   5.047857s

SeekBar and media player in android

    int  pos  = 0;
    yourSeekBar.setMax(mPlayer.getDuration());

After You start Your MediaPlayer i.e mplayer.start()

Try this code

while(mPlayer!=null){
         try {
                Thread.sleep(1000);
                pos  = mPlayer.getCurrentPosition();
            }  catch (Exception e) {
                //show exception in LogCat
            }
            yourSeekBar.setProgress(pos);

   }

Before you added this code you have to create xml resource for SeekBar and use it in Your Activity class of ur onCreate() method.

How to update json file with python

The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.

The easiest solution would be to close the file after you've read it in, then reopen it for writing.

with open("replayScript.json", "r") as jsonFile:
    data = json.load(jsonFile)

data["location"] = "NewPath"

with open("replayScript.json", "w") as jsonFile:
    json.dump(data, jsonFile)

Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.

with open("replayScript.json", "r+") as jsonFile:
    data = json.load(jsonFile)

    data["location"] = "NewPath"

    jsonFile.seek(0)  # rewind
    json.dump(data, jsonFile)
    jsonFile.truncate()

How to generate all permutations of a list?

And in Python 2.6 onwards:

import itertools
itertools.permutations([1,2,3])

(returned as a generator. Use list(permutations(l)) to return as a list.)

Where to get "UTF-8" string literal in Java?

Constant definitions for the standard. These charsets are guaranteed to be available on every implementation of the Java platform. since 1.7

 package java.nio.charset;
 Charset utf8 = StandardCharsets.UTF_8;

How to install the JDK on Ubuntu Linux

Simply run:

sudo apt-get install default-jdk

How do I check when a UITextField changes?

SWIFT

Swift 4.2

textfield.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)

and

@objc func textFieldDidChange(_ textField: UITextField) {

}

SWIFT 3 & swift 4.1

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)

and

func textFieldDidChange(_ textField: UITextField) {

}

SWIFT 2.2

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)

and

func textFieldDidChange(textField: UITextField) {
    //your code
}

OBJECTIVE-C

[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

and textFieldDidChange method is

-(void)textFieldDidChange :(UITextField *) textField{
    //your code
}

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

If using Tomcat 6 and earlier, make sure the keystore password and the key password are same. If using Tomcat 7 and later, make sure they are the same or that the key password is specified in the server.xml file.

What are the uses of "using" in C#?

Things like this:

using (var conn = new SqlConnection("connection string"))
{
   conn.Open();

    // Execute SQL statement here on the connection you created
}

This SqlConnection will be closed without needing to explicitly call the .Close() function, and this will happen even if an exception is thrown, without the need for a try/catch/finally.

How does one capture a Mac's command key via JavaScript?

Basing on Ilya's data, I wrote a Vanilla JS library for supporting modifier keys on Mac: https://github.com/MichaelZelensky/jsLibraries/blob/master/macKeys.js

Just use it like this, e.g.:

document.onclick = function (event) {
  if (event.shiftKey || macKeys.shiftKey) {
    //do something interesting
  }
}

Tested on Chrome, Safari, Firefox, Opera on Mac. Please check if it works for you.

How do I make a LinearLayout scrollable?

you can make any layout scrollable. Just under <?xml version="1.0" encoding="utf-8"?> add these lines:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

and at the end add </ScrollView>

example of a non-scrollable activity:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:verticalScrollbarPosition="right"
    tools:context="p32929.demo.MainActivity">


    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="102dp"
        android:id="@+id/textView"
        android:textSize="30sp" />
</RelativeLayout>

After making it scrollable, it becomes like this:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:verticalScrollbarPosition="right"
        tools:context="p32929.demo.MainActivity">


        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="102dp"
            android:text="TextView"
            android:textSize="30sp" />
    </RelativeLayout>
</ScrollView>

Check if pull needed in Git

I use a version of a script based on Stephen Haberman's answer:

if [ -n "$1" ]; then
    gitbin="git -C $1"
else
    gitbin="git"
fi

# Fetches from all the remotes, although --all can be replaced with origin
$gitbin fetch --all
if [ $($gitbin rev-parse HEAD) != $($gitbin rev-parse @{u}) ]; then
    $gitbin rebase @{u} --preserve-merges
fi

Assuming this script is called git-fetch-and-rebase, it can be invoked with an optional argument directory name of the local Git repository to perform operation on. If the script is called with no arguments, it assumes the current directory to be part of the Git repository.

Examples:

# Operates on /abc/def/my-git-repo-dir
git-fetch-and-rebase /abc/def/my-git-repo-dir

# Operates on the Git repository which the current working directory is part of
git-fetch-and-rebase

It is available here as well.

How to remove a field completely from a MongoDB document?

In the beginning, I did not get why the question has a bounty (I thought that the question has a nice answer and there is nothing to add), but then I noticed that the answer which was accepted and upvoted 15 times was actually wrong!

Yes, you have to use $unset operator, but this unset is going to remove the words key which does not exist for a document for a collection. So basically it will do nothing.

So you need to tell Mongo to look in the document tags and then in the words using dot notation. So the correct query is.

db.example.update(
  {},
  { $unset: {'tags.words':1}},
  false, true
)

Just for the sake of completion, I will refer to another way of doing it, which is much worse, but this way you can change the field with any custom code (even based on another field from this document).

How to find the foreach index?

foreach($array as $key=>$value) {
    // do stuff
}

$key is the index of each $array element

add maven repository to build.gradle

You will need to define the repository outside of buildscript. The buildscript configuration block only sets up the repositories and dependencies for the classpath of your build script but not your application.

How to exit an if clause

Generally speaking, don't. If you are nesting "ifs" and breaking from them, you are doing it wrong.

However, if you must:

if condition_a:
   def condition_a_fun():
       do_stuff()
       if we_wanna_escape:
           return
   condition_a_fun()
if condition_b:
   def condition_b_fun():
       do_more_stuff()
       if we_wanna_get_out_again:
           return
   condition_b_fun()

Note, the functions don't HAVE to be declared in the if statement, they can be declared in advance ;) This would be a better choice, since it will avoid needing to refactor out an ugly if/then later on.

Sending email from Azure

If you're looking for some ESP alternatives, you should have a look at Mailjet for Microsoft Azure too! As a global email service and infrastructure provider, they enable you to send, deliver and track transactional and marketing emails via their APIs, SMTP Relay or UI all from one single platform, thought both for developers and emails owners.

Disclaimer: I’m working at Mailjet as a Developer Evangelist.

Hibernate vs JPA vs JDO - pros and cons of each?

Anyone who says that JDO is dead is an astroturfing FUD monger and they know it.

JDO is alive and well. The specification is still more powerful, mature and advanced than the much younger and constrained JPA.

If you want to limit yourself to only what's available in the JPA standard you can write to JPA and use DataNucleus as a high performance, more transparent persistence implementation than the other implementations of JPA. Of course DataNucleus also implements the JDO standard if you want the flexibility and efficiency of modeling that JDO brings.

Java: how do I check if a Date is within a certain range?

your logic would work fine . As u mentioned the dates ur getting from the database are in timestamp , You just need to convert timestamp to date first and then use this logic.

Also dont forget to check for null dates.

here m sharing a bit to convert from Timestamp to date.

public static Date convertTimeStamptoDate(String val) throws Exception {

    DateFormat df = null;
    Date date = null;

    try {
        df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        date = df.parse(val);
        // System.out.println("Date Converted..");
        return date;
    } catch (Exception ex) {
        System.out.println(ex);
        return convertDate2(val);
    } finally {
        df = null;
        date = null;
    }
}

Nested lists python

Try this setup:

a = [["a","b","c",],["d","e"],["f","g","h"]]

To print the 2nd element in the 1st list ("b"), use print a[0][1] - For the 2nd element in 3rd list ("g"): print a[2][1]

The first brackets reference which nested list you're accessing, the second pair references the item in that list.

Changing background color of ListView items on Android

the easiest way is this. Inside your ListArrayAdapter just do this

if(your condition here) rowView.setBackgroundColor(Color.parseColor("#20FFFFFF"));

don't over complicate

NameError: uninitialized constant (rails)

I was getting the error:

NameError: uninitialized constant

Then I noticed that I had accidentally created a plural model so I went back and renamed the model file to singular and also changed the class name in the model file to singular and that solved it.

Could not create work tree dir 'example.com'.: Permission denied

I think you don't have your permissions set up correctly for /var/www Change the ownership of the folder.

sudo chown -R **yourusername** /var/www

json_encode() escaping forward slashes

Yes, but don't - escaping forward slashes is a good thing. When using JSON inside <script> tags it's necessary as a </script> anywhere - even inside a string - will end the script tag.

Depending on where the JSON is used it's not necessary, but it can be safely ignored.

Absolute and Flexbox in React Native

This solution worked for me:

tabBarOptions: {
      showIcon: true,
      showLabel: false,
      style: {
        backgroundColor: '#000',
        borderTopLeftRadius: 40,
        borderTopRightRadius: 40,
        position: 'relative',
        zIndex: 2,
        marginTop: -48
      }
  }

Found 'OR 1=1/* sql injection in my newsletter database

'OR 1=1 is an attempt to make a query succeed no matter what
The /* is an attempt to start a multiline comment so the rest of the query is ignored.

An example would be

SELECT userid 
FROM users 
WHERE username = ''OR 1=1/*' 
    AND password = ''
    AND domain = ''

As you can see if you were to populate the username field without escaping the ' no matter what credentials the user passes in the query would return all userids in the system likely granting access to the attacker (possibly admin access if admin is your first user). You will also notice the remainder of the query would be commented out because of the /* including the real '.

The fact that you can see the value in your database means that it was escaped and that particular attack did not succeed. However, you should investigate if any other attempts were made.

Get last field using awk substr

You can also use:

    sed -n 's/.*\/\([^\/]\{1,\}\)$/\1/p'

or

    sed -n 's/.*\/\([^\/]*\)$/\1/p'

AttributeError: 'str' object has no attribute 'strftime'

you should change cr_date(str) to datetime object then you 'll change the date to the specific format:

cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")

How to format html table with inline styles to look like a rendered Excel table?

Add cellpadding and cellspacing to solve it. Edit: Also removed double pixel border.

<style>
td
{border-left:1px solid black;
border-top:1px solid black;}
table
{border-right:1px solid black;
border-bottom:1px solid black;}
</style>
<html>
    <body>
        <table cellpadding="0" cellspacing="0">
            <tr>
                <td width="350" >
                    Foo
                </td>
                <td width="80" >
                    Foo1
                </td>
                <td width="65" >
                    Foo2
                </td>
            </tr>
            <tr>
                <td>
                    Bar1
                </td>
                <td>
                    Bar2
                </td>
                <td>
                    Bar3
                </td>
            </tr>
            <tr >
                <td>
                    Bar1
                </td>
                <td>
                    Bar2
                </td>
                <td>
                    Bar3
                </td>
            </tr>
        </table>
    </body>
</html>

curl_init() function not working

I got this error using PHP7 / Apache 2.4 on a windows platform. curl_init worked from CLI but not with Apache 2.4. I resolved it by adding LoadFile directives for libeay32.dll and ssleay32.dll:

LoadFile "C:/path/to/Php7/libeay32.dll"
LoadFile "C:/path/to/Php7/ssleay32.dll"
LoadFile "C:/path/to/Php7/php7ts.dll"
LoadModule php7_module "C:/path/to/Php7/php7apache2_4.dll"

How to kill a process in MacOS?

Given the path to your program, I assume you're currently running this under Xcode, and are probably at a debug breakpoint. Processes cannot be killed in this state because of the underlying implementation of breakpoints.

The first step would be to go to your Xcode process and stop debugging. If for some strange reason you have lost access to Xcode (perhaps Xcode has lost access to its gdb sub-process), then the solution is to kill the gdb process. More generally, the solution here is to kill the parent process. In your case this is PID 811 (the third column).

There is no need to use -9 in this case.

Why is the jquery script not working?

This works fine. just insert your jquery code in document.ready function.

 $(document).ready(function(e) {   
    // your code here
 });

example:

jquery

    $(document).ready(function(e) {   

      $('[id^=\"btnRight\"]').click(function (e) {    
        $(this).prev('select').find('option:selected').remove().appendTo('#isselect_code');    
      });

      $('[id^=\"btnLeft\"]').click(function (e) {
        $(this).next('select').find('option:selected').remove().appendTo('#canselect_code');
      });

    });

html

    <div>
        <select id='canselect_code' name='canselect_code' multiple class='fl'>
            <option value='1'>toto</option>
            <option value='2'>titi</option>
        </select>
        <input type='button' id='btnRight_code' value='  >  ' />
        <br>
        <input type='button' id='btnLeft_code' value='  <  ' />
        <select id='isselect_code' name='isselect_code' multiple class='fr'>
            <option value='3'>tata</option>
            <option value='4'>tutu</option>
        </select>
    </div>

How do I evenly add space between a label and the input field regardless of length of text?

You can also used below code

<html>
<head>
    <style>
        .labelClass{
            float: left;
            width: 113px;
        }
    </style>
</head>
<body>
  <form action="yourclassName.jsp">
    <span class="labelClass">First name: </span><input type="text" name="fname"><br>
    <span class="labelClass">Last name: </span><input type="text" name="lname"><br>
    <input type="submit" value="Submit">
  </form>
</body>
</html>

Is there any kind of hash code function in JavaScript?

If you want to have unique values in a lookup object you can do something like this:

Creating a lookup object

var lookup = {};

Setting up the hashcode function

function getHashCode(obj) {
    var hashCode = '';
    if (typeof obj !== 'object')
        return hashCode + obj;
    for (var prop in obj) // No hasOwnProperty needed
        hashCode += prop + getHashCode(obj[prop]); // Add key + value to the result string
    return hashCode;
}

Object

var key = getHashCode({ 1: 3, 3: 7 });
// key = '1337'
lookup[key] = true;

Array

var key = getHashCode([1, 3, 3, 7]);
// key = '01132337'
lookup[key] = true;

Other types

var key = getHashCode('StackOverflow');
// key = 'StackOverflow'
lookup[key] = true;

Final result

{ 1337: true, 01132337: true, StackOverflow: true }

Do note that getHashCode doesn't return any value when the object or array is empty

getHashCode([{},{},{}]);
// '012'
getHashCode([[],[],[]]);
// '012'

This is similar to @ijmacd solution only getHashCode doesn't has the JSON dependency.

Spring Boot Program cannot find main class

I was having the same problem just delete .m2 folder folder from your local repositry Hope it will work.

Read contents of a local file into a variable in Rails

I think you should consider using IO.binread("/path/to/file") if you have a recent ruby interpreter (i.e. >= 1.9.2)

You could find IO class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html

How to pass the button value into my onclick event function?

You can pass the value to the function using this.value, where this points to the button

<input type="button" value="mybutton1" onclick="dosomething(this.value)">

And then access that value in the function

function dosomething(val){
  console.log(val);
}

Refresh image with a new one at the same url

As an alternative to...

newImage.src = "http://localhost/image.jpg?" + new Date().getTime();

...it seems that...

newImage.src = "http://localhost/image.jpg#" + new Date().getTime();

...is sufficient to fool the browser cache without bypassing any upstream caches, assuming you returned the correct Cache-Control headers. Although you can use...

Cache-Control: no-cache, must-revalidate

...you lose the benefits of the If-Modified-Since or If-None-Match headers, so something like...

Cache-Control: max-age=0, must-revalidate

...should prevent the browser from re-downloading the entire image if it hasn't actually changed. Tested and working on IE, Firefox, and Chrome. Annoyingly it fails on Safari unless you use...

Cache-Control: no-store

...although this still may be preferable to filling upstream caches with hundreds of identical images, particularly when they're running on your own server. ;-)

Update (2014-09-28): Nowadays it looks like Cache-Control: no-store is needed for Chrome as well.

Laravel Fluent Query Builder Join with subquery

Ok for all of you out there that arrived here in desperation searching for the same problem. I hope you will find this quicker then I did ;O.

This is how it is solved. JoostK told me at github that "the first argument to join is the table (or data) you're joining.". And he was right.

Here is the code. Different table and names but you will get the idea right? It t

DB::table('users')
        ->select('first_name', 'TotalCatches.*')

        ->join(DB::raw('(SELECT user_id, COUNT(user_id) TotalCatch,
               DATEDIFF(NOW(), MIN(created_at)) Days,
               COUNT(user_id)/DATEDIFF(NOW(), MIN(created_at))
               CatchesPerDay FROM `catch-text` GROUP BY user_id)
               TotalCatches'), 
        function($join)
        {
           $join->on('users.id', '=', 'TotalCatches.user_id');
        })
        ->orderBy('TotalCatches.CatchesPerDay', 'DESC')
        ->get();

How to fix "Headers already sent" error in PHP

You do

printf ("Hi %s,</br />", $name);

before setting the cookies, which isn't allowed. You can't send any output before the headers, not even a blank line.

Simple Java Client/Server Program

My try to do client socket program

server reads file and print it to console and copies it to output file

Server Program:

package SocketProgramming.copy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerRecieveFile {
    public static void main(String[] args) throws IOException {
        // TODO Auto-enerated method stub
        int filesize = 1022386;
        int bytesRead;
        int currentTot;
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        ServerSocket serverSocket = new ServerSocket(15123);
        while (true) {
            Socket socket = serverSocket.accept();
            byte[] bytearray = new byte[filesize];
            InputStream is = socket.getInputStream();
            File copyFileName = new File("C:/Users/Username/Desktop/Output_file.txt");
            FileOutputStream fos = new FileOutputStream(copyFileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(bytearray, 0, bytearray.length);
            currentTot = bytesRead;
            do {
                bytesRead = is.read(bytearray, currentTot,
                        (bytearray.length - currentTot));
                if (bytesRead >= 0)
                    currentTot += bytesRead;
            } while (bytesRead > -1);
            bos.write(bytearray, 0, currentTot);
            bos.flush();
            bos.close();
            socket.close();
        }
    }
}

Client program:

package SocketProgramming.copy;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientSendFile {
    public static void main(String[] args) throws UnknownHostException,
            IOException {
        // final String FILE_NAME="C:/Users/Username/Desktop/Input_file.txt";
        final String FILE_NAME = "C:/Users/Username/Desktop/Input_file.txt";
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        Socket socket = new Socket(InetAddress.getLocalHost(), 15123);
        System.out.println("Accepted connection : " + socket);
        File transferFile = new File(FILE_NAME);
        byte[] bytearray = new byte[(int) transferFile.length()];
        FileInputStream fin = new FileInputStream(transferFile);
        BufferedInputStream bin = new BufferedInputStream(fin);
        bin.read(bytearray, 0, bytearray.length);
        OutputStream os = socket.getOutputStream();
        System.out.println("Sending Files...");

        os.write(bytearray, 0, bytearray.length);

        BufferedReader r = new BufferedReader(new FileReader(FILE_NAME));
        String as = "", line = null;
        while ((line = r.readLine()) != null) {
            as += line + "\n";
            // as += line;

        }
        System.out.print("Input File contains following data: " + as);
        os.flush();
        fin.close();
        bin.close();
        os.close();
        socket.close();

        System.out.println("File transfer complete");
    }
}

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

This code defines a function fixed_sum_digits returning a generator enumerating all six digits numbers such that the sum of digits is 20.

def iter_fun(sum, deepness, myString, Total):
    if deepness == 0:
        if sum == Total:
            yield myString
    else:  
        for i in range(min(10, Total - sum + 1)):
            yield from iter_fun(sum + i,deepness - 1,myString + str(i),Total)

def fixed_sum_digits(digits, Tot):
    return iter_fun(0,digits,"",Tot) 

Try to write it without yield from. If you find an effective way to do it let me know.

I think that for cases like this one: visiting trees, yield from makes the code simpler and cleaner.

How to initialize an array in Kotlin with values?

Here's an example:

fun main(args: Array<String>) {
    val arr = arrayOf(1, 2, 3);
    for (item in arr) {
        println(item);
    }
}

You can also use a playground to test language features.

How does one create an InputStream from a String?

InputStream in = new ByteArrayInputStream(yourstring.getBytes());

PHP Fatal error: Class 'PDO' not found

If you run php with php-fpm module,do not forget to run command systemctl restart php-fpm!That will reload php-fpm module.

JavaScript listener, "keypress" doesn't detect backspace?

My numeric control:

function CheckNumeric(event) {
    var _key = (window.Event) ? event.which : event.keyCode;
    if (_key > 95 && _key < 106) {
        return true;
    }
    else if (_key > 47 && _key < 58) {
        return true;
    }
    else {
        return false;
    }
}

<input type="text" onkeydown="return CheckNumerick(event);" />

try it

BackSpace key code is 8

Get Specific Columns Using “With()” Function in Laravel Eloquent

So, similar to other solutions here is mine:

// For example you have this relation defined with "user()" method
public function user()
{
    return $this->belongsTo('User');
}
// Just make another one defined with "user_frontend()" method
public function user_frontend()
{
    return $this->belongsTo('User')->select(array('id', 'username'));
}

// Then use it later like this
$thing = new Thing();
$thing->with('user_frontend');

// This way, you get only id and username, 
// and if you want all fields you can do this

$thing = new Thing();
$thing->with('user');

Arithmetic overflow error converting numeric to data type numeric

If you want to reduce the size to decimal(7,2) from decimal(9,2) you will have to account for the existing data with values greater to fit into decimal(7,2). Either you will have to delete those numbers are truncate it down to fit into your new size. If there was no data for the field you are trying to update it will do it automatically without issues

How to add a new line in textarea element?

<textarea cols='60' rows='8'>This is my statement one.

This is my statement2</textarea>

Fiddle showing that it works: http://jsfiddle.net/trott/5vu28/.

If you really want this to be on a single line in the source file, you could insert the HTML character references for a line feed and a carriage return as shown in the answer from @Bakudan:

_x000D_
_x000D_
  <textarea cols='60' rows='8'>This is my statement one.&#13;&#10;This is my statement2</textarea>
_x000D_
_x000D_
_x000D_

Laravel 5 route not defined, while it is?

This thread is old but was the first one to come up so I thought id share my solution too. Apart from having named routes in your routes.php file. This error can also occur when you have duplicate URLs in your routes file, but with different names, the error can be misleading in this scenario. Example

Route::any('official/form/reject-form', 'FormStatus@rejectForm')->name('reject-form');  


Route::any('official/form/accept-form', 'FormStatus@acceptForm')->name('accept-form');

Changing one of the names solves the problem. Copy pasting and fatigue will get you to this problem :).

How to force a line break on a Javascript concatenated string?

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

Ajax passing data to php script

You are sending a POST AJAX request so use $albumname = $_POST['album']; on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:

$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: { album: this.title },
    success: function(response) {
        content.html(response);
    }
});

or in its shorter form:

$.post('test.php', { album: this.title }, function() {
    content.html(response);
});

and if you wanted to use a GET request:

$.ajax({  
    type: 'GET',
    url: 'test.php', 
    data: { album: this.title },
    success: function(response) {
        content.html(response);
    }
});

or in its shorter form:

$.get('test.php', { album: this.title }, function() {
    content.html(response);
});

and now on your server you wil be able to use $albumname = $_GET['album'];. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false setting.

SVN how to resolve new tree conflicts when file is added on two branches

I found a post suggesting a solution for that. It's about to run:

svn resolve --accept working <YourPath>

which will claim the local version files as OK.
You can run it for single file or entire project catalogues.

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

How to compare strings in an "if" statement?

You can't compare array of characters using == operator. You have to use string compare functions. Take a look at Strings (c-faq).

The standard library's strcmp function compares two strings, and returns 0 if they are identical, or a negative number if the first string is alphabetically "less than" the second string, or a positive number if the first string is "greater."

Convert iterator to pointer?

If your function really takes vector<int> * (a pointer to vector), then you should pass &foo since that will be a pointer to the vector. Obviously that will not simply solve your problem, but you cannot directly convert an iterator to a vector, since the memory at the address of the iterator will not directly address a valid vector.

You can construct a new vector by calling the vector constructor:

template <class InputIterator> vector(InputIterator, InputIterator)

This constructs a new vector by copying the elements between the two iterators. You would use it roughly like this:

bar(std::vector<int>(foo.begin()+1, foo.end());

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

I got solution. For pre-8.0 devices, you have to just use startService(), but for post-7.0 devices, you have to use startForgroundService(). Here is sample for code to start service.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(new Intent(context, ServedService.class));
    } else {
        context.startService(new Intent(context, ServedService.class));
    }

And in service class, please add the code below for notification:

@Override
public void onCreate() {
    super.onCreate();
    startForeground(1,new Notification());
}

Where O is Android version 26.

If you don't want your service to run in Foreground and want it to run in background instead, post Android O you must bind the service to a connection like below:

Intent serviceIntent = new Intent(context, ServedService.class);
context.startService(serviceIntent);
context.bindService(serviceIntent, new ServiceConnection() {
     @Override
     public void onServiceConnected(ComponentName name, IBinder service) {
         //retrieve an instance of the service here from the IBinder returned 
         //from the onBind method to communicate with 
     }

     @Override
     public void onServiceDisconnected(ComponentName name) {
     }
}, Context.BIND_AUTO_CREATE);

How do you count the number of occurrences of a certain substring in a SQL varchar?

I finally write this function that should cover all the possible situations, adding a char prefix and suffix to the input. this char is evaluated to be different to any of the char conteined in the search parameter, so it can't affect the result.

CREATE FUNCTION [dbo].[CountOccurrency]
(
@Input nvarchar(max),
@Search nvarchar(max)
)
RETURNS int AS
BEGIN
    declare @SearhLength as int = len('-' + @Search + '-') -2;
    declare @conteinerIndex as int = 255;
    declare @conteiner as char(1) = char(@conteinerIndex);
    WHILE ((CHARINDEX(@conteiner, @Search)>0) and (@conteinerIndex>0))
    BEGIN
        set @conteinerIndex = @conteinerIndex-1;
        set @conteiner = char(@conteinerIndex);
    END;
    set @Input = @conteiner + @Input + @conteiner
    RETURN (len(@Input) - len(replace(@Input, @Search, ''))) / @SearhLength
END 

usage

select dbo.CountOccurrency('a,b,c,d ,', ',')

How to redirect on another page and pass parameter in url from table?

Do this :

<script type="text/javascript">
function showDetails(username)
{
   window.location = '/player_detail?username='+username;
}
</script>

<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">

fatal: bad default revision 'HEAD'

Not committed yet?

It is a orphan branch if it has no commit.

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

this is easy,
if you use .htaccess , check http: for https: ,
if you use codeigniter, check config : url_base -> you url http change for https.....
I solved my problem.

How to check if running as root in a bash script

Check for root:

ROOT_UID=0   # Root has $UID 0.

if [ "$UID" -eq "$ROOT_UID" ]
then
  echo "You are root."
else
  echo "You are just an ordinary user."
fi

exit 0

Tested and running in root.

How to make an android app to always run in background?

In mi and vivo - Using the above solution is not enough. You must also tell the user to add permission manually. You can help them by opening the right location inside phone settings. Varies for different phone models.

How to open a link in new tab using angular?

you can try binding property whit route

in your component.ts user:any = 'linkABC';

in your component.html <a target="_blank" href="yourtab/{{user}}">new tab </a>

Where is SQL Profiler in my SQL Server 2008?

SQL Server Express does not come with profiler, but you can use SQL Server 2005/2008 Express Profiler instead.

How to compare files from two different branches?

You can do this: git diff branch1:path/to/file branch2:path/to/file

If you have difftool configured, then you can also: git difftool branch1:path/to/file branch2:path/to/file

Related question: How do I view git diff output with visual diff program

CURL to access a page that requires a login from a different page

Also you might want to log in via browser and get the command with all headers including cookies:

Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".

screenshot

Normalizing a list of numbers in Python

Use scikit-learn:

from sklearn.preprocessing import MinMaxScaler
data = np.array([1,2,3]).reshape(-1, 1)
scaler = MinMaxScaler()
scaler.fit(data)
print(scaler.transform(data))

node.js require all files in a folder?

I recommend using glob to accomplish that task.

var glob = require( 'glob' )
  , path = require( 'path' );

glob.sync( './routes/**/*.js' ).forEach( function( file ) {
  require( path.resolve( file ) );
});

How to load json into my angular.js ng-model?

As Kris mentions, you can use the $resource service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http service. In this case you can call its get method.

If you have the following JSON

[{ "text":"learn angular", "done":true },
 { "text":"build an angular app", "done":false},
 { "text":"something", "done":false },
 { "text":"another todo", "done":true }]

You can load it like this

var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
          $scope.todos = res.data;                
        });
});

The get method returns a promise object which first argument is a success callback and the second an error callback.

When you add $http as a parameter of a function Angular does it magic and injects the $http resource into your controller.

I've put some examples here

Hide separator line on one UITableViewCell

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}

jQuery AJAX form data serialize using PHP

I just had the same problem: You have to unserialize the data on the php side.

Add to the beginning of your php file (Attention this short version would replace all other post variables):

parse_str($_POST["data"], $_POST);

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

how to merge 200 csv files in Python

OR, you could just do

cat sh*.csv > merged.csv

Counting words in string

Try these before reinventing the wheels

from Count number of words in string using JavaScript

function countWords(str) {
  return str.trim().split(/\s+/).length;
}

from http://www.mediacollege.com/internet/javascript/text/count-words.html

function countWords(s){
    s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude  start and end white-space
    s = s.replace(/[ ]{2,}/gi," ");//2 or more space to 1
    s = s.replace(/\n /,"\n"); // exclude newline with a start spacing
    return s.split(' ').filter(function(str){return str!="";}).length;
    //return s.split(' ').filter(String).length; - this can also be used
}

from Use JavaScript to count words in a string, WITHOUT using a regex - this will be the best approach

function WordCount(str) {
     return str.split(' ')
            .filter(function(n) { return n != '' })
            .length;
}

Notes From Author:

You can adapt this script to count words in whichever way you like. The important part is s.split(' ').length — this counts the spaces. The script attempts to remove all extra spaces (double spaces etc) before counting. If the text contains two words without a space between them, it will count them as one word, e.g. "First sentence .Start of next sentence".

java.util.NoSuchElementException - Scanner reading user input

The problem is

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Thus scan.close() closes System.in.

To fix it you can make

Scanner scan static and do not close it in PromptCustomerQty. Code below works.

public static void main (String[] args) {   

// Create a customer
// Future proofing the possabiltiies of multiple customers
Customer customer = new Customer("Will");

// Create object for each Product
// (Name,Code,Description,Price)
// Initalize Qty at 0
Product Computer = new Product("Computer","PC1003","Basic Computer",399.99); 
Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99);
Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23);

// Define internal variables 
// ## DONT CHANGE 
ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products
String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output

// Add objects to list
ProductList.add(Computer);
ProductList.add(Monitor);
ProductList.add(Printer);

// Ask users for quantities 
PromptCustomerQty(customer, ProductList);

// Ask user for payment method
PromptCustomerPayment(customer);

// Create the header
PrintHeader(customer, formatString);

// Create Body
PrintBody(ProductList, formatString);   
}

static Scanner scan;

public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList)               {
// Initiate a Scanner
scan = new Scanner(System.in);

// **** VARIABLES ****
int qty = 0;

// Greet Customer
System.out.println("Hello " + customer.getName());

// Loop through each item and ask for qty desired
for (Product p : ProductList) {

    do {
    // Ask user for qty
    System.out.println("How many would you like for product: " + p.name);
    System.out.print("> ");

    // Get input and set qty for the object
    qty = scan.nextInt();

    }
    while (qty < 0); // Validation

    p.setQty(qty); // Set qty for object
    qty = 0; // Reset count
}

// Cleanup

}

public static void PromptCustomerPayment (Customer customer) {
// Variables
String payment = "";

// Prompt User
do {
System.out.println("Would you like to pay in full? [Yes/No]");
System.out.print("> ");

payment = scan.next();

} while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no")));

// Check/set result
if (payment.toLowerCase() == "yes") {
    customer.setPaidInFull(true);
}
else {
    customer.setPaidInFull(false);
}
}

On a side note, you shouldn't use == for String comparision, use .equals instead.