Programs & Examples On #Relay

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I got this error because I forgot the type="module" inside the script tag:

<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>

Flutter: RenderBox was not laid out

Wrap your ListView in an Expanded widget

 Expanded(child:MyListView())

UICollectionView - dynamic cell height?

Follow bolnad answer up to Step 4.

Then make it simpler by replacing all the other steps with:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    // Configure your cell
    sizingNibNew.configureCell(data as! CustomCellData, delegate: self)

    // We use the full width minus insets
    let width = collectionView.frame.size.width - collectionView.sectionInset.left - collectionView.sectionInset.right

    // Constrain our cell to this width 
    let height = sizingNibNew.systemLayoutSizeFitting(CGSize(width: width, height: .infinity), withHorizontalFittingPriority: UILayoutPriorityRequired, verticalFittingPriority: UILayoutPriorityFittingSizeLevel).height

    return CGSize(width: width, height: height)
}

App crashing when trying to use RecyclerView on android 5.0

Recyclerview recylerview = findbyid(R.id.recyclerview) May be you have missed it

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

The answer I have finally found is that the SMTP service on the server is not using the same certificate as https.

The diagnostic steps I had read here make the assumption they use the same certificate and every time I've tried this in the past they have done and the diagnostic steps are exactly what I've done to solve the problem several times.

In this case those steps didn't work because the certificates in use were different, and the possibility of this is something I had never come across.

The solution is either to export the actual certificate from the server and then install it as a trusted certificate on my machine, or to get a different valid/trusted certificate for the SMTP service on the server. That is currently with our IT department who administer the servers to decide which they want to do.

android.content.res.Resources$NotFoundException: String resource ID #0x0

Change

dateTime.setText(app.getTotalDl());

To

dateTime.setText(String.valueOf(app.getTotalDl()));

There are different versions of setText - one takes a String and one takes an int resource id. If you pass it an integer it will try to look for the corresponding string resource id - which it can't find, which is your error.

I guess app.getTotalDl() returns an int. You need to specifically tell setText to set it to the String value of this int.

setText (int resid) vs setText (CharSequence text)

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

How to configure SMTP settings in web.config

I don't have enough rep to answer ClintEastwood, and the accepted answer is correct for the Web.config file. Adding this in for code difference.

When your mailSettings are set on Web.config, you don't need to do anything other than new up your SmtpClient and .Send. It finds the connection itself without needing to be referenced. You would change your C# from this:

SmtpClient smtpClient = new SmtpClient("smtp.sender.you", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;
smtpClient.Send(msgMail);  

To this:

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(msgMail);

How to get current location in Android

I'm using this tutorial and it works nicely for my application.

In my activity I put this code:

GPSTracker tracker = new GPSTracker(this);
    if (!tracker.canGetLocation()) {
        tracker.showSettingsAlert();
    } else {
        latitude = tracker.getLatitude();
        longitude = tracker.getLongitude();
    }

also check if your emulator runs with Google API

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

Relay access denied on sending mail, Other domain outside of network

Configuring $mail->SMTPAuth = true; was the solution for me. The reason why is because without authentication the mail server answers with 'Relay access denied'. Since putting this in my code, all mails work fine.

Close Window from ViewModel

Well here is something I used in several projects. It may look like a hack, but it works fine.

public class AttachedProperties : DependencyObject //adds a bindable DialogResult to window
{
    public static readonly DependencyProperty DialogResultProperty = 
        DependencyProperty.RegisterAttached("DialogResult", typeof(bool?), typeof(AttachedProperties), 
        new PropertyMetaData(default(bool?), OnDialogResultChanged));

    public bool? DialogResult
    {
        get { return (bool?)GetValue(DialogResultProperty); }
        set { SetValue(DialogResultProperty, value); }
    }

    private static void OnDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var window = d as Window;
        if (window == null)
            return;

        window.DialogResult = (bool?)e.NewValue;
    }
}

Now you can bind DialogResult to a VM and set its value of a property. The Window will close, when the value is set.

<!-- Assuming that the VM is bound to the DataContext and the bound VM has a property DialogResult -->
<Window someNs:AttachedProperties.DialogResult={Binding DialogResult} />

This is an abstract of what's running in our production environment

<Window x:Class="AC.Frontend.Controls.DialogControl.Dialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:DialogControl="clr-namespace:AC.Frontend.Controls.DialogControl" 
        xmlns:hlp="clr-namespace:AC.Frontend.Helper"
        MinHeight="150" MinWidth="300" ResizeMode="NoResize" SizeToContent="WidthAndHeight"
        WindowStartupLocation="CenterScreen" Title="{Binding Title}"
        hlp:AttachedProperties.DialogResult="{Binding DialogResult}" WindowStyle="ToolWindow" ShowInTaskbar="True"
        Language="{Binding UiCulture, Source={StaticResource Strings}}">
        <!-- A lot more stuff here -->
</Window>

As you can see, I'm declaring the namespace xmlns:hlp="clr-namespace:AC.Frontend.Helper" first and afterwards the binding hlp:AttachedProperties.DialogResult="{Binding DialogResult}".

The AttachedProperty looks like this. It's not the same I posted yesterday, but IMHO it shouldn't have any effect.

public class AttachedProperties
{
    #region DialogResult

    public static readonly DependencyProperty DialogResultProperty =
        DependencyProperty.RegisterAttached("DialogResult", typeof (bool?), typeof (AttachedProperties), new PropertyMetadata(default(bool?), OnDialogResultChanged));

    private static void OnDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var wnd = d as Window;
        if (wnd == null)
            return;

        wnd.DialogResult = (bool?) e.NewValue;
    }

    public static bool? GetDialogResult(DependencyObject dp)
    {
        if (dp == null) throw new ArgumentNullException("dp");

        return (bool?)dp.GetValue(DialogResultProperty);
    }

    public static void SetDialogResult(DependencyObject dp, object value)
    {
        if (dp == null) throw new ArgumentNullException("dp");

        dp.SetValue(DialogResultProperty, value);
    }

    #endregion
}

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

To point your apex/root/naked domain at a Heroku-hosted application, you'll need to use a DNS provider who supports CNAME-like records (often referred to as ALIAS or ANAME records). Currently Heroku recommends:

Whichever of those you choose, your record will look like the following:

Record: ALIAS or ANAME

Name: empty or @

Target: example.com.herokudns.com.

That's all you need.


However, it's not good for SEO to have both the www version and non-www version resolve. One should point to the other as the canonical URL. How you decide to do that depends on if you're using HTTPS or not. And if you're not, you probably should be as Heroku now handles SSL certificates for you automatically and for free for all applications running on paid dynos.

If you're not using HTTPS, you can just set up a 301 Redirect record with most DNS providers pointing name www to http://example.com.

If you are using HTTPS, you'll most likely need to handle the redirection at the application level. If you want to know why, check out these short and long explanations but basically since your DNS provider or other URL forwarding service doesn't have, and shouldn't have, your SSL certificate and private key, they can't respond to HTTPS requests for your domain.

To handle the redirects at the application level, you'll need to:

  • Add both your apex and www host names to the Heroku application (heroku domains:add example.com and heroku domains:add www.example.com)
  • Set up your SSL certificates
  • Point your apex domain record at Heroku using an ALIAS or ANAME record as described above
  • Add a CNAME record with name www pointing to www.example.com.herokudns.com.
  • And then in your application, 301 redirect any www requests to the non-www URL (here's an example of how to do it in Django)
  • Also in your application, you should probably redirect any HTTP requests to HTTPS (for example, in Django set SECURE_SSL_REDIRECT to True)

Check out this post from DNSimple for more.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

WE had this issue. everything was setup fine in terms of permissions and security.

after MUCH needling around in the haystack. the issue was some sort of heuristics. in the email body , anytime a certain email address was listed, we would get the above error message from our exchange server.

it took 2 days of crazy testing and hair pulling to find this.

so if you have checked everything out, try changing the email body to only the word 'test'. If after that, your email goes out fine, you are having some sort of spam/heuristic filter issue like we were

TypeScript function overloading

This may be because, when both functions are compiled to JavaScript, their signature is totally identical. As JavaScript doesn't have types, we end up creating two functions taking same number of arguments. So, TypeScript restricts us from creating such functions.

TypeScript supports overloading based on number of parameters, but the steps to be followed are a bit different if we compare to OO languages. In answer to another SO question, someone explained it with a nice example: Method overloading?.

Basically, what we are doing is, we are creating just one function and a number of declarations so that TypeScript doesn't give compile errors. When this code is compiled to JavaScript, the concrete function alone will be visible. As a JavaScript function can be called by passing multiple arguments, it just works.

Jackson enum Serializing and DeSerializer

In my case, this is what resolved:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum PeriodEnum {

    DAILY(1),
    WEEKLY(2),
    ;

    private final int id;

    PeriodEnum(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return this.name();
    }

    @JsonCreator
    public static PeriodEnum fromJson(@JsonProperty("name") String name) {
        return valueOf(name);
    }
}

Serializes and deserializes the following json:

{
  "id": 2,
  "name": "WEEKLY"
}

I hope it helps!

How can I start and check my MySQL log?

Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html

Get a specific bit from byte

The method is to use another byte along with a bitwise AND to mask out the target bit.

I used convention from my classes here where "0" is the most significant bit and "7" is the least.

public static class ByteExtensions
{
    // Assume 0 is the MSB andd 7 is the LSB.
    public static bool GetBit(this byte byt, int index)
    {
        if (index < 0 || index > 7)
            throw new ArgumentOutOfRangeException();

        int shift = 7 - index;

        // Get a single bit in the proper position.
        byte bitMask = (byte)(1 << shift);

        // Mask out the appropriate bit.
        byte masked = (byte)(byt & bitMask);

        // If masked != 0, then the masked out bit is 1.
        // Otherwise, masked will be 0.
        return masked != 0;
    }
}

How to rotate portrait/landscape Android emulator?

Officially it's Ctrl+F11 & Ctrl+F12 or KEYPAD 7 & KEYPAD 9.

In practise it's a bit quirky.

  1. Specifically it's Left Ctrl+F11 and Left Ctrl+F12 to switch to previous orientation and next orientation respectively.

  2. You have to release Ctrl before you can rotate again.

  3. KEYPAD 7 and KEYPAD 9 only work with Num Lock OFF (so they're acting as Home & PageUp rather than 7 & 9).

  4. The only orientations are vertically upright and rotated one quarter-turn anti-clockwise.

Maybe a bit too much info for such a simple question, but it drove me half-mad finding this out.

Note: This was tested on Android SDK R16 and a very old keyboard, modern keyboards may behave differently.

Handling the window closing event with WPF / MVVM Light Toolkit

This code works just fine:

ViewModel.cs:

public ICommand WindowClosing
{
    get
    {
        return new RelayCommand<CancelEventArgs>(
            (args) =>{
                     });
    }
}

and in XAML:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
        <command:EventToCommand Command="{Binding WindowClosing}" PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers>

assuming that:

  • ViewModel is assigned to a DataContext of the main container.
  • xmlns:command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL5"
  • xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

Thanks to Vinod for the well presented answer.

I got the same error as Mick Byrne when I followed the steps above. Turning it back to All Unassigned sorted it but I had to tweak a few other things as well:

  • Add the user my site was running under to the users on the Security Tab in SMTP Virtual Server.
  • Changed the value in the mailSettings > network > host attribute in my web.config to the specific server IP (for example 192.168.100.120) as opposed to localhost (which was pointing at 127.0.0.1 in the hosts file).

Hope this saves someone a few mins of messing about.

HorizontalScrollView within ScrollView Touch Handling

It wasn't working well for me. I changed it and now it works smoothly. If anyone interested.

public class ScrollViewForNesting extends ScrollView {
    private final int DIRECTION_VERTICAL = 0;
    private final int DIRECTION_HORIZONTAL = 1;
    private final int DIRECTION_NO_VALUE = -1;

    private final int mTouchSlop;
    private int mGestureDirection;

    private float mDistanceX;
    private float mDistanceY;
    private float mLastX;
    private float mLastY;

    public ScrollViewForNesting(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);

        final ViewConfiguration configuration = ViewConfiguration.get(context);
        mTouchSlop = configuration.getScaledTouchSlop();
    }

    public ScrollViewForNesting(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ScrollViewForNesting(Context context) {
        this(context,null);
    }    


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {      
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDistanceY = mDistanceX = 0f;
                mLastX = ev.getX();
                mLastY = ev.getY();
                mGestureDirection = DIRECTION_NO_VALUE;
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                mDistanceX += Math.abs(curX - mLastX);
                mDistanceY += Math.abs(curY - mLastY);
                mLastX = curX;
                mLastY = curY;
                break;
        }

        return super.onInterceptTouchEvent(ev) && shouldIntercept();
    }


    private boolean shouldIntercept(){
        if((mDistanceY > mTouchSlop || mDistanceX > mTouchSlop) && mGestureDirection == DIRECTION_NO_VALUE){
            if(Math.abs(mDistanceY) > Math.abs(mDistanceX)){
                mGestureDirection = DIRECTION_VERTICAL;
            }
            else{
                mGestureDirection = DIRECTION_HORIZONTAL;
            }
        }

        if(mGestureDirection == DIRECTION_VERTICAL){
            return true;
        }
        else{
            return false;
        }
    }
}

MySQL server has gone away - in exactly 60 seconds

I have the same problem with mysqli. My solution is https://www.php.net/manual/en/mysqli.configuration.php

mysqli.reconnect = On

What is the behavior difference between return-path, reply-to and from?

I had to add a Return-Path header in emails send by a Redmine instance. I agree with greatwolf only the sender can determine a correct (non default) Return-Path. The case is the following : E-mails are send with the default email address : [email protected] But we want that the real user initiating the action receives the bounce emails, because he will be the one knowing how to fix wrong recipients emails (and not the application adminstrators that have other cats to whip :-) ). We use this and it works perfectly well with exim on the application server and zimbra as the final company mail server.

SMTP error 554

SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.

We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct reverse DNS lookup set up.

Python 3 Building an array of bytes

Here is a solution to getting an array (list) of bytes:

I found that you needed to convert the Int to a byte first, before passing it to the bytes():

bytes(int('0xA2', 16).to_bytes(1, "big"))

Then create a list from the bytes:

list(frame)

So your code should look like:

frame = b""
frame += bytes(int('0xA2', 16).to_bytes(1, "big"))
frame += bytes(int('0x01', 16).to_bytes(1, "big"))
frame += bytes(int('0x02', 16).to_bytes(1, "big"))
frame += bytes(int('0x03', 16).to_bytes(1, "big"))
frame += bytes(int('0x04', 16).to_bytes(1, "big"))
bytesList = list(frame)

The question was for an array (list) of bytes. You accepted an answer that doesn't tell how to get a list so I'm not sure if this is actually what you needed.

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

How to detect simple geometric shapes using OpenCV

You can also use template matching to detect shapes inside an image.

How to find if a file contains a given string using Windows command line

From other post:

    find /c "string" file >NUL
    if %errorlevel% equ 1 goto notfound
        echo found
    goto done
    :notfound
        echo notfound
    goto done
    :done

Use the /i switch when you want case insensitive checking:

    find /i /c "string" file >NUL

Or something like: if not found write to file.

    find /c "%%P" file.txt  || ( echo %%P >> newfile.txt )

Or something like: if found write to file.

    find /c "%%P" file.txt  && ( echo %%P >> newfile.txt )

Or something like:

    find /c "%%P" file.txt  && ( echo found ) || ( echo not found )

Set type for function parameters?

While you can't inform JavaScript the language about types, you can inform your IDE about them, so you get much more useful autocompletion.

Here are two ways to do that:

  1. Use JSDoc, a system for documenting JavaScript code in comments. In particular, you'll need the @param directive:

    /**
     * @param {Date} myDate - The date
     * @param {string} myString - The string
     */
    function myFunction(myDate, myString) {
      // ...
    }
    

    You can also use JSDoc to define custom types and specify those in @param directives, but note that JSDoc won't do any type checking; it's only a documentation tool. To check types defined in JSDoc, look into TypeScript, which can parse JSDoc tags.

  2. Use type hinting by specifying the type right before the parameter in a
    /* comment */:

    JavaScript type hinting in WebStorm

    This is a pretty widespread technique, used by ReactJS for instance. Very handy for parameters of callbacks passed to 3rd party libraries.

TypeScript

For actual type checking, the closest solution is to use TypeScript, a (mostly) superset of JavaScript. Here's TypeScript in 5 minutes.

How to get a list of MySQL views?

To complement about to get more info about a specific view

Even with the two valid answers

SHOW FULL TABLES IN your_db_name WHERE TABLE_TYPE LIKE 'VIEW';

SELECT TABLE_SCHEMA, TABLE_NAME 
FROM information_schema.TABLES 
WHERE TABLE_TYPE LIKE 'VIEW' AND TABLE_SCHEMA LIKE 'your_db_name';

You can apply the following (I think is better):

SELECT TABLE_SCHEMA, TABLE_NAME 
FROM information_schema.VIEWS 
WHERE TABLE_SCHEMA LIKE 'your_db_name';

is better work directly with information_schema.VIEWS (observe now is VIEWS and not TABLES anymore), thus you can retrieve more data, use DESC VIEWS for more details:

+----------------------+---------------------------------+------+-----+---------+-------+
| Field                | Type                            | Null | Key | Default | Extra |
+----------------------+---------------------------------+------+-----+---------+-------+
| TABLE_CATALOG        | varchar(64)                     | YES  |     | NULL    |       |
| TABLE_SCHEMA         | varchar(64)                     | YES  |     | NULL    |       |
| TABLE_NAME           | varchar(64)                     | YES  |     | NULL    |       |
| VIEW_DEFINITION      | longtext                        | YES  |     | NULL    |       |
| CHECK_OPTION         | enum('NONE','LOCAL','CASCADED') | YES  |     | NULL    |       |
| IS_UPDATABLE         | enum('NO','YES')                | YES  |     | NULL    |       |
| DEFINER              | varchar(93)                     | YES  |     | NULL    |       |
| SECURITY_TYPE        | varchar(7)                      | YES  |     | NULL    |       |
| CHARACTER_SET_CLIENT | varchar(64)                     | NO   |     | NULL    |       |
| COLLATION_CONNECTION | varchar(64)                     | NO   |     | NULL    |       |
+----------------------+---------------------------------+------+-----+---------+-------+

For example observe the VIEW_DEFINITION field, thus you can use in action:

SELECT TABLE_SCHEMA, TABLE_NAME, VIEW_DEFINITION 
FROM information_schema.VIEWS 
WHERE TABLE_SCHEMA LIKE 'your_db_name';

Of course you have more fields available for your consideration.

Rank function in MySQL

While the most upvoted answer ranks, it doesn't partition, You can do a self Join to get the whole thing partitioned also:

SELECT    a.first_name,
      a.age,
      a.gender,
        count(b.age)+1 as rank
FROM  person a left join person b on a.age>b.age and a.gender=b.gender 
group by  a.first_name,
      a.age,
      a.gender

Use Case

CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));

INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');

Answer:

Bill    32  M   4
Bob     25  M   2
Jack    30  M   3
Nick    22  M   1
Steve   36  M   5
Anne    25  F   3
Jane    20  F   2
Kathy   18  F   1

Linux find file names with given string recursively

use ack its simple. just type ack <string to be searched>

Create an empty object in JavaScript with {} or new Object()?

var objectA = {}

is a lot quicker and, in my experience, more commonly used, so it's probably best to adopt the 'standard' and save some typing.

Encode html entities in javascript

replaceHtmlEntities(text) {
  var tagsToReplace = {
    '&amp;': '&',
    '&lt;': '<',
    '&gt;': '>',
  };
  var newtext = text;
  for (var tag in tagsToReplace) {
    if (Reflect.apply({}.hasOwnProperty, this, [tagsToReplace, tag])) {
      var regex = new RegExp(tag, 'g');
      newtext = newtext.replace(regex, tagsToReplace[tag]);
    }
  }
  return newtext;
}

Unable to import a module that is definitely installed

In my case I had to also install the module(s) for the superuser, too.

sudo su
pip install <module>

Apparently the superuse cannot access the normal users files under certain circumstances.

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Also register your created service in the Manifest and uses-permission as

<application ...>
   <service android:name=".MyBroadcastReceiver">
        <intent-filter>
            <action android:name="com.example.MyBroadcastReciver"/>
        </intent-filter>
   </service>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

and then in braod cast Reciever call your service

public class MyBroadcastReceiver extends BroadcastReceiver 
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Intent myIntent = new Intent(context, MyService.class);
        context.startService(myIntent);
    }
}

python: after installing anaconda, how to import pandas

i had pandas installed ('conda list|grep pandas') and python could find it ('python; import imp; imp.find_module("pandas");'

However still was getting this error inside spyder. I had accidentally been using 'spyder3' instead of 'spyder' command, the former using a different python (3.5) rather than one conda is using (3.8). Running spyder and things worked as expected.

Can we instantiate an abstract class?

It is a well-established fact that abstract class can not be instantiated as everyone answered.

When the program defines anonymous class, the compiler actually creates a new class with different name (has the pattern EnclosedClassName$n where n is the anonymous class number)

So if you decompile this Java class you will find the code as below:

my.class

abstract class my { 
    public void mymethod() 
    { 
        System.out.print("Abstract"); 
    }
} 

poly$1.class (the generated class of the "anonymous class")

class poly$1 extends my 
{
} 

ploly.cass

public class poly extends my
{
    public static void main(String[] a)
    {
        my m = new poly.1(); // instance of poly.1 class NOT the abstract my class

        m.mymethod();
    }
}

Where does linux store my syslog?

I'm running Ubuntu under WSL(Windows Subsystem for Linux) and systemctl start rsyslog didn't work for me.

So what I did is this:

$ service rsyslog start

Now syslog file will appear at /var/log/

How can I order a List<string>?

ListaServizi.Sort();

Will do that for you. It's straightforward enough with a list of strings. You need to be a little cleverer if sorting objects.

get dictionary key by value

I have created a double-lookup class:

/// <summary>
/// dictionary with double key lookup
/// </summary>
/// <typeparam name="T1">primary key</typeparam>
/// <typeparam name="T2">secondary key</typeparam>
/// <typeparam name="TValue">value type</typeparam>
public class cDoubleKeyDictionary<T1, T2, TValue> {
    private struct Key2ValuePair {
        internal T2 key2;
        internal TValue value;
    }
    private Dictionary<T1, Key2ValuePair> d1 = new Dictionary<T1, Key2ValuePair>();
    private Dictionary<T2, T1> d2 = new Dictionary<T2, T1>();

    /// <summary>
    /// add item
    /// not exacly like add, mote like Dictionary[] = overwriting existing values
    /// </summary>
    /// <param name="key1"></param>
    /// <param name="key2"></param>
    public void Add(T1 key1, T2 key2, TValue value) {
        lock (d1) {
            d1[key1] = new Key2ValuePair {
                key2 = key2,
                value = value,
            };
            d2[key2] = key1;
        }
    }

    /// <summary>
    /// get key2 by key1
    /// </summary>
    /// <param name="key1"></param>
    /// <param name="key2"></param>
    /// <returns></returns>
    public bool TryGetValue(T1 key1, out TValue value) {
        if (d1.TryGetValue(key1, out Key2ValuePair kvp)) {
            value = kvp.value;
            return true;
        } else {
            value = default;
            return false;
        }
    }

    /// <summary>
    /// get key1 by key2
    /// </summary>
    /// <param name="key2"></param>
    /// <param name="key1"></param>
    /// <remarks>
    /// 2x O(1) operation
    /// </remarks>
    /// <returns></returns>
    public bool TryGetValue2(T2 key2, out TValue value) {
        if (d2.TryGetValue(key2, out T1 key1)) {
            return TryGetValue(key1, out value);
        } else {
            value = default;
            return false;
        }
    }

    /// <summary>
    /// get key1 by key2
    /// </summary>
    /// <param name="key2"></param>
    /// <param name="key1"></param>
    /// <remarks>
    /// 2x O(1) operation
    /// </remarks>
    /// <returns></returns>
    public bool TryGetKey1(T2 key2, out T1 key1) {
        return d2.TryGetValue(key2, out key1);
    }

    /// <summary>
    /// get key1 by key2
    /// </summary>
    /// <param name="key2"></param>
    /// <param name="key1"></param>
    /// <remarks>
    /// 2x O(1) operation
    /// </remarks>
    /// <returns></returns>
    public bool TryGetKey2(T1 key1, out T2 key2) {
        if (d1.TryGetValue(key1, out Key2ValuePair kvp1)) {
            key2 = kvp1.key2;
            return true;
        } else {
            key2 = default;
            return false;
        }
    }

    /// <summary>
    /// remove item by key 1
    /// </summary>
    /// <param name="key1"></param>
    public void Remove(T1 key1) {
        lock (d1) {
            if (d1.TryGetValue(key1, out Key2ValuePair kvp)) {
                d1.Remove(key1);
                d2.Remove(kvp.key2);
            }
        }
    }

    /// <summary>
    /// remove item by key 2
    /// </summary>
    /// <param name="key2"></param>
    public void Remove2(T2 key2) {
        lock (d1) {
            if (d2.TryGetValue(key2, out T1 key1)) {
                d1.Remove(key1);
                d2.Remove(key2);
            }
        }
    }

    /// <summary>
    /// clear all items
    /// </summary>
    public void Clear() {
        lock (d1) {
            d1.Clear();
            d2.Clear();
        }
    }

    /// <summary>
    /// enumerator on key1, so we can replace Dictionary by cDoubleKeyDictionary
    /// </summary>
    /// <param name="key1"></param>
    /// <returns></returns>
    public TValue this[T1 key1] {
        get => d1[key1].value;
    }

    /// <summary>
    /// enumerator on key1, so we can replace Dictionary by cDoubleKeyDictionary
    /// </summary>
    /// <param name="key1"></param>
    /// <returns></returns>
    public TValue this[T1 key1, T2 key2] {
        set {
            lock (d1) {
                d1[key1] = new Key2ValuePair {
                    key2 = key2,
                    value = value,
                };
                d2[key2] = key1;
            }
        }
    }

Can you blur the content beneath/behind a div?

If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before

//HTML

<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
    <div class="morph-button morph-button-overlay morph-button-fixed">
        <button id="user-interface" type="button">MORE INFO</button>
        <!--a id="user-interface" href="javascript:void(0)">popup</a-->
        <div class="morph-content">
            <div>
                <div class="content-style-overlay">
                    <span class="icon icon-close">Close the overlay</span>
                    <h2>About Parsley</h2>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                </div>
            </div>
        </div>
    </div>
</div>

//CSS

/* Blur - doesn't work on IE */

.blur-on, .blur-element {
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
    filter: blur(10px);

    -webkit-transition: all 5s linear;
    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}
.blur-off {
    -webkit-filter: blur(0px) !important;
    -moz-filter   : blur(0px) !important;
    -o-filter     : blur(0px) !important;
    -ms-filter    : blur(0px) !important;
    filter        : blur(0px) !important;
}
.blur-bgimage:before {
    content: "";
    position: absolute;
    height: 20%; width: 20%;
    background-size: cover;
    background: inherit;
    z-index: -1;

    transform: scale(5);
    transform-origin: top left;
    filter: blur(2px);       
    -moz-transform: scale(5);
    -moz-transform-origin: top left;
    -moz-filter: blur(2px);       
    -webkit-transform: scale(5);
    -webkit-transform-origin: top left;
    -webkit-filter: blur(2px);
    -o-transform: scale(5);
    -o-transform-origin: top left;
    -o-filter: blur(2px);       

    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}


//Javascript

function blurBehindPopup() {
    if(blurredElements.length == 0) {
        for(var i=0; i < document.body.children.length; i++) {
            var element = document.body.children[i];
            if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
                classie.addClass( element, 'blur-element' );
                blurredElements.push(element);
            }
        }
    } else {
        for(var i=0; i < blurredElements.length; i++) {
            classie.addClass( blurredElements[i], 'blur-element' );
        }
    }
}
function unblurBehindPopup() {
    for(var i=0; i < blurredElements.length; i++) {
        classie.removeClass( blurredElements[i], 'blur-element' );
    }
}

Full Working Example Link

How to assign Php variable value to Javascript variable?

Essentially:

<?php
//somewhere set a value
$var = "a value";
?>

<script>
// then echo it into the js/html stream
// and assign to a js variable
spge = '<?php echo $var ;?>';

// then
alert(spge);

</script>

Convert Month Number to Month Name Function in SQL

You can create a function like this to generate the Month and do SELECT dbo.fn_GetMonthFromDate(date_column) as Month FROM table_name


/****** Object:  UserDefinedFunction [dbo].[fn_GetMonthFromDate]    Script Date: 11/16/2018 10:26:33 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fn_GetMonthFromDate] 
(@date datetime)
RETURNS varchar(50)
AS
BEGIN
    DECLARE @monthPart int

SET @monthPart = MONTH(@date) IF @monthPart = 1 BEGIN RETURN 'January' END ELSE IF @monthPart = 2 BEGIN RETURN 'February' END ELSE IF @monthPart = 3 BEGIN RETURN 'March' END ELSE IF @monthPart = 4 BEGIN RETURN 'April' END ELSE IF @monthPart = 5 BEGIN RETURN 'May' END ELSE IF @monthPart = 6 BEGIN RETURN 'June' END ELSE IF @monthPart = 7 BEGIN RETURN 'July' END ELSE IF @monthPart = 8 BEGIN RETURN 'August' END ELSE IF @monthPart = 9 BEGIN RETURN 'September' END ELSE IF @monthPart = 10 BEGIN RETURN 'October' END ELSE IF @monthPart = 11 BEGIN RETURN 'November' END ELSE IF @monthPart = 12 BEGIN RETURN 'December' END RETURN NULL END

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

Return HTML content as a string, given URL. Javascript Function

In some websites, XMLHttpRequest may send you something like <script src="#"></srcipt>. In that case, try using a HTML document like the script under:

<html>
  <body>
    <iframe src="website.com"></iframe>
    <script src="your_JS"></script>
  </body>
</html>

Now you can use JS to get some text out of the HTML, such as getElementbyId.

But this may not work for some websites with cross-domain blocking.

How to add a reference programmatically

Ommit

There are two ways to add references via VBA to your projects

1) Using GUID

2) Directly referencing the dll.

Let me cover both.

But first these are 3 things you need to take care of

a) Macros should be enabled

b) In Security settings, ensure that "Trust Access To Visual Basic Project" is checked

enter image description here

c) You have manually set a reference to `Microsoft Visual Basic for Applications Extensibility" object

enter image description here

Way 1 (Using GUID)

I usually avoid this way as I have to search for the GUID in the registry... which I hate LOL. More on GUID here.

Topic: Add a VBA Reference Library via code

Link: http://www.vbaexpress.com/kb/getarticle.php?kb_id=267

'Credits: Ken Puls
Sub AddReference()
     'Macro purpose:  To add a reference to the project using the GUID for the
     'reference library

    Dim strGUID As String, theRef As Variant, i As Long

     'Update the GUID you need below.
    strGUID = "{00020905-0000-0000-C000-000000000046}"

     'Set to continue in case of error
    On Error Resume Next

     'Remove any missing references
    For i = ThisWorkbook.VBProject.References.Count To 1 Step -1
        Set theRef = ThisWorkbook.VBProject.References.Item(i)
        If theRef.isbroken = True Then
            ThisWorkbook.VBProject.References.Remove theRef
        End If
    Next i

     'Clear any errors so that error trapping for GUID additions can be evaluated
    Err.Clear

     'Add the reference
    ThisWorkbook.VBProject.References.AddFromGuid _
    GUID:=strGUID, Major:=1, Minor:=0

     'If an error was encountered, inform the user
    Select Case Err.Number
    Case Is = 32813
         'Reference already in use.  No action necessary
    Case Is = vbNullString
         'Reference added without issue
    Case Else
         'An unknown error was encountered, so alert the user
        MsgBox "A problem was encountered trying to" & vbNewLine _
        & "add or remove a reference in this file" & vbNewLine & "Please check the " _
        & "references in your VBA project!", vbCritical + vbOKOnly, "Error!"
    End Select
    On Error GoTo 0
End Sub

Way 2 (Directly referencing the dll)

This code adds a reference to Microsoft VBScript Regular Expressions 5.5

Option Explicit

Sub AddReference()
    Dim VBAEditor As VBIDE.VBE
    Dim vbProj As VBIDE.VBProject
    Dim chkRef As VBIDE.Reference
    Dim BoolExists As Boolean

    Set VBAEditor = Application.VBE
    Set vbProj = ActiveWorkbook.VBProject

    '~~> Check if "Microsoft VBScript Regular Expressions 5.5" is already added
    For Each chkRef In vbProj.References
        If chkRef.Name = "VBScript_RegExp_55" Then
            BoolExists = True
            GoTo CleanUp
        End If
    Next

    vbProj.References.AddFromFile "C:\WINDOWS\system32\vbscript.dll\3"

CleanUp:
    If BoolExists = True Then
        MsgBox "Reference already exists"
    Else
        MsgBox "Reference Added Successfully"
    End If

    Set vbProj = Nothing
    Set VBAEditor = Nothing
End Sub

Note: I have not added Error Handling. It is recommended that in your actual code, do use it :)

EDIT Beaten by mischab1 :)

Authenticated HTTP proxy with Java

For Java 1.8 and higher you must set

-Djdk.http.auth.tunneling.disabledSchemes=

to make proxies with Basic Authorization working with https along with Authenticator as mentioned in accepted answer

iOS: Convert UTC NSDate to local Timezone

EDIT When i wrote this I didn't know I should use a dateformatter which is probably a better approach, so check out slf's answer too.

I have a webservice that returns dates in UTC. I use toLocalTime to convert it to local time and toGlobalTime to convert back if needed.

This is where I got my answer from:

https://agilewarrior.wordpress.com/2012/06/27/how-to-convert-nsdate-to-different-time-zones/

@implementation NSDate(Utils)

-(NSDate *) toLocalTime
{
  NSTimeZone *tz = [NSTimeZone defaultTimeZone];
  NSInteger seconds = [tz secondsFromGMTForDate: self];
  return [NSDate dateWithTimeInterval: seconds sinceDate: self];
}

-(NSDate *) toGlobalTime
{
  NSTimeZone *tz = [NSTimeZone defaultTimeZone];
  NSInteger seconds = -[tz secondsFromGMTForDate: self];
  return [NSDate dateWithTimeInterval: seconds sinceDate: self];
}

@end

What is Dispatcher Servlet in Spring?

You can say Dispatcher Servlet acts as an entry and exit point for any request. Whenever a request comes it first goes to the Dispatcher Servlet(DS) where the DS then tries to identify its handler method ( the methods you define in the controller to handle the requests ), once the handler mapper (The DS asks the handler mapper) returns the controller the dispatcher servlet knows the controller which can handle this request and can now go to this controller to further complete the processing of the request. Now the controller can respond with an appropriate response and then the DS goes to the view resolver to identify where the view is located and once the view resolver tells the DS it then grabs that view and returns it back to you as the final response. I am adding an image which I took from YouTube from the channel Java Guides.

Dispatcher Servlet in Action

Make 2 functions run at the same time

The answer about threading is good, but you need to be a bit more specific about what you want to do.

If you have two functions that both use a lot of CPU, threading (in CPython) will probably get you nowhere. Then you might want to have a look at the multiprocessing module or possibly you might want to use jython/IronPython.

If CPU-bound performance is the reason, you could even implement things in (non-threaded) C and get a much bigger speedup than doing two parallel things in python.

Without more information, it isn't easy to come up with a good answer.

Symfony - generate url with parameter in controller

make sure your controller extends Symfony\Bundle\FrameworkBundle\Controller\Controller;

you should also check app/console debug:router in terminal to see what name symfony has named the route

in my case it used a minus instead of an underscore

i.e blog-show

$uri = $this->generateUrl('blog-show', ['slug' => 'my-blog-post']);

Fully backup a git repo?

cd /path/to/backupdir/
git clone /path/to/repo
cd /path/to/repo
git remote add backup /path/to/backupdir
git push --set-upstream backup master

this creates a backup and makes the setup, so that you can do a git push to update your backup, what is probably what you want to do. Just make sure, that /path/to/backupdir and /path/to/repo are at least different hard drives, otherwise it doesn't make that much sense to do that.

What are the First and Second Level caches in (N)Hibernate?

First Level Cache

Session object holds the first level cache data. It is enabled by default. The first level cache data will not be available to entire application. An application can use many session object.

Second Level Cache

SessionFactory object holds the second level cache data. The data stored in the second level cache will be available to entire application. But we need to enable it explicitly.

Difference of two date time in sql server

SELECT DATEDIFF (MyUnits, '2010-01-22 15:29:55.090', '2010-01-22 15:30:09.153')

Substitute "MyUnits" based on DATEDIFF on MSDN

Method List in Visual Studio Code

Update: As stated in the comments by @jeff-xiao this extension is Deprecated and it's now a built in feature of Visual Studio code. It should be available at the bottom of file explorer as "Outline" view.

Previous text: There is now an Extension that supports this. Code Outline creates a panel in the "Explorer" section and for JavaScript, will list variables and functions in a file. I've been using this for a while now and it scratches the itch I had. Other commenters have mentioned it supports Python and PHP well.

It still seems to be in development but I haven't had any issues. Development version available on GitHub. If you're the author reading this - thanks!

This is how it looks:
Code Outline plugin for VSCode

If Code Outline is not visible, you can show it by: enter image description here

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

One of the possible reasons is when you load jQuery TWICE ,like:

<script src='..../jquery.js'></script>
....
....
....
....
....
<script src='......./jquery.js'></script>

So, check your source code and remove duplicate jQuery load.

Cannot connect to Database server (mysql workbench)

To be up to date for upper versions and later visitors :

Currently I'm working on a win7 64bit having different tools on it including python 2.7.4 as a prerequisite for google android ...

When I upgraded from WB 6.0.8-win32 to upper versions to have 64bit performance I had some problems for example on 6.3.5-winx64 I had a bug in the details view of tables (disordered view) caused me to downgrade to 6.2.5-winx64.

As a GUI user, easy forward/backward engineering and db server relative items were working well but when we try to Database>Connect to Database we will have Not connected and will have python error if we try to execute a query however the DB server service is absolutely ran and is working well and this problem is not from the server and is from workbench. To resolve it we must use Query>Reconnect to Server to choose the DB connection explicitly and then almost everything looks good (this may be due to my multiple db connections and I couldn't find some solution to define the default db connection in workbench).

As a note : because I'm using latest Xampp version (even in linux addictively :) ), recently Xampp uses mariadb 10 instead of mysql 5.x causes the mysql file version to be 10 may cause some problems such as forward engineering of procedures which can be resolved via mysql_upgrade.exe but still when we try to check a db connection wb will inform about the wrong version however it is not critical and works well.

Conclusion : Thus sometimes db connection problems in workbench may be due to itself and not server (if you don't have other db connection relative problems).

Adding iOS UITableView HeaderView (not section header)

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,30)];
    headerView.backgroundColor=[[UIColor redColor]colorWithAlphaComponent:0.5f];
    headerView.layer.borderColor=[UIColor blackColor].CGColor;
    headerView.layer.borderWidth=1.0f;

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5,100,20)];

    headerLabel.textAlignment = NSTextAlignmentRight;
    headerLabel.text = @"LeadCode ";
    //headerLabel.textColor=[UIColor whiteColor];
    headerLabel.backgroundColor = [UIColor clearColor];


    [headerView addSubview:headerLabel];

    UILabel *headerLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, headerView.frame.size.width-120.0, headerView.frame.size.height)];

    headerLabel1.textAlignment = NSTextAlignmentRight;
    headerLabel1.text = @"LeadName";
    headerLabel.textColor=[UIColor whiteColor];
    headerLabel1.backgroundColor = [UIColor clearColor];

    [headerView addSubview:headerLabel1];

    return headerView;

}

How do I combine the first character of a cell with another cell in Excel?

Not sure why no one is using semicolons. This is how it works for me:

=CONCATENATE(LEFT(A1;1); B1)

Solutions with comma produce an error in Excel.

Android Studio - Failed to apply plugin [id 'com.android.application']

Delete gradle cache files. It can be in path like C:\Users\username\.gradle\caches for Windows users. For UNIX based operating systems it will be ~/.gradle/caches.

Fixed Table Cell Width

Now in HTML5/CSS3 we have better solution for the problem. In my opinion this purely CSS solution is recommended:

_x000D_
_x000D_
table.fixed {table-layout:fixed; width:90px;}/*Setting the table width is important!*/_x000D_
table.fixed td {overflow:hidden;}/*Hide text outside the cell.*/_x000D_
table.fixed td:nth-of-type(1) {width:20px;}/*Setting the width of column 1.*/_x000D_
table.fixed td:nth-of-type(2) {width:30px;}/*Setting the width of column 2.*/_x000D_
table.fixed td:nth-of-type(3) {width:40px;}/*Setting the width of column 3.*/
_x000D_
<table class="fixed">_x000D_
    <tr>_x000D_
        <td>Veryverylongtext</td>_x000D_
        <td>Actuallythistextismuchlongeeeeeer</td>_x000D_
        <td>We should use spaces tooooooooooooo</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

You need to set the table's width even in haunter's solution. Otherwise it doesn't work.
Also a new CSS3 feature that vsync suggested is: word-break:break-all;. This will break the words without spaces in them to multiple lines too. Just modify the code like this:

table.fixed { table-layout:fixed; width:90px; word-break:break-all;}

Final result

Rendered table

CORS: credentials mode is 'include'

If you are using CORS middleware and you want to send withCredentials boolean true, you can configure CORS like this:

_x000D_
_x000D_
var cors = require('cors');    _x000D_
app.use(cors({credentials: true, origin: 'http://localhost:5000'}));
_x000D_
_x000D_
_x000D_

`

How do I return a proper success/error message for JQuery .ajax() using PHP?

Server side:

if (mysql_query($query)) {
    // ...
}
else {
    ajaxError(); 
}

Client side:

error: function() {
    alert("There was an error. Try again please!");
},
success: function(){
    alert("Thank you for subscribing!");
}

NOT IN vs NOT EXISTS

Actually, I believe this would be the fastest:

SELECT ProductID, ProductName 
    FROM Northwind..Products p  
          outer join Northwind..[Order Details] od on p.ProductId = od.ProductId)
WHERE od.ProductId is null

PHP Array to CSV

This is a simple solution that exports an array to csv string:

function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
    $f = fopen('php://memory', 'r+');
    foreach ($data as $item) {
        fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
    }
    rewind($f);
    return stream_get_contents($f);
}

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

Yeah, I agree, top answers are really pro solutions,

here is one for intermediates,

Solutions Explorer

Right click on project select Unload project

Again Right click and select Edit ProjectName.csproj

remove these 3 lines

<DevelopmentServerPort>0</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:62940/</IISUrl>

Save and reload the project and you are good to go

How do I delete virtual interface in Linux?

Have you tried:

ifconfig 10:35978f0 down

As the physical interface is 10 and the virtual aspect is after the colon :.

See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/

Convert string in base64 to image and save on filesystem in Python

You could probably use the PyPNG package's png.Reader object to do this - decode the base64 string into a regular string (via the base64 standard library), and pass it to the constructor.

Can you have multiple $(document).ready(function(){ ... }); sections?

You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal. See the below:

http://www.learningjquery.com/2006/09/multiple-document-ready

Try this out:

$(document).ready(function() {
    alert('Hello Tom!');
});

$(document).ready(function() {
    alert('Hello Jeff!');
});

$(document).ready(function() {
    alert('Hello Dexter!');
});

You'll find that it's equivalent to this, note the order of execution:

$(document).ready(function() {
    alert('Hello Tom!');
    alert('Hello Jeff!');
    alert('Hello Dexter!');
});

It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block, I just ran this test:

$(document).ready(function() {
    alert('hello1');
    function saySomething() {
        alert('something');
    }
    saySomething();

});
$(document).ready(function() {
    alert('hello2');
    saySomething();
}); 

output was:

hello1
something
hello2

How to trigger the onclick event of a marker on a Google Maps V3?

I've found out the solution! Thanks to Firebug ;)

//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event

//V2 version is:
GEvent.trigger(markers[i], 'click');

//V3 version is:
google.maps.event.trigger(markers[i], 'click');

Windows Explorer "Command Prompt Here"

Tried the answer given by Tough Coder in Windows 7 and it works!

Create a shortcut to cmd.exe in %HOMEDRIVE%%HOMEPATH%\Links, open its file properties and change the field 'Start at' to %1 ('Iniciar en' translated from spanish).

Now drag folders to it and you'll see the magic. It works too in all standard Open File dialogs. wow!

ps: those 'strange' tabs above in my picture are because I use Clover. I recommend it!

enter image description here

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

Any approach should give you roughly same number. It is always a good idea to allocate the heap using -X..m -X..x for all generations. You can then guarantee and also do ps to see what parameters were passed and hence being used.

For actual memory usages, you can roughly compare VIRT (allocated and shared) and RES (actual used) compare against the jstat values as well:

For Java 8, see jstat for these values actually mean. Assuming you run a simple class with no mmap or file processing.

$ jstat -gccapacity 32277
 NGCMN    NGCMX     NGC     S0C   S1C       EC      OGCMN      OGCMX       OGC         OC       MCMN     MCMX      MC     CCSMN    CCSMX     CCSC    YGC    FGC
215040.0 3433472.0  73728.0  512.0  512.0  67072.0   430080.0  6867968.0   392704.0   392704.0      0.0 1083392.0  39680.0      0.0 1048576.0   4864.0   7225     2
$ jstat -gcutil 32277
  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT
  6.25   0.00   7.96  18.21  98.01  95.29   7228   30.859     2    0.173   31.032

Max:

     NGCMX + S0C + S1C + EC    + OGCMX   + MCMX    + CCSMX
   3433472 + 512 + 512 + 67072 + 6867968 + 1083392 + 1048576 = 12 GB

(roughly close and below to VIRT memory)

Max(Min, Used):

215040 + 512 + 512 + 67072 + 430080  + 39680    +  4864  = ~ 1GB

(roughly close to RES memory)

"Don't quote me on this" but VIRT mem is roughly close to or more than Max memory allocated but as long as memory being used is free/available in physical memory, JVM does not throw memory exception. In fact, max memory is not even checked against physical memory on JVM startup even with swap off on OS. A better explanation of what Virtual memory really used by a Java process is discussed here.

Get user info via Google API

There are 3 steps that needs to be run.

  1. Register your app's client id from Google API console
  2. Ask your end user to give consent using this api https://developers.google.com/identity/protocols/OpenIDConnect#sendauthrequest
  3. Use google's oauth2 api as described at https://any-api.com/googleapis_com/oauth2/docs/userinfo/oauth2_userinfo_v2_me_get using the token obtained in step 2. (Though still I could not find how to fill "fields" parameter properly).

It is very interesting that this simplest usage is not clearly described anywhere. And i believe there is a danger, you should pay attention to the verified_emailparameter coming in the response. Because if I am not wrong it may yield fake emails to register your application. (This is just my interpretation, has a fair chance that I may be wrong!)

I find facebook's OAuth mechanics much much clearly described.

What is Scala's yield?

val aList = List( 1,2,3,4,5 )

val res3 = for ( al <- aList if al > 3 ) yield al + 1
val res4 = aList.filter(_ > 3).map(_ + 1)

println( res3 )
println( res4 )

These two pieces of code are equivalent.

val res3 = for (al <- aList) yield al + 1 > 3
val res4 = aList.map( _+ 1 > 3 )

println( res3 ) 
println( res4 )

These two pieces of code are also equivalent.

Map is as flexible as yield and vice-versa.

How to reset index in a pandas dataframe?

DataFrame.reset_index is what you're looking for. If you don't want it saved as a column, then do:

df = df.reset_index(drop=True)

If you don't want to reassign:

df.reset_index(drop=True, inplace=True)

Clearing the terminal screen?

There is no way to clear the screen but, a really easy way to fake it can be printing as much Serial.println(); as you need to keep all the old data out of the screen.

ExpressJS - throw er Unhandled error event

This is because the port you are using to run the script is already in use. You have to stop all other nodes which are using that post. for that, you can check all node by

ps -e

OR for node process only use ps -ef | grep node This will give you the list of all node process with id

to Kill all node process

sudo killall -9 node

Or for the specific id sudo kill -9 id

DLL load failed error when importing cv2

Recently I have faced the similar issue in Azure Windows Server 2012 r2 . Tried all option with and without Anaconda but none of them helped. After lot of findings I found that mfplat.dll was missing which is related to Window Media Service.

Hence you have to manually install the features so that you can get dll related to window media service.

1.Turn windows features on or off

2.Skip the roles screen and directly go to Feature screen

3.Select "Desktop Experience" under "User Interfaces and Infrastructure"

After this all required dll of media services for opencv would be available.

So if you are planning to run your code in cloud(Window Server) then please dont forget to select Desktop Experience feature.

'tuple' object does not support item assignment

You have misspelt the second pixels as pixel. The following works:

pixels = [1,2,3]
pixels[0] = 5

It appears that due to the typo you were trying to accidentally modify some tuple called pixel, and in Python tuples are immutable. Hence the confusing error message.

Colspan all columns

According to the specification colspan="0" should result in a table width td.

However, this is only true if your table has a width! A table may contain rows of different widths. So, the only case that the renderer knows the width of the table if you define a colgroup! Otherwise, result of colspan="0" is indeterminable...

http://www.w3.org/TR/REC-html40/struct/tables.html#adef-colspan

I cannot test it on older browsers, but this is part of specification since 4.0...

Displaying a Table in Django from Database

$ pip install django-tables2

settings.py

INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'

models.py

class hotel(models.Model):
     name = models.CharField(max_length=20)

views.py

from django.shortcuts import render

def people(request):
    istekler = hotel.objects.all()
    return render(request, 'list.html', locals())

list.html

{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
    </head>
    <body>
        {% render_table istekler %}
    </body>
</html>

How to have Ellipsis effect on Text

<Text ellipsizeMode='tail' numberOfLines={2} style={{width:100}}>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at cursus 
</Text>

Result: Lorem ipsum...

Allow only numbers and dot in script

This works best for me.

I also apply a currency formatter on blur where the decimal part is rounded at 2 digits just in case after validating with parseFloat.

The functions that get and set the cursor position are from Vishal Monpara's blog. I also do some nice stuff on focus with those functions. You can easily remove 2 blocks of code where 2 decimals are forced if you want and get rid of the set/get caret functions.

<html>
<body>
<input type="text" size="30" maxlength="30" onkeypress="return numericValidation(this,event);" />
<script language="JavaScript">
    function numericValidation(obj,evt) {
        var e = event || evt; // for trans-browser compatibility

        var charCode = e.which || e.keyCode;        

        if (charCode == 46) { //one dot
            if (obj.value.indexOf(".") > -1)
                return false;
            else {
                //---if the dot is positioned in the middle give the user a surprise, remember: just 2 decimals allowed
                var idx = doGetCaretPosition(obj);
                var part1 = obj.value.substr(0,idx),
                    part2 = obj.value.substring(idx);

                if (part2.length > 2) {
                    obj.value = part1 + "." + part2.substr(0,2);
                    setCaretPosition(obj, idx + 1);
                    return false;
                }//---

                //allow one dot if not cheating
                return true;
            }
        }
        else if (charCode > 31 && (charCode < 48 || charCode > 57)) { //just numbers
            return false;
        }

        //---just 2 decimals stubborn!
        var arr = obj.value.split(".") , pos = doGetCaretPosition(obj);

        if (arr.length == 2 && pos > arr[0].length && arr[1].length == 2)                               
            return false;
        //---

        //ok it's a number
        return true;
    }

    function doGetCaretPosition (ctrl) {
        var CaretPos = 0;   // IE Support
        if (document.selection) {
        ctrl.focus ();
            var Sel = document.selection.createRange ();
            Sel.moveStart ('character', -ctrl.value.length);
            CaretPos = Sel.text.length;
        }
        // Firefox support
        else if (ctrl.selectionStart || ctrl.selectionStart == '0')
            CaretPos = ctrl.selectionStart;
        return (CaretPos);
    }

    function setCaretPosition(ctrl, pos){
        if(ctrl.setSelectionRange)
        {
            ctrl.focus();
            ctrl.setSelectionRange(pos,pos);
        }
        else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }
</script>
</body>
</html>

How can I add a help method to a shell script?

here's an example for bash:

usage="$(basename "$0") [-h] [-s n] -- program to calculate the answer to life, the universe and everything

where:
    -h  show this help text
    -s  set the seed value (default: 42)"

seed=42
while getopts ':hs:' option; do
  case "$option" in
    h) echo "$usage"
       exit
       ;;
    s) seed=$OPTARG
       ;;
    :) printf "missing argument for -%s\n" "$OPTARG" >&2
       echo "$usage" >&2
       exit 1
       ;;
   \?) printf "illegal option: -%s\n" "$OPTARG" >&2
       echo "$usage" >&2
       exit 1
       ;;
  esac
done
shift $((OPTIND - 1))

To use this inside a function:

  • use "$FUNCNAME" instead of $(basename "$0")
  • add local OPTIND OPTARG before calling getopts

Convert MFC CString to integer

The simplest approach is to use the atoi() function found in stdlib.h:

CString s = "123";
int x = atoi( s );

However, this does not deal well with the case where the string does not contain a valid integer, in which case you should investigate the strtol() function:

CString s = "12zzz";    // bad integer
char * p;
int x = strtol ( s, & p, 10 );
if ( * p != 0 ) {
   // s does not contain an integer
}

flutter remove back button on appbar

// if you want to hide back button use below code

class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text('Remove Back Button'),
    
    //hide back button
    automaticallyImplyLeading: false,
   ),
  body: Center(
    child: Container(),
  ),
);
}
}

// if you want to hide back button and stop the pop action use below code

class SecondScreen extends StatelessWidget {

@override
Widget build(BuildContext context) {
 return new WillPopScope(

  onWillPop: () async => false,
  child: Scaffold(
    appBar: AppBar(
      title: Text("Second Screen"),
      //For hide back button
      automaticallyImplyLeading: false,
    ),
    body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Back'),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ],
        )
    ),
  ),
);
 }


[

How to increase heap size of an android application?

Is there a way to increase this size of memory an application can use?

Applications running on API Level 11+ can have android:largeHeap="true" on the <application> element in the manifest to request a larger-than-normal heap size, and getLargeMemoryClass() on ActivityManager will tell you how big that heap is. However:

  1. This only works on API Level 11+ (i.e., Honeycomb and beyond)

  2. There is no guarantee how large the large heap will be

  3. The user will perceive your large-heap request, because it will force their other apps out of RAM terminate other apps' processes to free up system RAM for use by your large heap

  4. Because of #3, and the fact that I expect that android:largeHeap will be abused, support for this may be abandoned in the future, or the user may be warned about this at install time (e.g., you will need to request a special permission for it)

  5. Presently, this feature is lightly documented

How to copy a file from remote server to local machine?

When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:

scp -P[portnumber] myfile_at_remote_host [user]@[your_ip_address]:/your/path/

Example:

scp -P22 table [email protected]:/home/me/Desktop/

On the other hand, if you are at your are actually on your machine you may use something like this:

scp -P[portnumber] [remote_login]@[remote's_ip_address]:/remote/path/myfile_at_remote_host /your/path/

Example:

scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/

How to disable textbox from editing?

        textBox1.Enabled = false;

"false" property will make the text box disable. and "true" will make it in regular form. Thanks.

MySQL server has gone away - in exactly 60 seconds

This is something I do, (but usually with the MySQLi class).

$link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass");
mysql_select_db($MYSQL_db, $link);

// RUN REALLY LONG QUERY HERE

// Reconnect if needed

if( !mysql_ping($link) ) $link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass", true);

// RUN ANOTHER QUERY

How to check if a string contains a substring in Bash

One is:

[ $(expr $mystring : ".*${search}.*") -ne 0 ] && echo 'yes' ||  echo 'no'

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

While installing the node modules for mocha I had tried the below commands

  • npm install
  • npm install mocha
  • npm install --save-dev mocha
  • npm install mocha -g # to install it globally also

and on running or executing the mocha test I was trying

  • mocha test
  • npm run test
  • mocha test test\index.test.js
  • npm test

but I was getting the below error as:

'Mocha' is not recognized as internal or external command

So , after trying everything it came out to be just set the path to environment variables under the System Variables as:

C:\Program Files\nodejs\

and it worked :)

How can I define fieldset border color?

It does appear red on Firefox and IE 8. But perhaps you need to change the border-style too.

_x000D_
_x000D_
.field_set{_x000D_
  border-color: #F00;_x000D_
  border-style: solid;_x000D_
}
_x000D_
<fieldset class="field_set">_x000D_
  <legend>box</legend>_x000D_
  <table width="100%" border="0" cellspacing="0" cellpadding="0">_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

alt text

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

To monitor the backup or restore progress completely separate from the session where the backup or restore was initiated. No third party tools required. Tested on Microsoft SQL Server 2012.

SELECT percent_complete, *
FROM sys.dm_exec_requests
WHERE command In ( 'RESTORE DATABASE', 'BACKUP DATABASE' )

Get parent directory of running script

If your script is located in /var/www/dir/index.php then the following would return:

dirname(__FILE__); // /var/www/dir

or

dirname( dirname(__FILE__) ); // /var/www

Edit

This is a technique used in many frameworks to determine relative paths from the app_root.

File structure:

 /var/
      www/
          index.php
          subdir/
                 library.php

index.php is my dispatcher/boostrap file that all requests are routed to:

define(ROOT_PATH, dirname(__FILE__) ); // /var/www

library.php is some file located an extra directory down and I need to determine the path relative to the app root (/var/www/).

$path_current = dirname( __FILE__ ); // /var/www/subdir
$path_relative = str_replace(ROOT_PATH, '', $path_current); // /subdir

There's probably a better way to calculate the relative path then str_replace() but you get the idea.

Remove 'standalone="yes"' from generated XML

in JAXB that is part of JDK1.6

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

ActiveMQ connection refused

I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:

Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();

  connectionFactory.setBrokerURL("tcp://hostname:61616");
  connectionFactory.setUserName("admin");
  connectionFactory.setPassword("admin");

How to change a particular element of a C++ STL vector

Even though @JamesMcNellis answer is a valid one I would like to explain something about error handling and also the fact that there is another way of doing what you want.

You have four ways of accessing a specific item in a vector:

  • Using the [] operator
  • Using the member function at(...)
  • Using an iterator in combination with a given offset
  • Using std::for_each from the algorithm header of the standard C++ library. This is another way which I can recommend (it uses internally an iterator). You can read more about it for example here.

In the following examples I will be using the following vector as a lab rat and explaining the first three methods:

static const int arr[] = {1, 2, 3, 4};
std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0]));

This creates a vector as seen below:

1 2 3 4

First let's look at the [] way of doing things. It works in pretty much the same way as you expect when working with a normal array. You give an index and possibly you access the item you want. I say possibly because the [] operator doesn't check whether the vector actually has that many items. This leads to a silent invalid memory access. Example:

v[10] = 9;

This may or may not lead to an instant crash. Worst case is of course is if it doesn't and you actually get what seems to be a valid value. Similar to arrays this may lead to wasted time in trying to find the reason why for example 1000 lines of code later you get a value of 100 instead of 234, which is somewhat connected to that very location where you retrieve an item from you vector.

A much better way is to use at(...). This will automatically check for out of bounds behaviour and break throwing an std::out_of_range. So in the case when we have

v.at(10) = 9;

We will get:

terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 4)

The third way is similar to the [] operator in the sense you can screw things up. A vector just like an array is a sequence of continuous memory blocks containing data of the same type. This means that you can use your starting address by assigning it to an iterator and then just add an offset to this iterator. The offset simply stands for how many items after the first item you want to traverse:

std::vector<int>::iterator it = v.begin(); // First element of your vector
*(it+0) = 9;  // offest = 0 basically means accessing v.begin()
// Now we have 9 2 3 4 instead of 1 2 3 4
*(it+1) = -1; // offset = 1 means first item of v plus an additional one
// Now we have 9 -1 3 4 instead of 9 2 3 4
// ...

As you can see we can also do

*(it+10) = 9;

which is again an invalid memory access. This is basically the same as using at(0 + offset) but without the out of bounds error checking.

I would advice using at(...) whenever possible not only because it's more readable compared to the iterator access but because of the error checking for invalid index that I have mentioned above for both the iterator with offset combination and the [] operator.

How to display items side-by-side without using tables?

It depends on what you want to do and what type of data/information you are displaying. In general, tables are reserved for displaying tabular data.

An alternate for your situation would be to use css. A simple option would be to float your image and give it a margin:

<p>
    <img style="float: left; margin: 5px;" ... />
    Text goes here...
</p>

This would cause the text to wrap around the image. If you don't want the text to wrap around the image, put the text in a separate container:

<div>
    <img style="float: left; margin: ...;" ... />
    <p style="float: right;">Text goes here...</p>
</div>

Note that it may be necessary to assign a width to the paragraph tag to display the way you'd like. Also note, for elements that appear below floated elements, you may need to add the style "clear: left;" (or clear: right, or clear: both).

Convert String to equivalent Enum value

I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

I guess it gives more granular control but I'm not sure it's really necessary.

public enum Type {
    DEBIT,
    CREDIT;

    public static Map<String, Type> typeMapping = Maps.newHashMap();
    static {
        typeMapping.put(DEBIT.name(), DEBIT);
        typeMapping.put(CREDIT.name(), CREDIT);
    }

    public static Type getType(String typeName) {
        if (typeMapping.get(typeName) == null) {
            throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
        }
        return typeMapping.get(typeName);
    }
}

I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

Printing object properties in Powershell

# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

http://plnkr.co/edit/A2IG03FLYnEYMpZ5RxEm?p=preview

Here is a case sensitive search that also separates your search into words to search in each model as well. Only when it finds a space will it try to split the query into an array and then search each word.

It returns true if every word is at least in one of the models.

$scope.songSearch = function (row) {
    var query = angular.lowercase($scope.query);
    if (query.indexOf(" ") > 0) {
        query_array = query.split(" ");
        search_result = false;
        for (x in query_array) {
            query = query_array[x];
            if (angular.lowercase(row.model1).indexOf(query || '') !== -1 || angular.lowercase(row.model2).indexOf(query || '') !== -1 || angular.lowercase(row.model3).indexOf(query || '') !== -1){
                search_result = true;
            } else {
                search_result = false;
                break;
            }
        }
        return search_result;
    } else {
        return (angular.lowercase(row.model1).indexOf(query || '') !== -1 || angular.lowercase(row.model2).indexOf(query || '') !== -1 || angular.lowercase(row.model3).indexOf(query || '') !== -1);
    }
};

How to replace a character with a newline in Emacs?

M-x replace-string RET ; RET C-q C-j.

  • C-q for quoted-insert,

  • C-j is a newline.

Cheers!

How to compile a Perl script to a Windows executable with Strawberry Perl?

  :: short answer :
  :: perl -MCPAN -e "install PAR::Packer" 
  pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>> 

  :: long answer - create the following cmd , adjust vars to your taste ...
  :: next_line_is_templatized
  :: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
  :: disable the echo
  @echo off

  :: this is part of the name of the file - not used
  set _Action=run

  :: the name of the Product next_line_is_templatized
  set _ProductName=morphus

  :: the version of the current Product next_line_is_templatized
  set _ProductVersion=1.2.3

  :: could be dev , test , dev , prod next_line_is_templatized
  set _ProductType=dev

  :: who owns this Product / environment next_line_is_templatized
  set _ProductOwner=ysg

  :: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )   
  set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%

  :: go the run dir
  cd %~dp0

  :: do 4 times going up
  for /L %%i in (1,1,5) do pushd ..

  :: The BaseDir is 4 dirs up than the run dir
  set _ProductBaseDir=%CD%
  :: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
  :: remove the trailing \

  IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
  :: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
  :: debug pause


  :: The version directory of the Product 
  set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%

  :: the dir under which all the perl scripts are placed
  set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl

  :: The Perl script performing all the tasks
  set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl

  :: where the log events are stored 
  set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log

  :: define a favorite editor 
  set _MyEditor=textpad

  ECHO Check the variables 
  set _
  :: debug PAUSE
  :: truncate the run log
  echo date is %date% time is %time% > %_RunLog%


  :: uncomment this to debug all the vars 
  :: debug set  >> %_RunLog%

  :: for each perl pm and or pl file to check syntax and with output to logs
  for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a  %_RunLog% 2>&1


  :: for each perl pm and or pl file to check syntax and with output to logs
  for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a  %_RunLog% 2>&1

  :: now open the run log
  cmd /c start /max %_MyEditor% %_RunLog%


  :: this is the call without debugging
  :: old 
  echo CFPoint1  OK The run cmd script %0 is executed >> %_RunLog%
  echo CFPoint2  OK  compile the exe file  STDOUT and STDERR  to a single _RunLog file >> %_RunLog%
  cd %_ProductVersionPerlDir%

  pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1 

  :: open the run log
  cmd /c start /max %_MyEditor% %_RunLog%

  :: uncomment this line to wait for 5 seconds
  :: ping localhost -n 5

  :: uncomment this line to see what is happening 
  :: PAUSE

  ::
  :::::::
  :: Purpose: 
  :: To compile every *.pl file into *.exe file under a folder 
  :::::::
  :: Requirements : 
  :: perl , pp , win gnu utils tee 
  :: perl -MCPAN -e "install PAR::Packer" 
  :: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
  :::::::
  :: VersionHistory
  :: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
  :::::::
  :: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0

Unable to create Genymotion Virtual Device

Solved!!

I am using OS X 10.9 (Mavericks), Genymotion v1.3.1

While adding the device, instead of adding Nexus, I added Galaxy S4/HTC One/Xperia Z - 4.2.2 with Google Apps.

This one just worked.

What is the difference between "long", "long long", "long int", and "long long int" in C++?

Long and long int are at least 32 bits.

long long and long long int are at least 64 bits. You must be using a c99 compiler or better.

long doubles are a bit odd. Look them up on Wikipedia for details.

Understanding the results of Execute Explain Plan in Oracle SQL Developer

Here is a reference for using EXPLAIN PLAN with Oracle: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm), with specific information about the columns found here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm#i18300

Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.

Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.

Generating HTML email body in C#

Emitting handbuilt html like this is probably the best way so long as the markup isn't too complicated. The stringbuilder only starts to pay you back in terms of efficiency after about three concatenations, so for really simple stuff string + string will do.

Other than that you can start to use the html controls (System.Web.UI.HtmlControls) and render them, that way you can sometimes inherit them and make your own clasess for complex conditional layout.

How to set image button backgroundimage for different state?

i think you problem is not the selector file.

you have to add

<imagebutton ..
    android:clickable="true"
/>

to your image buttons.

by default the onClick is handled at the listitem level (parent). and the imageButtons dont recieve the onClick.

when you add the above attribute the image button will receive the event and the selector will be used.

check this POST which explains the same for checkbox.

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

Cancel a UIView animation?

[UIView setAnimationsEnabled:NO];
// your code here
[UIView setAnimationsEnabled:YES];

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

No, this is, as you say "rubbish code". If it works as should, it is because browsers try to "read the writer's mind" - in other words, they have algorithms to try to make sense of "rubbish code", guess at the probable intent and internally change it into something that actually makes sense.

In other words, your code only works by accident, and probably not in all browsers.

Is this what you're trying to do?

<a href="#" onClick="alert('Hello World!')"><img title="The Link" /></a>

Monad in plain English? (For the OOP programmer with no FP background)

I would say the closest OO analogy to monads is the "command pattern".

In the command pattern you wrap an ordinary statement or expression in a command object. The command object expose an execute method which executes the wrapped statement. So statement are turned into first class objects which can passed around and executed at will. Commands can be composed so you can create a program-object by chaining and nesting command-objects.

The commands are executed by a separate object, the invoker. The benefit of using the command pattern (rather than just execute a series of ordinary statements) is that different invokers can apply different logic to how the commands should be executed.

The command pattern could be used to add (or remove) language features which is not supported by the host language. For example, in a hypothetical OO language without exceptions, you could add exception semantics by exposing "try" and "throw" methods to the commands. When a command calls throw, the invoker backtracks through the list (or tree) of commands until the last "try" call. Conversely, you could remove exception semantic from a language (if you believe exceptions are bad) by catching all exceptions thrown by each individual commands, and turning them into error codes which are then passed to the next command.

Even more fancy execution semantics like transactions, non-deterministic execution or continuations can be implemented like this in a language which doesn't support it natively. It is a pretty powerful pattern if you think about it.

Now in reality the command-patterns is not used as a general language feature like this. The overhead of turning each statement into a separate class would lead to an unbearable amount of boilerplate code. But in principle it can be used to solve the same problems as monads are used to solve in fp.

Nginx: Permission denied for nginx on Ubuntu

I just patch nginx binary replacing path /var/log/nginx/error.log and other with local path.

$ perl -pi \
    -e 's@/var/log/nginx/@_var_log_nginx/@g;' \
    -e 's@/var/lib/nginx/@_var_lib_nginx/@g;' \
    -e 's@/var/run/nginx.pid@_var_run/nginx.pid@g;' \
    -e 's@/run/nginx.pid@_run/nginx.pid@g;' \
    < /usr/sbin/nginx > nginx
$ chmod +x nginx
$ mkdir _var_log_nginx _var_lib_nginx _var_run _run
$ ./nginx -p . -c nginx.conf

It works for testing.

"static const" vs "#define" vs "enum"

In C, specifically? In C the correct answer is: use #define (or, if appropriate, enum)

While it is beneficial to have the scoping and typing properties of a const object, in reality const objects in C (as opposed to C++) are not true constants and therefore are usually useless in most practical cases.

So, in C the choice should be determined by how you plan to use your constant. For example, you can't use a const int object as a case label (while a macro will work). You can't use a const int object as a bit-field width (while a macro will work). In C89/90 you can't use a const object to specify an array size (while a macro will work). Even in C99 you can't use a const object to specify an array size when you need a non-VLA array.

If this is important for you then it will determine your choice. Most of the time, you'll have no choice but to use #define in C. And don't forget another alternative, that produces true constants in C - enum.

In C++ const objects are true constants, so in C++ it is almost always better to prefer the const variant (no need for explicit static in C++ though).

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Syntax errors is not checked easily in external servers, just runtime errors.

What I do? Just like you, I use

ini_set('display_errors', 'On');
error_reporting(E_ALL);

However, before run I check syntax errors in a PHP file using an online PHP syntax checker.

The best, IMHO is PHP Code Checker

I copy all the source code, paste inside the main box and click the Analyze button.

It is not the most practical method, but the 2 procedures are complementary and it solves the problem completely

Easy way to turn JavaScript array into comma-separated list?

There are many methods to convert an array to comma separated list

1. Using array#join

From MDN

The join() method joins all elements of an array (or an array-like object) into a string.

The code

var arr = ["this","is","a","comma","separated","list"];
arr = arr.join(",");

Snippet

_x000D_
_x000D_
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr.join(",");_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

2. Using array#toString

From MDN

The toString() method returns a string representing the specified array and its elements.

The code

var arr = ["this","is","a","comma","separated","list"];
arr = arr.toString();

Snippet

_x000D_
_x000D_
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr.toString();_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

3. Add []+ before array or +[] after an array

The []+ or +[] will convert it into a string

Proof

([]+[] === [].toString())

will output true

_x000D_
_x000D_
console.log([]+[] === [].toString());
_x000D_
_x000D_
_x000D_

var arr = ["this","is","a","comma","separated","list"];
arr = []+arr;

Snippet

_x000D_
_x000D_
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = []+arr;_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Also

var arr = ["this","is","a","comma","separated","list"];
arr = arr+[];

_x000D_
_x000D_
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr + [];_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

PHP Unset Session Variable

// set
$_SESSION['test'] = 1;

// destroy
unset($_SESSION['test']);

Convert String to Type in C#

use following LoadType method to use System.Reflection to load all registered(GAC) and referenced assemblies and check for typeName

public Type[] LoadType(string typeName)
{
    return LoadType(typeName, true);
}

public Type[] LoadType(string typeName, bool referenced)
{
    return LoadType(typeName, referenced, true);
}

private Type[] LoadType(string typeName, bool referenced, bool gac)
{
    //check for problematic work
    if (string.IsNullOrEmpty(typeName) || !referenced && !gac)
        return new Type[] { };

    Assembly currentAssembly = Assembly.GetExecutingAssembly();

    List<string> assemblyFullnames = new List<string>();
    List<Type> types = new List<Type>();

    if (referenced)
    {            //Check refrenced assemblies
        foreach (AssemblyName assemblyName in currentAssembly.GetReferencedAssemblies())
        {
            //Load method resolve refrenced loaded assembly
            Assembly assembly = Assembly.Load(assemblyName.FullName);

            //Check if type is exists in assembly
            var type = assembly.GetType(typeName, false, true);

            if (type != null && !assemblyFullnames.Contains(assembly.FullName))
            {
                types.Add(type);
                assemblyFullnames.Add(assembly.FullName);
            }
        }
    }

    if (gac)
    {
        //GAC files
        string gacPath = Environment.GetFolderPath(System.Environment.SpecialFolder.Windows) + "\\assembly";
        var files = GetGlobalAssemblyCacheFiles(gacPath);
        foreach (string file in files)
        {
            try
            {
                //reflection only
                Assembly assembly = Assembly.ReflectionOnlyLoadFrom(file);

                //Check if type is exists in assembly
                var type = assembly.GetType(typeName, false, true);

                if (type != null && !assemblyFullnames.Contains(assembly.FullName))
                {
                    types.Add(type);
                    assemblyFullnames.Add(assembly.FullName);
                }
            }
            catch
            {
                //your custom handling
            }
        }
    }

    return types.ToArray();
}

public static string[] GetGlobalAssemblyCacheFiles(string path)
{
    List<string> files = new List<string>();

    DirectoryInfo di = new DirectoryInfo(path);

    foreach (FileInfo fi in di.GetFiles("*.dll"))
    {
        files.Add(fi.FullName);
    }

    foreach (DirectoryInfo diChild in di.GetDirectories())
    {
        var files2 = GetGlobalAssemblyCacheFiles(diChild.FullName);
        files.AddRange(files2);
    }

    return files.ToArray();
}

Resize UIImage and change the size of UIImageView

Use the category below and then apply border from Quartz into your image:

[yourimage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
[yourimage.layer setBorderWidth:2];

The category: UIImage+AutoScaleResize.h

#import <Foundation/Foundation.h>

@interface UIImage (AutoScaleResize)

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize;

@end

UIImage+AutoScaleResize.m

#import "UIImage+AutoScaleResize.h"

@implementation UIImage (AutoScaleResize)

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor > heightFactor)
        {
            scaleFactor = widthFactor; // scale to fit height
        }
        else
        {
            scaleFactor = heightFactor; // scale to fit width
        }

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
        {
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }
    }

    UIGraphicsBeginImageContext(targetSize); // this will crop

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    if(newImage == nil)
    {
        NSLog(@"could not scale image");
    }

    //pop the context to get back to the default
    UIGraphicsEndImageContext();

    return newImage;
}

@end

Gridview row editing - dynamic binding to a DropDownList

protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)  
{  
    grvSecondaryLocations.EditIndex = e.NewEditIndex;  

    DropDownList ddlPbx = (DropDownList)(grvSecondaryLocations.Rows[grvSecondaryLocations.EditIndex].FindControl("ddlPBXTypeNS"));
    if (ddlPbx != null)  
    {  
        ddlPbx.DataSource = _pbxTypes;  
        ddlPbx.DataBind();  
    }  

    .... (more stuff)  
}

How to include external Python code to use in other files?

Just write the "include" command :

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

I was facing the same error while running command

pip install --upgrade pip

in a virtual venvironment (created with python -m venv venv).

using the --user flag fixed the problem for me

pip install --upgrade pip --user

If the problem not resolved use --user flag in a command prompt with admin rights.

React component not re-rendering on state change

After looking into many answers (most of them are correct for their scenarios) and none of them fix my problem I realized that my case is a bit different:

In my weird scenario my component was being rendered inside the state and therefore couldn't be updated. Below is a simple example:

constructor() {
    this.myMethod = this.myMethod.bind(this);
    this.changeTitle = this.changeTitle.bind(this);

    this.myMethod();
}

changeTitle() {
    this.setState({title: 'I will never get updated!!'});
}

myMethod() {
    this.setState({body: <div>{this.state.title}</div>});
}

render() {
    return <>
        {this.state.body}
        <Button onclick={() => this.changeTitle()}>Change Title!</Button>
    </>
}

After refactoring the code to not render the body from state it worked fine :)

SQL to Entity Framework Count Group-By

with EF 6.2 it worked for me

  var query = context.People
               .GroupBy(p => new {p.name})
               .Select(g => new { name = g.Key.name, count = g.Count() });

How do I exit a while loop in Java?

To exit a while loop, use Break; This will not allow to loop to process any conditions that are placed inside, make sure to have this inside the loop, as you cannot place it outside the loop

Make a link use POST instead of GET

You can use this jQuery function

function makePostRequest(url, data) {
    var jForm = $('<form></form>');
    jForm.attr('action', url);
    jForm.attr('method', 'post');
    for (name in data) {
        var jInput = $("<input>");
        jInput.attr('name', name);
        jInput.attr('value', data[name]);
        jForm.append(jInput);
    }
    jForm.submit();
}

Here is an example in jsFiddle (http://jsfiddle.net/S7zUm/)

Running Python code in Vim

If you want to quickly jump back through your :w commands, a cool thing is to type :w and then press your up arrow. It will only cycle through commands that start with w.

Check if string ends with one of the strings from a list

There is two ways: regular expressions and string (str) methods.

String methods are usually faster ( ~2x ).

import re, timeit
p = re.compile('.*(.mp3|.avi)$', re.IGNORECASE)
file_name = 'test.mp3'
print(bool(t.match(file_name))
%timeit bool(t.match(file_name)

792 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

file_name = 'test.mp3'
extensions = ('.mp3','.avi')
print(file_name.lower().endswith(extensions))
%timeit file_name.lower().endswith(extensions)

274 ns ± 4.22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

JavaScript URL Decode function

If you are responsible for encoding the data in PHP using urlencode, PHP's rawurlencode works with JavaScript's decodeURIComponent without needing to replace the + character.

How I could add dir to $PATH in Makefile?

What I usually do is supply the path to the executable explicitly:

EXE=./bin/
...
test all:
    $(EXE)x

I also use this technique to run non-native binaries under an emulator like QEMU if I'm cross compiling:

EXE = qemu-mips ./bin/

If make is using the sh shell, this should work:

test all:
    PATH=bin:$PATH x

How to extract one column of a csv file

You could use GNU Awk, see this article of the user guide. As an improvement to the solution presented in the article (in June 2015), the following gawk command allows double quotes inside double quoted fields; a double quote is marked by two consecutive double quotes ("") there. Furthermore, this allows empty fields, but even this can not handle multiline fields. The following example prints the 3rd column (via c=3) of textfile.csv:

#!/bin/bash
gawk -- '
BEGIN{
    FPAT="([^,\"]*)|(\"((\"\")*[^\"]*)*\")"
}
{
    if (substr($c, 1, 1) == "\"") {
        $c = substr($c, 2, length($c) - 2) # Get the text within the two quotes
        gsub("\"\"", "\"", $c)  # Normalize double quotes
    }
    print $c
}
' c=3 < <(dos2unix <textfile.csv)

Note the use of dos2unix to convert possible DOS style line breaks (CRLF i.e. "\r\n") and UTF-16 encoding (with byte order mark) to "\n" and UTF-8 (without byte order mark), respectively. Standard CSV files use CRLF as line break, see Wikipedia.

If the input may contain multiline fields, you can use the following script. Note the use of special string for separating records in output (since the default separator newline could occur within a record). Again, the following example prints the 3rd column (via c=3) of textfile.csv:

#!/bin/bash
gawk -- '
BEGIN{
    RS="\0" # Read the whole input file as one record;
    # assume there is no null character in input.
    FS="" # Suppose this setting eases internal splitting work.
    ORS="\n####\n" # Use a special output separator to show borders of a record.
}
{
    nof=patsplit($0, a, /([^,"\n]*)|("(("")*[^"]*)*")/, seps)
    field=0;
    for (i=1; i<=nof; i++){
        field++
        if (field==c) {
            if (substr(a[i], 1, 1) == "\"") {
                a[i] = substr(a[i], 2, length(a[i]) - 2) # Get the text within 
                # the two quotes.
                gsub(/""/, "\"", a[i])  # Normalize double quotes.
            }
            print a[i]
        }
        if (seps[i]!=",") field=0
    }
}
' c=3 < <(dos2unix <textfile.csv)

There is another approach to the problem. csvquote can output contents of a CSV file modified so that special characters within field are transformed so that usual Unix text processing tools can be used to select certain column. For example the following code outputs the third column:

csvquote textfile.csv | cut -d ',' -f 3 | csvquote -u

csvquote can be used to process arbitrary large files.

java.net.SocketTimeoutException: Read timed out under Tomcat

Here are the basic instructions:-

  1. Locate the "server.xml" file in the "conf" folder beneath Tomcat's base directory (i.e. %CATALINA_HOME%/conf/server.xml).
  2. Open the file in an editor and search for <Connector.
  3. Locate the relevant connector that is timing out - this will typically be the HTTP connector, i.e. the one with protocol="HTTP/1.1".
  4. If a connectionTimeout value is set on the connector, it may need to be increased - e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout property value is set on the connector, the default is 60 seconds - if this is insufficient, the property may need to be added.
  5. Restart Tomcat

Get the year from specified date php

You can use the strtotime and date functions like this:

echo date('Y', strtotime('2068-06-15'));

Note however that PHP can handle year upto 2038

You can test it out here


If your date is always in that format, you can also get the year like this:

$parts = explode('-', '2068-06-15');
echo $parts[0];

How to execute an .SQL script file using c#

I couldn't find any exact and valid way to do this. So after a whole day, I came with this mixed code achieved from different sources and trying to get the job done.

But it is still generating an exception ExecuteNonQuery: CommandText property has not been Initialized even though it successfully runs the script file - in my case, it successfully creates the database and inserts data on the first startup.

public partial class Form1 : MetroForm
{
    SqlConnection cn;
    SqlCommand cm;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if (!CheckDatabaseExist())
        {
            GenerateDatabase();
        }
    }

    private bool CheckDatabaseExist()
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=SalmanTradersDB;Integrated Security=true");
        try
        {
            con.Open();
            return true;
        }
        catch
        {
            return false;
        }
    }

    private void GenerateDatabase()
    {

        try
        {
            cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format("drop databse {0}", "SalmanTradersDB"));
            cm = new SqlCommand(sb.ToString() , cn);
            cn.Open();
            cm.ExecuteNonQuery();
            cn.Close();
        }
        catch
        {

        }
        try
        {
            //Application.StartupPath is the location where the application is Installed
            //Here File Path Can Be Provided Via OpenFileDialog
            if (File.Exists(Application.StartupPath + "\\script.sql"))
            {
                string script = null;
                script = File.ReadAllText(Application.StartupPath + "\\script.sql");
                string[] ScriptSplitter = script.Split(new string[] { "GO" }, StringSplitOptions.None);
                using (cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
                {
                    cn.Open();
                    foreach (string str in ScriptSplitter)
                    {
                        using (cm = cn.CreateCommand())
                        {
                            cm.CommandText = str;
                            cm.ExecuteNonQuery();
                        }
                    }
                }
            }
        }
        catch
        {

        }

    }

}

How to save and load cookies using Python + Selenium WebDriver

You can save the current cookies as a Python object using pickle. For example:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

And later to add them back:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

How can I get a character in a string by index?

string s = "hello";
char c = s[1];
// now c == 'e'

See also Substring, to return more than one character.

Get cookie by name

Simple function for Get cookie with cookie name:

function getCookie(cn) {
    var name = cn+"=";
    var allCookie = decodeURIComponent(document.cookie).split(';');
    var cval = [];
    for(var i=0; i < allCookie.length; i++) {
        if (allCookie[i].trim().indexOf(name) == 0) {
            cval = allCookie[i].trim().split("=");
        }   
    }
    return (cval.length > 0) ? cval[1] : "";
}

For a boolean field, what is the naming convention for its getter/setter?

I believe it would be:

void setCurrent(boolean current)
boolean isCurrent()

libstdc++-6.dll not found

Simply removing libstdc++-6.dll.a \ libstdc++.dll.a from the mingw directory fixes this.

I tried using the flag -static-libstdc++ but this did not work for me. I found the solution in: http://ghc.haskell.org/trac/ghc/ticket/4468#

Running PHP script from the command line

On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.

If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.

You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.

Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.

Can I send a ctrl-C (SIGINT) to an application on Windows?

Here is the code I use in my C++ app.

Positive points :

  • Works from console app
  • Works from Windows service
  • No delay required
  • Does not close the current app

Negative points :

  • The main console is lost and a new one is created (see FreeConsole)
  • The console switching give strange results...

// Inspired from http://stackoverflow.com/a/15281070/1529139
// and http://stackoverflow.com/q/40059902/1529139
bool signalCtrl(DWORD dwProcessId, DWORD dwCtrlEvent)
{
    bool success = false;
    DWORD thisConsoleId = GetCurrentProcessId();
    // Leave current console if it exists
    // (otherwise AttachConsole will return ERROR_ACCESS_DENIED)
    bool consoleDetached = (FreeConsole() != FALSE);

    if (AttachConsole(dwProcessId) != FALSE)
    {
        // Add a fake Ctrl-C handler for avoid instant kill is this console
        // WARNING: do not revert it or current program will be also killed
        SetConsoleCtrlHandler(nullptr, true);
        success = (GenerateConsoleCtrlEvent(dwCtrlEvent, 0) != FALSE);
        FreeConsole();
    }

    if (consoleDetached)
    {
        // Create a new console if previous was deleted by OS
        if (AttachConsole(thisConsoleId) == FALSE)
        {
            int errorCode = GetLastError();
            if (errorCode == 31) // 31=ERROR_GEN_FAILURE
            {
                AllocConsole();
            }
        }
    }
    return success;
}

Usage example :

DWORD dwProcessId = ...;
if (signalCtrl(dwProcessId, CTRL_C_EVENT))
{
    cout << "Signal sent" << endl;
}

What is default session timeout in ASP.NET?

It is 20 Minutes according to MSDN

From MSDN:

Optional TimeSpan attribute.

Specifies the number of minutes a session can be idle before it is abandoned. The timeout attribute cannot be set to a value that is greater than 525,601 minutes (1 year) for the in-process and state-server modes. The session timeout configuration setting applies only to ASP.NET pages. Changing the session timeout value does not affect the session time-out for ASP pages. Similarly, changing the session time-out for ASP pages does not affect the session time-out for ASP.NET pages. The default is 20 minutes.

How to check if input file is empty in jQuery

Here is the jQuery version of it:

if ($('#videoUploadFile').get(0).files.length === 0) {
    console.log("No files selected.");
}

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

If you're using a graphical tool. It shows you the schema right next to the table name. In case of DB Browser For Sqlite, click to open the database(top right corner), navigate and open your database, you'll see the information populated in the table as below.

enter image description here

right click on the record/table_name, click on copy create statement and there you have it.

Hope it helped some beginner who failed to work with the commandline.

Import Google Play Services library in Android Studio

Try this once and make sure you are not getting any error in project Structure saying that "ComGoogleAndroidGmsPlay not added"

Open File > Project Structure and check for below all. If error is shown click on Red bulb marked and click on "Add to dependency".

GMS dependency

This is a bug in Android Studio and fixed for the next release(0.4.3)

SQL ROWNUM how to return rows between a specific range

SELECT  *
FROM    (
        SELECT  q.*, rownum rn
        FROM    (
                SELECT  *
                FROM    maps006
                ORDER BY
                        id
                ) q
        )
WHERE   rn BETWEEN 50 AND 100

Note the double nested view. ROWNUM is evaluated before ORDER BY, so it is required for correct numbering.

If you omit ORDER BY clause, you won't get consistent order.

pandas GroupBy columns with NaN (missing) values

All answers provided thus far result in potentially dangerous behavior as it is quite possible you select a dummy value that is actually part of the dataset. This is increasingly likely as you create groups with many attributes. Simply put, the approach doesn't always generalize well.

A less hacky solve is to use pd.drop_duplicates() to create a unique index of value combinations each with their own ID, and then group on that id. It is more verbose but does get the job done:

def safe_groupby(df, group_cols, agg_dict):
    # set name of group col to unique value
    group_id = 'group_id'
    while group_id in df.columns:
        group_id += 'x'
    # get final order of columns
    agg_col_order = (group_cols + list(agg_dict.keys()))
    # create unique index of grouped values
    group_idx = df[group_cols].drop_duplicates()
    group_idx[group_id] = np.arange(group_idx.shape[0])
    # merge unique index on dataframe
    df = df.merge(group_idx, on=group_cols)
    # group dataframe on group id and aggregate values
    df_agg = df.groupby(group_id, as_index=True)\
               .agg(agg_dict)
    # merge grouped value index to results of aggregation
    df_agg = group_idx.set_index(group_id).join(df_agg)
    # rename index
    df_agg.index.name = None
    # return reordered columns
    return df_agg[agg_col_order]

Note that you can now simply do the following:

data_block = [np.tile([None, 'A'], 3),
              np.repeat(['B', 'C'], 3),
              [1] * (2 * 3)]

col_names = ['col_a', 'col_b', 'value']

test_df = pd.DataFrame(data_block, index=col_names).T

grouped_df = safe_groupby(test_df, ['col_a', 'col_b'],
                          OrderedDict([('value', 'sum')]))

This will return the successful result without having to worry about overwriting real data that is mistaken as a dummy value.

Check if element found in array c++

One wants this to be done tersely. Nothing makes code more unreadable then spending 10 lines to achieve something elementary. In C++ (and other languages) we have all and any which help us to achieve terseness in this case. I want to check whether a function parameter is valid, meaning equal to one of a number of values. Naively and wrongly, I would first write

if (!any_of({ DNS_TYPE_A, DNS_TYPE_MX }, wtype) return false;

a second attempt could be

if (!any_of({ DNS_TYPE_A, DNS_TYPE_MX }, [&wtype](const int elem) { return elem == wtype; })) return false;

Less incorrect, but looses some terseness. However, this is still not correct because C++ insists in this case (and many others) that I specify both start and end iterators and cannot use the whole container as a default for both. So, in the end:

const vector validvalues{ DNS_TYPE_A, DNS_TYPE_MX };
if (!any_of(validvalues.cbegin(),  validvalues.cend(), [&wtype](const int elem) { return elem == wtype; })) return false;

which sort of defeats the terseness, but I don't know a better alternative... Thank you for not pointing out that in the case of 2 values I could just have just if ( || ). The best approach here (if possible) is to use a case structure with a default where not only the values are checked, but also the appropriate actions are done. The default case can be used for signalling an invalid value.

Regular expression for not allowing spaces in the input field

This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.

/^([A-z0-9!@#$%^&*().,<>{}[\]<>?_=+\-|;:\'\"\/])*[^\s]\1*$/

Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.

If you want just alphanumeric characters then change what is in the [] like so:

/^([A-z])*[^\s]\1*$/

Random record from MongoDB

My PHP/MongoDB sort/order by RANDOM solution. Hope this helps anyone.

Note: I have numeric ID's within my MongoDB collection that refer to a MySQL database record.

First I create an array with 10 randomly generated numbers

    $randomNumbers = [];
    for($i = 0; $i < 10; $i++){
        $randomNumbers[] = rand(0,1000);
    }

In my aggregation I use the $addField pipeline operator combined with $arrayElemAt and $mod (modulus). The modulus operator will give me a number from 0 - 9 which I then use to pick a number from the array with random generated numbers.

    $aggregate[] = [
        '$addFields' => [
            'random_sort' => [ '$arrayElemAt' => [ $randomNumbers, [ '$mod' => [ '$my_numeric_mysql_id', 10 ] ] ] ],
        ],
    ];

After that you can use the sort Pipeline.

    $aggregate[] = [
        '$sort' => [
            'random_sort' => 1
        ]
    ];

Open File Dialog, One Filter for Multiple Excel Extensions?

Use a semicolon

OpenFileDialog of = new OpenFileDialog();
of.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";

Remove all child elements of a DOM node in JavaScript

If you use jQuery:

$('#foo').empty();

If you don't:

var foo = document.getElementById('foo');
while (foo.firstChild) foo.removeChild(foo.firstChild);

Importing files from different folder

I was faced with the same challenge, especially when importing multiple files, this is how I managed to overcome it.

import os, sys

from os.path import dirname, join, abspath
sys.path.insert(0, abspath(join(dirname(__file__), '..')))

from root_folder import file_name

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

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

<OTHER_ENVIRONMENT_VARIABLES>;CUDA_VISIBLE_DEVICES=-1

How to remove specific elements in a numpy array

Using np.delete is the fastest way to do it, if we know the indices of the elements that we want to remove. However, for completeness, let me add another way of "removing" array elements using a boolean mask created with the help of np.isin. This method allows us to remove the elements by specifying them directly or by their indices:

import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Remove by indices:

indices_to_remove = [2, 3, 6]
a = a[~np.isin(np.arange(a.size), indices_to_remove)]

Remove by elements (don't forget to recreate the original a since it was rewritten in the previous line):

elements_to_remove = a[indices_to_remove]  # [3, 4, 7]
a = a[~np.isin(a, elements_to_remove)]

How to insert special characters into a database?

Note that as others have pointed out mysql_real_escape_string() will solve the problem (as will addslashes), however you should always use mysql_real_escape_string() for security reasons - consider:

SELECT * FROM valid_users WHERE username='$user' AND password='$password'

What if the browser sends

user="admin' OR (user=''"
password="') AND ''='"

The query becomes:

SELECT * FROM valid_users 
WHERE username='admin' OR (user='' AND password='') AND ''=''

i.e. the security checks are completely bypassed.

C.

Style input element to fill remaining width of its container

I suggest using Flexbox:

Be sure to add the proper vendor prefixes though!

_x000D_
_x000D_
form {_x000D_
  width: 400px;_x000D_
  border: 1px solid black;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
input {_x000D_
  flex: 2;_x000D_
}_x000D_
_x000D_
input, label {_x000D_
  margin: 5px;_x000D_
}
_x000D_
<form method="post">_x000D_
  <label for="myInput">Sample label</label>_x000D_
  <input type="text" id="myInput" placeholder="Sample Input"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How do I initialize an empty array in C#?

string[] a = new string[0];

or short notation:

string[] a = { };

The preferred way now is:

var a = Array.Empty<string>();

I have written a short regular expression that you can use in Visual Studio if you want to replace zero-length allocations e.g. new string[0]. Use Find (search) in Visual Studio with Regular Expression option turned on:

new[ ][a-zA-Z0-9]+\[0\]

Now Find All or F3 (Find Next) and replace all with Array.Empty<…>() !

Specifying a custom DateTime format when serializing with Json.Net

Also available using one of the serializer settings overloads:

var json = JsonConvert.SerializeObject(someObject, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });

Or

var json = JsonConvert.SerializeObject(someObject, Formatting.Indented, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });

Overloads taking a Type are also available.

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

If you just want the bitmap, This too works

InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();

sample uri : content://media/external/images/media/12345

How to pause in C?

If you are making a console window program, you can use system("pause");

How to test the type of a thrown exception in Jest

It is a little bit weird, but it works and IMHO is good readable:

it('should throw Error with message \'UNKNOWN ERROR\' when no parameters were passed', () => {
  try {
      throwError();
      // Fail test if above expression doesn't throw anything.
      expect(true).toBe(false);
  } catch (e) {
      expect(e.message).toBe("UNKNOWN ERROR");
  }
});

The Catch block catches your exception, and then you can test on your raised Error. Strange expect(true).toBe(false); is needed to fail your test if the expected Error will be not thrown. Otherwise, this line is never reachable (Error should be raised before them).

@Kenny Body suggested a better solution which improve a code quality if you use expect.assertions():

it('should throw Error with message \'UNKNOWN ERROR\' when no parameters were passed', () => {
  expect.assertions(1);
  try {
      throwError();
  } catch (e) {
      expect(e.message).toBe("UNKNOWN ERROR");
  }
});

See the original answer with more explanations: How to test the type of a thrown exception in Jest

Fail to create Android virtual Device, "No system image installed for this Target"

I had android sdk and android studio installed separately in my system. Android studio had installed its own sdk. After I deleted the stand-alone android sdk, the issue of "“No system image installed for this Target” was gone.

What port is used by Java RMI connection?

RMI generally won't work over a firewall, since it uses unpredictable ports (it starts off on 1099, and then runs off with a random port after that).

In these situations, you generally need to resort to tunnelling RMI over HTTP, which is described well here.

How to update Pandas from Anaconda and is it possible to use eclipse with this last

Simply type conda update pandas in your preferred shell (on Windows, use cmd; if Anaconda is not added to your PATH use the Anaconda prompt). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory). See this document for a detailed instruction.

Sort dataGridView columns in C# ? (Windows Form)

This one is simplier :)

dataview dataview1; 
this.dataview1= dataset.tables[0].defaultview;
this.dataview1.sort = "[ColumnName] ASC, [ColumnName] DESC";
this.datagridview.datasource = dataview1;

Compare DATETIME and DATE ignoring time portion

For Compare two date like MM/DD/YYYY to MM/DD/YYYY . Remember First thing column type of Field must be dateTime. Example : columnName : payment_date dataType : DateTime .

after that you can easily compare it. Query is :

select  *  from demo_date where date >= '3/1/2015' and date <=  '3/31/2015'.

It very simple ...... It tested it.....

Shorter syntax for casting from a List<X> to a List<Y>?

The direct cast var ListOfY = (List<Y>)ListOfX is not possible because it would require co/contravariance of the List<T> type, and that just can't be guaranteed in every case. Please read on to see the solutions to this casting problem.

While it seems normal to be able to write code like this:

List<Animal> animals = (List<Animal>) mammalList;

because we can guarantee that every mammal will be an animal, this is obviously a mistake:

List<Mammal> mammals = (List<Mammal>) animalList;

since not every animal is a mammal.

However, using C# 3 and above, you can use

IEnumerable<Animal> animals = mammalList.Cast<Animal>();

that eases the casting a little. This is syntactically equivalent to your one-by-one adding code, as it uses an explicit cast to cast each Mammal in the list to an Animal, and will fail if the cast is not successfull.

If you like more control over the casting / conversion process, you could use the ConvertAll method of the List<T> class, which can use a supplied expression to convert the items. It has the added benifit that it returns a List, instead of IEnumerable, so no .ToList() is necessary.

List<object> o = new List<object>();
o.Add("one");
o.Add("two");
o.Add(3);

IEnumerable<string> s1 = o.Cast<string>(); //fails on the 3rd item
List<string> s2 = o.ConvertAll(x => x.ToString()); //succeeds

What methods of ‘clearfix’ can I use?

With LESS (http://lesscss.org/), one can create a handy clearfix helper:

.clearfix() {
  zoom: 1;
  &:before { 
    content: ''; 
    display: block; 
  }
  &:after { 
    content: ''; 
    display: table; 
    clear: both; 
  }
}

And then use it with problematic containers, for example:

<!-- HTML -->
<div id="container">
  <div id="content"></div>
  <div id="sidebar"></div>
</div>
/* LESS */
div#container {
  .clearfix();
}

How to check if a Docker image with a specific tag exist locally?

With the help of Vonc's answer above I created the following bash script named check.sh:

#!/bin/bash
image_and_tag="$1"
image_and_tag_array=(${image_and_tag//:/ })
if [[ "$(docker images ${image_and_tag_array[0]} | grep ${image_and_tag_array[1]} 2> /dev/null)" != "" ]]; then
  echo "exists"
else
  echo "doesn't exist"
fi

Using it for an existing image and tag will print exists, for example:

./check.sh rabbitmq:3.4.4

Using it for a non-existing image and tag will print doesn't exist, for example:

./check.sh rabbitmq:3.4.3

Splitting a string into chunks of a certain size

    public static List<string> SplitByMaxLength(this string str)
    {
        List<string> splitString = new List<string>();

        for (int index = 0; index < str.Length; index += MaxLength)
        {
            splitString.Add(str.Substring(index, Math.Min(MaxLength, str.Length - index)));
        }

        return splitString;
    }

How can I get device ID for Admob

To get the device id, connect your phone to USB and open logcat in android studio Use the code below (make sure you have USB debugging enabled in your device). Then open any app (download any random app from play store) which has google Ad. In the Logcat type "set" as shown in the image. Your device id is shown highlighted in the image as

setTestDeviceIds(Arrays.asList("CC9DW7W7R4H0NM3LT9OLOF7455F8800D")).

enter image description here

Use the Test Device in your code as shown

val adRequest = AdRequest
        .Builder()
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("CC9DW7W7R4H0NM3LT9OLOF7455F8800D")
        .build()

How to make PopUp window in java

public class JSONPage {
    Logger log = Logger.getLogger("com.prodapt.autotest.gui.design.EditTestData");


    public static final JFrame JSONFrame = new JFrame();
    public final JPanel jPanel = new JPanel();

    JLabel IdLabel = new JLabel("JSON ID*");
    JLabel DataLabel = new JLabel("JSON Data*");
    JFormattedTextField JId = new JFormattedTextField("Auto Generated");
    JTextArea JData = new JTextArea();
    JButton Cancel = new JButton("Cancel");
    JButton Add = new JButton("Add");

    public void JsonPage() {

        JSONFrame.getContentPane().add(jPanel);
        JSONFrame.add(jPanel);
        JSONFrame.setSize(400, 250);
        JSONFrame.setResizable(false);
        JSONFrame.setVisible(false);
        JSONFrame.setTitle("Add JSON Data");
        JSONFrame.setLocationRelativeTo(null);
        jPanel.setLayout(null);

        JData.setWrapStyleWord(true);
        JId.setEditable(false);

        IdLabel.setBounds(20, 30, 120, 25);
        JId.setBounds(100, 30, 120, 25);
        DataLabel.setBounds(20, 60, 120, 25);
        JData.setBounds(100, 60, 250, 75);
        Cancel.setBounds(80, 170, 80, 30);
        Add.setBounds(280, 170, 50, 30);

        jPanel.add(IdLabel);
        jPanel.add(JId);
        jPanel.add(DataLabel);
        jPanel.add(JData);
        jPanel.add(Cancel);
        jPanel.add(Add);

        SwingUtilities.updateComponentTreeUI(JSONFrame);

        Cancel.addActionListener(new ActionListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void actionPerformed(ActionEvent e) {
                JData.setText("");
                JSONFrame.hide();
                TestCasePage.testCaseFrame.show();
            }
        });

        Add.addActionListener(new ActionListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    PreparedStatement pStatement = DAOHelper.getInstance()
                            .createJSON(
                                    ConnectionClass.getInstance()
                                            .getConnection());
                    pStatement.setString(1, null);
                    if (JData.getText().toString().isEmpty()) {
                        JOptionPane.showMessageDialog(JSONFrame,
                                "Must Enter JSON Path");
                    } else {
                        // System.out.println(eleSelectBy);
                        pStatement.setString(2, JData.getText());
                        pStatement.executeUpdate();
                        JOptionPane.showMessageDialog(JSONFrame, "!! Added !!");
                        log.info("JSON Path Added"+JData);
                        JData.setText("");
                        JSONFrame.hide();
                    }

                } catch (SQLException e1) {
                    JData.setText("");
                    log.info("Error in Adding JSON Path");
                    e1.printStackTrace();
                }
            }
        });
    }

}

Oracle: how to INSERT if a row doesn't exist

You should use Merge: For example:

MERGE INTO employees e
    USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
    ON (e.id = h.emp_id)
  WHEN MATCHED THEN
    UPDATE SET e.address = h.address
  WHEN NOT MATCHED THEN
    INSERT (id, address)
    VALUES (h.emp_id, h.address);

or

MERGE INTO employees e
    USING hr_records h
    ON (e.id = h.emp_id)
  WHEN MATCHED THEN
    UPDATE SET e.address = h.address
  WHEN NOT MATCHED THEN
    INSERT (id, address)
    VALUES (h.emp_id, h.address);

https://oracle-base.com/articles/9i/merge-statement

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

Well, you should also try adding the Javascript code into a function, then calling the function after document body has loaded..it worked for me :)

Finding the index of an item in a list

For those coming from another language like me, maybe with a simple loop it's easier to understand and use it:

mylist = ["foo", "bar", "baz", "bar"]
newlist = enumerate(mylist)
for index, item in newlist:
  if item == "bar":
    print(index, item)

I am thankful for So what exactly does enumerate do?. That helped me to understand.

Shell script to get the process ID on Linux

You can use the command killall:

$ killall ruby

How to install beautiful soup 4 with python 2.7 on windows

I feel most people have pip installed already with Python. On Windows, one way to check for pip is to open Command Prompt and typing in:

python -m pip

If you get Usage and Commands instructions then you have it installed. If python was not found though, then it needs to be added to the path. Alternatively you can run the same command from within the installation directory of python.

If all is good, then this command will install BeautifulSoup easily:

python -m pip install BeautifulSoup4

Screenshot:

Installing very very beautiful soup

N' now I see I need to upgrade my pip, which I just did :)

append to url and refresh page

Shorter than the accepted answer, doing the same, but keeping it simple:

window.location.search += '&param=42';

We don't have to alter the entire url, just the query string, known as the search attribute of location.

When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.

How to perform update operations on columns of type JSONB in Postgres 9.4

This is coming in 9.5 in the form of jsonb_set by Andrew Dunstan based on an existing extension jsonbx that does work with 9.4

How do I remove javascript validation from my eclipse project?

Turn off the JavaScript Validator in the "Builders" config for your project:

  1. Right click your project
  2. Select Properties -> Builders
  3. Uncheck the "JavaScript Validator"

Then either restart your Eclipse or/and rename the .js to something like .js_ then back again.

Changing color of Twitter bootstrap Nav-Pills

This is specific to Bootstrap 4.0.

HTML

<ul class="nav nav-pills">
  <li class="nav-item">
    <a class="nav-link nav-link-color" href="#about">home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link nav-link-color"  href="#contact">contact</a>
  </li>
</ul>

CSS

.nav-pills > li > a.active {
  background-color: #ffffff !important;
  color: #ffffff !important;
}

.nav-pills > li > a:hover {
  color: #ffffff !important;
}

.nav-link-color {
  color: #ffffff;
}

Can not find the tag library descriptor of springframework

I finally configured RAD to build my Maven-based project, but was getting the following exception when I navigate to a page that uses the Spring taglib:

JSPG0047E: Unable to locate tag library for uri http://www.springframework.org/tags at com.ibm.ws.jsp.translator.visitor.tagfiledep.TagFileDependencyVisitor.visitCustomTagStart(TagFileDependencyVisitor.java:76) ...

The way I had configured my EAR, all the jars were in the EAR, not in the WAR’s WEB-INF/lib. According to the JSP 2.0 spec, I believe tag libs are searched for in all subdirectories of WEB-INF, hence the issue. My solution was to copy the tld files and place under WEB-INF/lib or WEB-INF.. Then it worked.

T-SQL Substring - Last 3 Characters

Because more ways to think about it are always good:

select reverse(substring(reverse(columnName), 1, 3))

One line ftp server in python

Why don't you instead use a one-line HTTP server?

python -m SimpleHTTPServer 8000

will serve the contents of the current working directory over HTTP on port 8000.

If you use Python 3, you should instead write

python3 -m http.server 8000

See the SimpleHTTPServer module docs for 2.x and the http.server docs for 3.x.

By the way, in both cases the port parameter is optional.

How to post data in PHP using file_get_contents?

$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if($response === false) {
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

How do I combine 2 javascript variables into a string

ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:

// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);

// => "Yo, Brendan!"

var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);

//=> JavaScript first appeared 20 years ago. Crazy!

How to sort with a lambda?

To much code, you can use it like this:

#include<array>
#include<functional>

int main()
{
    std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };

    std::sort(std::begin(vec), 
              std::end(vec), 
              [](int a, int b) {return a > b; });

    for (auto item : vec)
      std::cout << item << " ";

    return 0;
}

Replace "vec" with your class and that's it.

How to process SIGTERM signal gracefully?

First, I'm not certain that you need a second thread to set the shutdown_flag.
Why not set it directly in the SIGTERM handler?

An alternative is to raise an exception from the SIGTERM handler, which will be propagated up the stack. Assuming you've got proper exception handling (e.g. with with/contextmanager and try: ... finally: blocks) this should be a fairly graceful shutdown, similar to if you were to Ctrl+C your program.

Example program signals-test.py:

#!/usr/bin/python

from time import sleep
import signal
import sys


def sigterm_handler(_signo, _stack_frame):
    # Raises SystemExit(0):
    sys.exit(0)

if sys.argv[1] == "handle_signal":
    signal.signal(signal.SIGTERM, sigterm_handler)

try:
    print "Hello"
    i = 0
    while True:
        i += 1
        print "Iteration #%i" % i
        sleep(1)
finally:
    print "Goodbye"

Now see the Ctrl+C behaviour:

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
^CGoodbye
Traceback (most recent call last):
  File "./signals-test.py", line 21, in <module>
    sleep(1)
KeyboardInterrupt
$ echo $?
1

This time I send it SIGTERM after 4 iterations with kill $(ps aux | grep signals-test | awk '/python/ {print $2}'):

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Terminated
$ echo $?
143

This time I enable my custom SIGTERM handler and send it SIGTERM:

$ ./signals-test.py handle_signal
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Goodbye
$ echo $?
0

Regular expression for a hexadecimal number?

If you are looking for an specific hex character in the middle of the string, you can use "\xhh" where hh is the character in hexadecimal. I've tried and it works. I use framework for C++ Qt but it can solve problems in other cases, depends on the flavor you need to use (php, javascript, python , golang, etc.).

This answer was taken from:http://ult-tex.net/info/perl/

Enabling HTTPS on express.js

Including Points:

  1. SSL setup
    1. In config/local.js
    2. In config/env/production.js

HTTP and WS handling

  1. The app must run on HTTP in development so we can easily debug our app.
  2. The app must run on HTTPS in production for security concern.
  3. App production HTTP request should always redirect to https.

SSL configuration

In Sailsjs there are two ways to configure all the stuff, first is to configure in config folder with each one has their separate files (like database connection regarding settings lies within connections.js ). And second is configure on environment base file structure, each environment files presents in config/env folder and each file contains settings for particular env.

Sails first looks in config/env folder and then look forward to config/ *.js

Now lets setup ssl in config/local.js.

var local = {
   port: process.env.PORT || 1337,
   environment: process.env.NODE_ENV || 'development'
};

if (process.env.NODE_ENV == 'production') {
    local.ssl = {
        secureProtocol: 'SSLv23_method',
        secureOptions: require('constants').SSL_OP_NO_SSLv3,
        ca: require('fs').readFileSync(__dirname + '/path/to/ca.crt','ascii'),
        key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key','ascii'),
        cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt','ascii')
    };
    local.port = 443; // This port should be different than your default port
}

module.exports = local;

Alternative you can add this in config/env/production.js too. (This snippet also show how to handle multiple CARoot certi)

Or in production.js

module.exports = {
    port: 443,
    ssl: {
        secureProtocol: 'SSLv23_method',
        secureOptions: require('constants').SSL_OP_NO_SSLv3,
        ca: [
            require('fs').readFileSync(__dirname + '/path/to/AddTrustExternalCARoot.crt', 'ascii'),
            require('fs').readFileSync(__dirname + '/path/to/COMODORSAAddTrustCA.crt', 'ascii'),
            require('fs').readFileSync(__dirname + '/path/to/COMODORSADomainValidationSecureServerCA.crt', 'ascii')
        ],
        key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key', 'ascii'),
        cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt', 'ascii')
    }
};

http/https & ws/wss redirection

Here ws is Web Socket and wss represent Secure Web Socket, as we set up ssl then now http and ws both requests become secure and transform to https and wss respectively.

There are many source from our app will receive request like any blog post, social media post but our server runs only on https so when any request come from http it gives “This site can’t be reached” error in client browser. And we loss our website traffic. So we must redirect http request to https, same rules allow for websocket otherwise socket will fails.

So we need to run same server on port 80 (http), and divert all request to port 443(https). Sails first compile config/bootstrap.js file before lifting server. Here we can start our express server on port 80.

In config/bootstrap.js (Create http server and redirect all request to https)

module.exports.bootstrap = function(cb) {
    var express = require("express"),
        app = express();

    app.get('*', function(req, res) {  
        if (req.isSocket) 
            return res.redirect('wss://' + req.headers.host + req.url)  

        return res.redirect('https://' + req.headers.host + req.url)  
    }).listen(80);
    cb();
};

Now you can visit http://www.yourdomain.com, it will redirect to https://www.yourdomain.com

When should I use UNSIGNED and SIGNED INT in MySQL?

If you know the type of numbers you are going to store, your can choose accordingly. In this case your have 'id' which can never be negative. So you can use unsigned int. Range of signed int: -n/2 to +n/2 Range of unsigned int: 0 to n So you have twice the number of positive numbers available. Choose accordingly.

Read connection string from web.config

I guess you need to add a reference to the System.Configuration assembly if that have not already been added.

Also, you may need to insert the following line at the top of your code file:

using System.Configuration;

TypeScript and React - children type?

In order to use <Aux> in your JSX, it needs to be a function that returns ReactElement<any> | null. That's the definition of a function component.

However, it's currently defined as a function that returns React.ReactNode, which is a much wider type. As React typings say:

type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

Make sure the unwanted types are neutralized by wrapping the returned value into React Fragment (<></>):

const aux: React.FC<AuxProps> = props =>
  <>{props.children}</>;

How to open existing project in Eclipse

Try File > New > Project... > Android Project From Existing Code. Don't copy your project from pc into workspace, copy it elsewhere and let the eclipse copy it into workspace by menu commands above and checking copy in existing workspace.

Java JDBC - How to connect to Oracle using Service Name instead of SID

In case you are using eclipse to connect oracle without SID. There are two drivers to select i.e., Oracle thin driver and other is other driver. Select other drivers and enter service name in database column. Now you can connect directly using service name without SID.

How to scanf only integer and repeat reading if the user enters non-numeric characters?

You will need to repeat your call to strtol inside your loops where you are asking the user to try again. In fact, if you make the loop a do { ... } while(...); instead of while, you don't get a the same sort of repeat things twice behaviour.

You should also format your code so that it's possible to see where the code is inside a loop and not.

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

Quick way to list all files in Amazon S3 bucket?

# find like file listing for s3 files
aws s3api --profile <<profile-name>> \
--endpoint-url=<<end-point-url>> list-objects \
--bucket <<bucket-name>> --query 'Contents[].{Key: Key}'

why is plotting with Matplotlib so slow?

To start, Joe Kington's answer provides very good advice using a gui-neutral approach, and you should definitely take his advice (especially about Blitting) and put it into practice. More info on this approach, read the Matplotlib Cookbook

However, the non-GUI-neutral (GUI-biased?) approach is key to speeding up the plotting. In other words, the backend is extremely important to plot speed.

Put these two lines before you import anything else from matplotlib:

import matplotlib
matplotlib.use('GTKAgg') 

Of course, there are various options to use instead of GTKAgg, but according to the cookbook mentioned before, this was the fastest. See the link about backends for more options.

Maximum on http header values?

As vartec says above, the HTTP spec does not define a limit, however many servers do by default. This means, practically speaking, the lower limit is 8K. For most servers, this limit applies to the sum of the request line and ALL header fields (so keep your cookies short).

It's worth noting that nginx uses the system page size by default, which is 4K on most systems. You can check with this tiny program:

pagesize.c:

#include <unistd.h>
#include <stdio.h>

int main() {
    int pageSize = getpagesize();
    printf("Page size on your system = %i bytes\n", pageSize);
    return 0;
}

Compile with gcc -o pagesize pagesize.c then run ./pagesize. My ubuntu server from Linode dutifully informs me the answer is 4k.

Export to CSV using jQuery and html

A tiny update for @Terry Young answer, i.e. add IE 10+ support

if (window.navigator.msSaveOrOpenBlob) {
  // IE 10+
  var blob = new Blob([decodeURIComponent(encodeURI(csvString))], {
    type: 'text/csv;charset=' + document.characterSet
  });
  window.navigator.msSaveBlob(blob, filename);
} else {
  // actual real browsers
  //Data URI
  csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvData);

    $(this).attr({
      'download': filename,
      'href': csvData,
      'target': '_blank'
    });
}

File input 'accept' attribute - is it useful?

It's been a few years, and Chrome at least makes use of this attribute. This attribute is very useful from a usability standpoint as it will filter out the unnecessary files for the user, making their experience smoother. However, the user can still select "all files" from the type (or otherwise bypass the filter), thus you should always validate the file where it is actually used; If you're using it on the server, validate it there before using it. The user can always bypass any client-side scripting.

C++ wait for user input

a do while loop would be a nice way to wait for the user input. Like this:

int main() 
{

 do 
 {
   cout << '\n' << "Press a key to continue...";
 } while (cin.get() != '\n');

 return 0;
}

You can also use the function system('PAUSE') but I think this is a bit slower and platform dependent

Node/Express file upload

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

npm install --save multer


in app.js

    var multer  =   require('multer');
    var storage = multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, './public/uploads');
      },
      filename: function (req, file, callback) {
        console.log(file);
        callback(null, Date.now()+'-'+file.originalname)
      }
    });

    var upload = multer({storage: storage}).single('photo');

    router.route("/storedata").post(function(req, res, next){

        upload(req, res, function(err) {
          if(err) {
            console.log('Error Occured');
            return;
          }
          var userDetail = new mongoOp.User({
            'name':req.body.name,
            'email':req.body.email,
            'mobile':req.body.mobile,
            'address':req.body.address
          });

          console.log(req.file);

          res.end('Your File Uploaded');
          console.log('Photo Uploaded');

          userDetail.save(function(err,result){
          if (err) {
            return console.log(err)
          }
          console.log('saved to database') 
        })
      })

      res.redirect('/')

    });

Expression ___ has changed after it was checked

I switched from AfterViewInit to AfterContentChecked and It worked for me.

Here is the process

  1. Add dependency in your constructor:

    constructor (private cdr: ChangeDetectorRef) {}

  2. and call your login in implemented method code here:

     ngAfterContentChecked() {
         this.cdr.detectChanges();
      // call or add here your code
     }
    

Distinct() with lambda?

You can use LambdaEqualityComparer:

var distinctValues
    = myCustomerList.Distinct(new LambdaEqualityComparer<OurType>((c1, c2) => c1.CustomerId == c2.CustomerId));


public class LambdaEqualityComparer<T> : IEqualityComparer<T>
    {
        public LambdaEqualityComparer(Func<T, T, bool> equalsFunction)
        {
            _equalsFunction = equalsFunction;
        }

        public bool Equals(T x, T y)
        {
            return _equalsFunction(x, y);
        }

        public int GetHashCode(T obj)
        {
            return obj.GetHashCode();
        }

        private readonly Func<T, T, bool> _equalsFunction;
    }

vertical-align with Bootstrap 3

I elaborated a bit on zessx's answer, in order to make it easier to use when mixing different column sizes on different screen sizes.

If you use Sass, you can add this to your scss-file:

@mixin v-col($prefix, $min-width) {
    @media (min-width: $min-width) {
        .col-#{$prefix}-v {
            display: inline-block;
            vertical-align: middle;
            float: none;
        }
    }
}

@include v-col(lg, $screen-lg);
@include v-col(md, $screen-md);
@include v-col(sm, $screen-sm);
@include v-col(xs, $screen-xs);

Which generates the following CSS (that you can use directly in your stylesheets, if you are not using Sass):

@media (min-width: 1200px) {
    .col-lg-v {
        display: inline-block;
        vertical-align: middle;
        float: none;
    }
}

@media (min-width: 992px) {
    .col-md-v {
        display: inline-block;
        vertical-align: middle;
        float: none;
    }
}

@media (min-width: 768px) {
    .col-sm-v {
        display: inline-block;
        vertical-align: middle;
        float: none;
    }
}

@media (min-width: 480px) {
    .col-xs-v {
        display: inline-block;
        vertical-align: middle;
        float: none;
    }
}

Now you can use it on your responsive columns like this:

<div class="container">
    <div class="row">
        <div class="col-sm-7 col-sm-v col-xs-12">
            <p>
                This content is vertically aligned on tablets and larger. On mobile it will expand to screen width.
            </p>
        </div><div class="col-sm-5 col-sm-v col-xs-12">
            <p>
                This content is vertically aligned on tablets and larger. On mobile it will expand to screen width.
            </p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-7 col-md-v col-sm-12">
            <p>
                This content is vertically aligned on desktops and larger. On tablets and smaller it will expand to screen width.
            </p>
        </div><div class="col-md-5 col-md-v col-sm-12">
            <p>
                This content is vertically aligned on desktops and larger. On tablets and smaller it will expand to screen width.
            </p>
        </div>
    </div>
</div>

Setting cursor at the end of any text of a textbox

Try like below... it will help you...

Some time in Window Form Focus() doesn't work correctly. So better you can use Select() to focus the textbox.

txtbox.Select(); // to Set Focus
txtbox.Select(txtbox.Text.Length, 0); //to set cursor at the end of textbox

How do I keep the screen on in my App?

Use PowerManager.WakeLock class inorder to perform this. See the following code:

import android.os.PowerManager;

public class MyActivity extends Activity {

    protected PowerManager.WakeLock mWakeLock;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle icicle) {
        setContentView(R.layout.main);

        /* This code together with the one in onDestroy() 
         * will make the screen be always on until this Activity gets destroyed. */
        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        this.mWakeLock.acquire();
    }

    @Override
    public void onDestroy() {
        this.mWakeLock.release();
        super.onDestroy();
    }
}

Use the follwing permission in manifest file :

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

Hope this will solve your problem...:)

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

Credit card payment gateway in PHP?

If you need something quick and dirty, you can just use PayPal's "Buy" buttons and drop them on your pages. These will take people off-site to PayPal where they can pay with a PayPal account or a credit card. This is free and super easy to implement.

If you want something a bit nicer where people pay on-site with their credit card, then you would want to look into one of those 3rd part payment providers. None of them (that I'm aware of) are completely free. All will have a per-transaction fee, and most will have a monthly fee as well.

Personally I've worked with Authorize.NET and PayPal Website Payments Pro. Both have great APIs and sample code that you can hook into via PHP easily enough.

How to get only time from date-time C#

You need to account for DateTime Kind too.

public static DateTime GetTime(this DateTime d)
{
    return new DateTime(d.TimeOfDay.Ticks, d.Kind);
}

What is the python "with" statement designed for?

I would suggest two interesting lectures:

  • PEP 343 The "with" Statement
  • Effbot Understanding Python's "with" statement

1. The with statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.

2. You could do something like:

with open("foo.txt") as foo_file:
    data = foo_file.read()

OR

from contextlib import nested
with nested(A(), B(), C()) as (X, Y, Z):
   do_something()

OR (Python 3.1)

with open('data') as input_file, open('result', 'w') as output_file:
   for line in input_file:
     output_file.write(parse(line))

OR

lock = threading.Lock()
with lock:
    # Critical section of code

3. I don't see any Antipattern here.
Quoting Dive into Python:

try..finally is good. with is better.

4. I guess it's related to programmers's habit to use try..catch..finally statement from other languages.

Why is __dirname not defined in node REPL?

Building on the existing answers here, you could define this in your REPL:

__dirname = path.resolve(path.dirname(''));

Or:

__dirname = path.resolve();

If no path segments are passed, path.resolve() will return the absolute path of the current working directory.


Or @Jthorpe's alternatives:

__dirname = process.cwd();
__dirname = fs.realpathSync('.');
__dirname = process.env.PWD

Java "lambda expressions not supported at this language level"

Just add compileOptions in build.gradle yours app:

android {


...

  defaultConfig {
    ...
    jackOptions {
      enabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

How to enable DataGridView sorting when user clicks on the column header?

I suggest using a DataTable.DefaultView as a DataSource. Then the line below.

foreach (DataGridViewColumn column in gridview.Columns)
    {
       column.SortMode = DataGridViewColumnSortMode.Automatic;
    }

After that the gridview itself will manage sorting(Ascending or Descending is supported.)