Programs & Examples On #Aabb

An Axis-Aligned Bounding Box (AABB) is a box aligned with the axes of a Cartesian co-ordinate frame. AABB's are commonly employed as a cheap way to approximate more complex geometries in a range of applications, including collision detection.

Spring Boot application.properties value not populating

The user "geoand" is right in pointing out the reasons here and giving a solution. But a better approach is to encapsulate your configuration into a separate class, say SystemContiguration java class and then inject this class into what ever services you want to use those fields.

Your current way(@grahamrb) of reading config values directly into services is error prone and would cause refactoring headaches if config setting name is changed.

'module' object has no attribute 'DataFrame'

Please make sure that your file name should not be panda.py or pd.py. Also, make sure that panda is there in your Lib/site-packages directory, if not that you need to install panda using below command line:

pip install pandas

if you work with proxy then try calling below in command prompt:

python.exe -m pip install pandas --proxy="YOUR_PROXY_IP:PORT"

In SQL Server, how to create while loop in select

  1. Create function that parses incoming string (say "AABBCC") as a table of strings (in particular "AA", "BB", "CC").
  2. Select IDs from your table and use CROSS APPLY the function with data as argument so you'll have as many rows as values contained in the current row's data. No need of cursors or stored procs.

Pandas DataFrame Groupby two columns and get counts

Inserting data into a pandas dataframe and providing column name.

import pandas as pd
df = pd.DataFrame([['A','C','A','B','C','A','B','B','A','A'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['Alphabet','Words']]
print(df)   #printing dataframe.

This is our printed data:

enter image description here

For making a group of dataframe in pandas and counter,
You need to provide one more column which counts the grouping, let's call that column as, "COUNTER" in dataframe.

Like this:

df['COUNTER'] =1       #initially, set that counter to 1.
group_data = df.groupby(['Alphabet','Words'])['COUNTER'].sum() #sum function
print(group_data)

OUTPUT:

enter image description here

How to pass multiple arguments in processStartInfo?

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

use /c as a cmd argument to close cmd.exe once its finish processing your commands

Remove unwanted parts from strings in a column

Try this using regular expression:

import re
data['result'] = data['result'].map(lambda x: re.sub('[-+A-Za-z]',x)

How to change the map center in Leaflet.js

For example:

map.panTo(new L.LatLng(40.737, -73.923));

Counting the number of occurences of characters in a string

public class StringTest{
public static void main(String[] args){

    String s ="aaabbbbccccccdd";
    String result="";
    StringBuilder sb = new StringBuilder(s);


    while(sb.length() != 0){
        int count = 0;
        char test = sb.charAt(0);
        while(sb.indexOf(test+"") != -1){
            sb.deleteCharAt(sb.indexOf(test+""));
            count++;
        }
        //System.out.println(test+" is repeated "+count+" number of times");
        result=result+test+count;
    }
    System.out.println(result);         
}
}

Changing capitalization of filenames in Git

Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv commands will tire quickly. To make things a bit easier this is what I do:

  1. Move all files outside of the directory to, let’s, say the desktop.
  2. Do a git add . -A to remove all files.
  3. Rename all files on the desktop to the proper capitalization.
  4. Move all the files back to the original directory.
  5. Do a git add .. Git should see that the files are renamed.

Now you can make a commit saying you have changed the file name capitalization.

Css height in percent not working

the root parent have to be in pixels if you want to work freely with percents,

<body style="margin: 0px; width: 1886px; height: 939px;">
<div id="containerA" class="containerA" style="height:65%;width:100%;">
    <div id="containerAinnerDiv" style="position: relative; background-color: aqua;width:70%;height: 80%;left:15%;top:10%;">
       <div style="height: 100%;width: 50%;float: left;"></div>
       <div style="height: 100%;width: 28%;float:left">
            <img src="img/justimage.png" style="max-width:100%;max-height:100%;">
       </div>
       <div style="height: 100%;width: 22%;float: left;"></div>
    </div>
</div>
</body>

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

Removing duplicates from a String in Java

public class StringTest {

    public static String dupRemove(String str) {

        Set<Character> s1 = new HashSet<Character>();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {

            Character c = str.charAt(i);

            if (!s1.contains(c)) {
                s1.add(c);
                sb.append(c);
            }


        }

        System.out.println(sb.toString());

        return sb.toString();

    }

    public static void main(String[] args) {

        dupRemove("AAAAAAAAAAAAAAAAA BBBBBBBB");
    }

}

memcpy() vs memmove()

I'm not entirely surprised that your example exhibits no strange behaviour. Try copying str1 to str1+2 instead and see what happens then. (May not actually make a difference, depends on compiler/libraries.)

In general, memcpy is implemented in a simple (but fast) manner. Simplistically, it just loops over the data (in order), copying from one location to the other. This can result in the source being overwritten while it's being read.

Memmove does more work to ensure it handles the overlap correctly.

EDIT:

(Unfortunately, I can't find decent examples, but these will do). Contrast the memcpy and memmove implementations shown here. memcpy just loops, while memmove performs a test to determine which direction to loop in to avoid corrupting the data. These implementations are rather simple. Most high-performance implementations are more complicated (involving copying word-size blocks at a time rather than bytes).

Convert integer into byte array (Java)

use this function it works for me

public byte[] toByteArray(int value) {
    return new byte[] {
            (byte)(value >> 24),
            (byte)(value >> 16),
            (byte)(value >> 8),
            (byte)value};
}

it translates the int into a byte value

How to avoid pressing Enter with getchar() for reading a single character only?

I like Lucas answer, but I would like to elaborate it a bit. There is a built-in function in termios.h named cfmakeraw() which man describes as:

cfmakeraw() sets the terminal to something like the "raw" mode of the
old Version 7 terminal driver: input is available character by
character, echoing is disabled, and all special processing of
terminal input and output characters is disabled. [...]

This basically does the same as what Lucas suggested and more, you can see the exact flags it sets in the man pages: termios(3).

Use case

int c = 0;
static struct termios oldTermios, newTermios;

tcgetattr(STDIN_FILENO, &oldTermios);
newTermios = oldTermios;

cfmakeraw(&newTermios);

tcsetattr(STDIN_FILENO, TCSANOW, &newTermios);
c = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldTermios);

switch (c) {
    case 113: // q
        printf("\n\n");
        exit(0);
        break;
    case 105: // i
        printf("insert\n");
        break;
    default:
        break;

Convert varchar to uniqueidentifier in SQL Server

It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.

create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
    -- just in case it came in with 0x prefix or dashes...
    set @s = replace(replace(@s,'0x',''),'-','')
    -- inject dashes in the right places
    set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
    return cast(@s as uniqueidentifier)
end

How to convert a String into an array of Strings containing one character each

String[] result = input.split("(?!^)");

What this does is split the input String on all empty Strings that are not preceded by the beginning of the String.

Regular expression that doesn't contain certain string

All you need is a reluctant quantifier:

regex: /aa.*?aa/

aabbabcaabda   => aabbabcaa

aaaaaabda      => aaaa

aabbabcaabda   => aabbabcaa

aababaaaabdaa  => aababaa, aabdaa

You could use negative lookahead, too, but in this case it's just a more verbose way accomplish the same thing. Also, it's a little trickier than gpojd made it out to be. The lookahead has to be applied at each position before the dot is allowed to consume the next character.

/aa(?:(?!aa).)*aa/

As for the approach suggested by Claudiu and finnw, it'll work okay when the sentinel string is only two characters long, but (as Claudiu acknowledged) it's too unwieldy for longer strings.

Removing multiple classes (jQuery)

The documentation says:

class (Optional) String
One or more CSS classes to remove from the elements, these are separated by spaces.

Example:

Remove the class 'blue' and 'under' from the matched elements.

$("p:odd").removeClass("blue under");

Java synchronized block vs. Collections.synchronizedMap

Collections.synchronizedMap() guarantees that each atomic operation you want to run on the map will be synchronized.

Running two (or more) operations on the map however, must be synchronized in a block. So yes - you are synchronizing correctly.

PHP code to get selected text of a combo box

You can achive this with creating new array:

<?php
$array = array(1 => "Toyota", 2 => "Nissan", 3 => "BMW");

if (isset ($_POST['search'])) {
  $maker = mysql_real_escape_string($_POST['Make']);
  echo $array[$maker];
}
?>

Postman: sending nested JSON object

In the Params I have added model.Email and model.Password, work for me well. Thanks for the question. I tried the same thing in headers did not work. But it worked on Body with form-data and x-www-form-urlencoded.

Postman version 6.4.4

enter image description here

How do I convert hh:mm:ss.000 to milliseconds in Excel?

you can do it like this:

cell[B1]: 0:04:58.727

cell[B2]: =FIND(".";B1)

cell[B3]: =LEFT(B1;B2-7)

cell[B4]: =MID(B1;11-8;2)

cell[B5]: =RIGHT(B1;6)

cell[B6]: =B3*3600000+B4*60000+B5

maybe you have to multiply B5 also with 1000.

=FIND(".";B1) is only necessary because you might have inputs like '0:04:58.727' or '10:04:58.727' with different length.

CSS force image resize and keep aspect ratio

Remove the "height" property.

<img src="big_image.jpg" width="900" alt=""/>

By specifying both you are changing the aspect ratio of the image. Just setting one will resize but preserve the aspect ratio.

Optionally, to restrict oversizings:

<img src="big_image.jpg" width="900" alt="" style="max-width:500px; height:auto; max-height:600px;"/>

How to display HTML <FORM> as inline element?

<form> cannot go inside <p>, no. The browser is going to abruptly close your <p> element when it hits the opening <form> tag as it tries to handle what it thinks is an unclosed paragraph element:

<p>Read this sentence 
 </p><form style='display:inline;'>

Java null check why use == instead of .equals()

If an Object variable is null, one cannot call an equals() method upon it, thus an object reference check of null is proper.

Oracle ORA-12154: TNS: Could not resolve service name Error?

It has nothing to do with a space embedded in the folder structure.

I had the same problem. But when I created an environmental variable (defined both at the system- and user-level) called TNS_HOME and made it to point to the folder where TNSNAMES.ORA existed, the problem was resolved. Voila!

venki

Get list of all tables in Oracle?

select * from dba_tables

gives all the tables of all the users only if the user with which you logged in is having the sysdba privileges.

How to change FontSize By JavaScript?

<span id="span">HOI</span>
<script>
   var span = document.getElementById("span");
   console.log(span);

   span.style.fontSize = "25px";
   span.innerHTML = "String";
</script>

You have two errors in your code:

  1. document.getElementById - This retrieves the element with an Id that is "span", you did not specify an id on the span-element.

  2. Capitals in Javascript - Also you forgot the capital of Size.

How do I configure different environments in Angular.js?

Have you seen this question and its answer?

You can set a globally valid value for you app like this:

app.value('key', 'value');

and then use it in your services. You could move this code to a config.js file and execute it on page load or another convenient moment.

jquery smooth scroll to an anchor?

Here is how I do it:

    var hashTagActive = "";
    $(".scroll").on("click touchstart" , function (event) {
        if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
            event.preventDefault();
            //calculate destination place
            var dest = 0;
            if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
                dest = $(document).height() - $(window).height();
            } else {
                dest = $(this.hash).offset().top;
            }
            //go to destination
            $('html,body').animate({
                scrollTop: dest
            }, 2000, 'swing');
            hashTagActive = this.hash;
        }
    });

Then you just need to create your anchor like this:

<a class="scroll" href="#destination1">Destination 1</a>

You can see it on my website.
A demo is also available here: http://jsfiddle.net/YtJcL/

git cherry-pick says "...38c74d is a merge but no -m option was given"

Simplification of @Daira Hopwood method good for picking one single commit. Need no temporary branches.

In the case of the author:

  • Z is wanted commit (fd9f578)
  • Y is commit before it
  • X current working branch

then do:

git checkout Z   # move HEAD to wanted commit
git reset Y      # have Z as changes in working tree
git stash        # save Z in stash
git checkout X   # return to working branch
git stash pop    # apply Z to current branch
git commit -a    # do commit

Cast Int to enum in Java

This is the same answer as the doctors but it shows how to eliminate the problem with mutable arrays. If you use this kind of approach because of branch prediction first if will have very little to zero effect and whole code only calls mutable array values() function only once. As both variables are static they will not consume n * memory for every usage of this enumeration too.

private static boolean arrayCreated = false;
private static RFMsgType[] ArrayOfValues;

public static RFMsgType GetMsgTypeFromValue(int MessageID) {
    if (arrayCreated == false) {
        ArrayOfValues = RFMsgType.values();
    }

    for (int i = 0; i < ArrayOfValues.length; i++) {
        if (ArrayOfValues[i].MessageIDValue == MessageID) {
            return ArrayOfValues[i];
        }
    }
    return RFMsgType.UNKNOWN;
}

How to change the status bar background color and text color on iOS 7?

If you're using a UINavigationController, you can use an extension like this:

extension UINavigationController {
    private struct AssociatedKeys {
        static var navigationBarBackgroundViewName = "NavigationBarBackground"
    }

    var navigationBarBackgroundView: UIView? {
        get {
            return objc_getAssociatedObject(self,
                                        &AssociatedKeys.navigationBarBackgroundViewName) as? UIView
        }
        set(newValue) {
             objc_setAssociatedObject(self,
                                 &AssociatedKeys.navigationBarBackgroundViewName,
                                 newValue,
                                 .OBJC_ASSOCIATION_RETAIN)
        }
    }

    func setNavigationBar(hidden isHidden: Bool, animated: Bool = false) {
       if animated {
           UIView.animate(withDuration: 0.3) {
               self.navigationBarBackgroundView?.isHidden = isHidden
           }
       } else {
           navigationBarBackgroundView?.isHidden = isHidden
       }
    }

    func setNavigationBarBackground(color: UIColor, includingStatusBar: Bool = true, animated: Bool = false) {
        navigationBarBackgroundView?.backgroundColor = UIColor.clear
        navigationBar.backgroundColor = UIColor.clear
        navigationBar.barTintColor = UIColor.clear

        let setupOperation = {
            if includingStatusBar {
                self.navigationBarBackgroundView?.isHidden = false
                if self.navigationBarBackgroundView == nil {
                    self.setupBackgroundView()
                }
                self.navigationBarBackgroundView?.backgroundColor = color
            } else {
                self.navigationBarBackgroundView?.isHidden = true
                self.navigationBar.backgroundColor = color
            }
        }

        if animated {
            UIView.animate(withDuration: 0.3) {
                setupOperation()
            }
        } else {
            setupOperation()
        }
    }

    private func setupBackgroundView() {
        var frame = navigationBar.frame
        frame.origin.y = 0
        frame.size.height = 64

        navigationBarBackgroundView = UIView(frame: frame)
        navigationBarBackgroundView?.translatesAutoresizingMaskIntoConstraints = true
        navigationBarBackgroundView?.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]

        navigationBarBackgroundView?.isUserInteractionEnabled = false

        view.insertSubview(navigationBarBackgroundView!, aboveSubview: navigationBar)
    }
}

It basically makes the navigation bar background transparent and uses another UIView as the background. You can call the setNavigationBarBackground method of your navigation controller to set the navigation bar background color together with the status bar.

Keep in mind that you have to then use the setNavigationBar(hidden: Bool, animated: Bool) method in the extension when you want to hide the navigation bar otherwise the view that was used as the background will still be visible.

Insert Update trigger how to determine if insert or update

This might be a faster way:

DECLARE @action char(1)

IF COLUMNS_UPDATED() > 0 -- insert or update
BEGIN
    IF EXISTS (SELECT * FROM DELETED) -- update
        SET @action = 'U'
    ELSE
        SET @action = 'I'
    END
ELSE -- delete
    SET @action = 'D'

Count multiple columns with group by in one query

    SELECT SUM(Output.count),Output.attr 
FROM
(
    SELECT COUNT(column1  ) AS count,column1 AS attr FROM tab1 GROUP BY column1 
    UNION ALL
    SELECT COUNT(column2) AS count,column2 AS attr FROM tab1 GROUP BY column2
    UNION ALL
    SELECT COUNT(column3) AS count,column3 AS attr FROM tab1 GROUP BY column3) AS Output

    GROUP BY attr 

How to overload __init__ method based on argument type?

Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:

Here's a sample (this is a read method and not a constructor, but the idea is the same):

def read(self, str=None, filename=None, addr=0):
    """ Read binary data and return a store object. The data
        store is also saved in the interal 'data' attribute.

        The data can either be taken from a string (str 
        argument) or a file (provide a filename, which will 
        be read in binary mode). If both are provided, the str 
        will be used. If neither is provided, an ArgumentError 
        is raised.
    """
    if str is None:
        if filename is None:
            raise ArgumentError('Please supply a string or a filename')

        file = open(filename, 'rb')
        str = file.read()
        file.close()
    ...
    ... # rest of code

The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:

obj.read(filename="blob.txt")

And to read it from a string, I say:

obj.read(str="\x34\x55")

This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex

How to view/delete local storage in Firefox?

I could not use localStorage directly in the Firefox (v27) console. I got the error:

[Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: debugger eval code :: :: line 1" data: no]

What worked was:

window.content.localStorage

Update multiple columns in SQL

I tried with this way and its working fine :

UPDATE 
  Emp
SET 
  ID = 123, 
  Name = 'Peter' 
FROM 
  Table_Name

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

Get the current language in device

Answers above don't distinguish between simple chinese and traditinal chinese. Locale.getDefault().toString() works which returns "zh_CN", "zh_TW", "en_US" and etc.

References to : https://developer.android.com/reference/java/util/Locale.html, ISO 639-1 is OLD.

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

Just for others (like me) who might have faced the above error. The solution in simple terms.

You might have missed to register your Interface and class (which implements that inteface) registration in your code.

e.g if the error is
"The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?"

Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. using code like below

 container.RegisterType<Imyinterfacename, myinterfaceimplclassname>();

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

The standard states that prompting can be controlled by canceling the beforeunload event or setting the return value to a non-null value. It also states that authors should use Event.preventDefault() instead of returnValue, and the message shown to the user is not customizable.

As of 69.0.3497.92, Chrome has not met the standard. However, there is a bug report filed, and a review is in progress. Chrome requires returnValue to be set by reference to the event object, not the value returned by the handler.

It is the author's responsibility to track whether changes have been made; it can be done with a variable or by ensuring the event is only handled when necessary.

_x000D_
_x000D_
window.addEventListener('beforeunload', function (e) {_x000D_
    // Cancel the event as stated by the standard._x000D_
    e.preventDefault();_x000D_
    // Chrome requires returnValue to be set._x000D_
    e.returnValue = '';_x000D_
});_x000D_
    _x000D_
window.location = 'about:blank';
_x000D_
_x000D_
_x000D_

How to get current foreground activity context in android?

Personally I did as "Cheok Yan Cheng" said, but I used a "List" to have a "Backstack" of all my activities.

If you want to check Which is the Current Activity you just need to get the last activity class in the list.

Create an application which extends "Application" and do this:

public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks,
EndSyncReceiver.IEndSyncCallback {

private List<Class> mActivitiesBackStack;
private EndSyncReceiver mReceiver;
    private Merlin mMerlin;
    private boolean isMerlinBound;
    private boolean isReceiverRegistered;

@Override
    public void onCreate() {
        super.onCreate();
        [....]
RealmHelper.initInstance();
        initMyMerlin();
        bindMerlin();
        initEndSyncReceiver();
        mActivitiesBackStack = new ArrayList<>();
    }

/* START Override ActivityLifecycleCallbacks Methods */
    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {
        mActivitiesBackStack.add(activity.getClass());
    }

    @Override
    public void onActivityStarted(Activity activity) {
        if(!isMerlinBound){
            bindMerlin();
        }
        if(!isReceiverRegistered){
            registerEndSyncReceiver();
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        if(!AppUtils.isAppOnForeground(this)){
            if(isMerlinBound) {
                unbindMerlin();
            }
            if(isReceiverRegistered){
                unregisterReceiver(mReceiver);
            }
            if(RealmHelper.getInstance() != null){
                RealmHelper.getInstance().close();
                RealmHelper.getInstance().logRealmInstanceCount("AppInBackground");
                RealmHelper.setMyInstance(null);
            }
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if(mActivitiesBackStack.contains(activity.getClass())){
            mActivitiesBackStack.remove(activity.getClass());
        }
    }
    /* END Override ActivityLifecycleCallbacks Methods */

/* START Override IEndSyncCallback Methods */
    @Override
    public void onEndSync(Intent intent) {
        Constants.SyncType syncType = null;
        if(intent.hasExtra(Constants.INTENT_DATA_SYNC_TYPE)){
            syncType = (Constants.SyncType) intent.getSerializableExtra(Constants.INTENT_DATA_SYNC_TYPE);
        }
        if(syncType != null){
            checkSyncType(syncType);
        }
    }
    /* END IEndSyncCallback Methods */

private void checkSyncType(Constants.SyncType){
    [...]
    if( mActivitiesBackStack.contains(ActivityClass.class) ){
         doOperation()     }
}

}

In my case I used "Application.ActivityLifecycleCallbacks" to:

  • Bind/Unbind Merlin Instance (used to get event when the app lose or get connection, for example when you close mobile data or when you open it). It is useful after the "OnConnectivityChanged" intent action was disabled. For more info about MERLIN see: MERLIN INFO LINK

  • Close my last Realm Instance when the application is closed; I will init it inside a BaseActivity wich is extended from all others activities and which has a private RealmHelper Instance. For more info about REALM see: REALM INFO LINK For instance I have a static "RealmHelper" instance inside my "RealmHelper" class which is instantiated inside my application "onCreate". I have a synchronization service in which I create I new "RealmHelper" because Realm is "Thread-Linked" and a Realm Instance can't work inside a different Thread. So in order to follow Realm Documentation "You Need To Close All Opened Realm Instances to avoid System Resources Leaks", to accomplish this thing I used the "Application.ActivityLifecycleCallbacks" as you can see up.

  • Finally I have a receiver wich is triggered when I finish to synchronize my application, then when the sync end it will call the "IEndSyncCallback" "onEndSync" method in which I look if I have a specific Activity Class inside my ActivitiesBackStack List because I need to update the data on the view if the sync updated them and I could need to do others operations after the app sync.

That's all, hope this is helpful. See u :)

ASP.NET MVC Dropdown List From SelectList

You are missing setting what field is the Text and Value in the SelectList itself. That is why it does a .ToString() on each object in the list. You could think that given it is a list of SelectListItem it should be smart enough to detect this... but it is not.

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
        new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text", 1);

BTW, you can use a list of array of any type... and then just set the name of the properties that will act as Text and Value.

I think it is better to do it like this:

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text");

I removed the -1 item, and the setting of each items selected true/false.

Then, in your view:

@Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")

This way, if you set the "Select one" item, and you don't set one item as selected in the SelectList, the UserType will be null (the UserType need to be int? ).

If you need to set one of the SelectList items as selected, you can use:

u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);

(Deep) copying an array using jQuery

If you want to use pure JavaScript then try this:

 var arr=["apple","ball","cat","dog"];
 var narr=[];

 for(var i=0;i<arr.length;i++){
     narr.push(arr[i]);
 }
 alert(narr); //output: apple,ball,vat,dog
 narr.push("elephant");
 alert(arr); // output: apple,ball,vat,dog
 alert(narr); // apple,ball,vat,dog,elephant

How can I define a composite primary key in SQL?

CREATE TABLE `voting` (
  `QuestionID` int(10) unsigned NOT NULL,
  `MemberId` int(10) unsigned NOT NULL,
  `vote` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`QuestionID`,`MemberId`)
);

Convert `List<string>` to comma-separated string

The following will result in a comma separated list. Be sure to include a using statement for System.Linq

List<string> ls = new List<string>();
ls.Add("one");
ls.Add("two");
string type = ls.Aggregate((x,y) => x + "," + y);

will yield one,two

if you need a space after the comma, simply change the last line to string type = ls.Aggregate((x,y) => x + ", " + y);

sqlplus how to find details of the currently connected database session

I know this is an old question but I did try all the above answers but didnt work in my case. What ultimately helped me out is

SHOW PARAMETER instance_name

Best way to load module/class from lib folder in Rails 3?

The magic of autoloading stuff

I think the option controlling the folders from which autoloading stuff gets done has been sufficiently covered in other answers. However, in case someone else is having trouble stuff loaded though they've had their autoload paths modified as required, then this answer tries to explain what is the magic behind this autoload thing.

So when it comes to loading stuff from subdirectories there's a gotcha or a convention you should be aware. Sometimes the Ruby/Rails magic (this time mostly Rails) can make it difficult to understand why something is happening. Any module declared in the autoload paths will only be loaded if the module name corresponds to the parent directory name. So in case you try to put into lib/my_stuff/bar.rb something like:

module Foo
  class Bar
  end
end

It will not be loaded automagically. Then again if you rename the parent dir to foo thus hosting your module at path: lib/foo/bar.rb. It will be there for you. Another option is to name the file you want autoloaded by the module name. Obviously there can only be one file by that name then. In case you need to split your stuff into many files you could of course use that one file to require other files, but I don't recommend that, because then when on development mode and you modify those other files then Rails is unable to automagically reload them for you. But if you really want you could have one file by the module name that then specifies the actual files required to use the module. So you could have two files: lib/my_stuff/bar.rb and lib/my_stuff/foo.rb and the former being the same as above and the latter containing a single line: require "bar" and that would work just the same.

P.S. I feel compelled to add one more important thing. As of lately, whenever I want to have something in the lib directory that needs to get autoloaded, I tend to start thinking that if this is something that I'm actually developing specifically for this project (which it usually is, it might some day turn into a "static" snippet of code used in many projects or a git submodule, etc.. in which case it definitely should be in the lib folder) then perhaps its place is not in the lib folder at all. Perhaps it should be in a subfolder under the app folder· I have a feeling that this is the new rails way of doing things. Obviously, the same magic is in work wherever in you autoload paths you put your stuff in so it's good to these things. Anyway, this is just my thoughts on the subject. You are free to disagree. :)


UPDATE: About the type of magic..

As severin pointed out in his comment, the core "autoload a module mechanism" sure is part of Ruby, but the autoload paths stuff isn't. You don't need Rails to do autoload :Foo, File.join(Rails.root, "lib", "my_stuff", "bar"). And when you would try to reference the module Foo for the first time then it would be loaded for you. However what Rails does is it gives us a way to try and load stuff automagically from registered folders and this has been implemented in such a way that it needs to assume something about the naming conventions. If it had not been implemented like that, then every time you reference something that's not currently loaded it would have to go through all of the files in all of the autoload folders and check if any of them contains what you were trying to reference. This in turn would defeat the idea of autoloading and autoreloading. However, with these conventions in place it can deduct from the module/class your trying to load where that might be defined and just load that.

jQuery - Get Width of Element when Not Visible (Display: None)

Before take the width make the parent display show ,then take the width and finally make the parent display hide. Just like following

$('#parent').show();
var tableWidth = $('#parent').children('table').outerWidth();
 $('#parent').hide();
if (tableWidth > $('#parent').width())
{
    $('#parent').width() = tableWidth;
}

Scanning Java annotations at runtime

The Classloader API doesn't have an "enumerate" method, because class loading is an "on-demand" activity -- you usually have thousands of classes in your classpath, only a fraction of which will ever be needed (the rt.jar alone is 48MB nowadays!).

So, even if you could enumerate all classes, this would be very time- and memory-consuming.

The simple approach is to list the concerned classes in a setup file (xml or whatever suits your fancy); if you want to do this automatically, restrict yourself to one JAR or one class directory.

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Try this query -

SELECT 
  t2.company_name,
  t2.expose_new,
  t2.expose_used,
  t1.title,
  t1.seller,
  t1.status,
  CASE status
      WHEN 'New' THEN t2.expose_new
      WHEN 'Used' THEN t2.expose_used
      ELSE NULL
  END as 'expose'
FROM
  `products` t1
JOIN manufacturers t2
  ON
    t2.id = t1.seller
WHERE
  t1.seller = 4238

"Could not find a valid gem in any repository" (rubygame and others)

If you are running behind the any firewall(if firewall blocking gem installation). just try following command it works.

 gem install --http-proxy http://username:pwd@server:port gem

Get element type with jQuery

you can use .is():

  $( "ul" ).click(function( event ) {
      var target = $( event.target );
      if ( target.is( "li" ) ) {
         target.css( "background-color", "red" );
      }
  });

see source

How can I set selected option selected in vue.js 2?

Handling the errors

You are binding properties to nothing. :required in

<select class="form-control" v-model="selected" :required @change="changeLocation">

and :selected in

<option :selected>Choose Province</option>

If you set the code like so, your errors should be gone:

<template>
  <select class="form-control" v-model="selected" :required @change="changeLocation">
    <option>Choose Province</option>
    <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
 </select>
</template>

Getting the select tags to have a default value

  1. you would now need to have a data property called selected so that v-model works. So,

    {
      data () {
        return {
          selected: "Choose Province"
        }
      }
    }
    
  2. If that seems like too much work, you can also do it like:

    <template>
      <select class="form-control" :required="true" @change="changeLocation">
       <option :selected="true">Choose Province</option>
       <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
      </select>
    </template>
    

When to use which method?

  1. You can use the v-model approach if your default value depends on some data property.

  2. You can go for the second method if your default selected value happens to be the first option.

  3. You can also handle it programmatically by doing so:

    <select class="form-control" :required="true">
      <option 
       v-for="option in options" 
       v-bind:value="option.id"
       :selected="option == '<the default value you want>'"
      >{{ option }}</option>
    </select>
    

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

Although this question has an accepted answer but I think this is a much cleaner way to achieve the desired output

<select required>
<option value="">Select</option>
<option>English</option>
<option>Spanish</option>
</select>

The required attribute in makes it mandatory to select an option from the list.

value="" inside the option tag combined with the required attribute in select tag makes selection of 'Select' option not permissible, thus achieving the required output

Method call if not null in C#

From C# 6 onwards, you can just use:

MyEvent?.Invoke();

or:

obj?.SomeMethod();

The ?. is the null-propagating operator, and will cause the .Invoke() to be short-circuited when the operand is null. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.

===

Prior to C# 6, no: there is no null-safe magic, with one exception; extension methods - for example:

public static void SafeInvoke(this Action action) {
    if(action != null) action();
}

now this is valid:

Action act = null;
act.SafeInvoke(); // does nothing
act = delegate {Console.WriteLine("hi");}
act.SafeInvoke(); // writes "hi"

In the case of events, this has the advantage of also removing the race-condition, i.e. you don't need a temporary variable. So normally you'd need:

var handler = SomeEvent;
if(handler != null) handler(this, EventArgs.Empty);

but with:

public static void SafeInvoke(this EventHandler handler, object sender) {
    if(handler != null) handler(sender, EventArgs.Empty);
}

we can use simply:

SomeEvent.SafeInvoke(this); // no race condition, no null risk

What __init__ and self do in Python?

Just a demo for the question.

class MyClass:

    def __init__(self):
        print('__init__ is the constructor for a class')

    def __del__(self):
        print('__del__ is the destructor for a class')

    def __enter__(self):
        print('__enter__ is for context manager')
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print('__exit__ is for context manager')

    def greeting(self):
        print('hello python')


if __name__ == '__main__':
    with MyClass() as mycls:
        mycls.greeting()

$ python3 class.objects_instantiation.py
__init__ is the constructor for a class
__enter__ is for context manager
hello python
__exit__ is for context manager
__del__ is the destructor for a class

How to set tbody height with overflow scroll

Change your second table code like below.

<table style="border: 1px solid red;width:300px;display:block;">
<thead>
    <tr>
        <td width=150>Name</td>
        <td width=150>phone</td>
    </tr>
</thead>
<tbody style='height:50px;overflow:auto;display:block;width:317px;'>
    <tr>
        <td width=150>AAAA</td>
        <td width=150>323232</td>
    </tr>
    <tr>
        <td>BBBBB</td>
        <td>323232</td>
    </tr>
    <tr>
        <td>CCCCC</td>
        <td>3435656</td>
    </tr>
</tbody>
</table>

JSFIDDLE DEMO

How to convert C++ Code to C

While you can do OO in C (e.g. by adding a theType *this first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).

I would suggest at least looking at a re-design to compare how this would work out.

Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

Is there a standardized method to swap two variables in Python?

I would not say it is a standard way to swap because it will cause some unexpected errors.

nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]

nums[i] will be modified first and then affect the second variable nums[nums[i] - 1].

typedef struct vs struct definitions

The following code creates an anonymous struct with the alias myStruct:

typedef struct{
    int one;
    int two;
} myStruct;

You can't refer it without the alias because you don't specify an identifier for the structure.

Adding images or videos to iPhone Simulator

3 Simple Steps

  1. Drag & Drop image onto simulator
    - this will open a browser with your image
  2. Click & hold image
    - this will open options
  3. save image
    - this will copy image onto simulator

Watch YouTube Video ( add images to iphone simulator)

Python dictionary: are keys() and values() always the same order?

For what it's worth, some heavy used production code I have written is based on this assumption and I never had a problem with it. I know that doesn't make it true though :-)

If you don't want to take the risk I would use iteritems() if you can.

for key, value in myDictionary.iteritems():
    print key, value

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

I would point a beginner to the Wiki article on the Main function, then supplement it with this.

  • Java only starts running a program with the specific public static void main(String[] args) signature, and one can think of a signature like their own name - it's how Java can tell the difference between someone else's main() and the one true main().

  • String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.

Prevent form submission on Enter key press

A little simple

Don't send the form on keypress "Enter":

<form id="form_cdb" onsubmit="return false">

Execute the function on keypress "Enter":

<input type="text" autocomplete="off" onkeypress="if(event.key === 'Enter') my_event()">

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

For me, it was the missing 'web.config' file. After adding it to the deployed project directory in asp net core 3.1 app, the problem was solved.

Use VBA to Clear Immediate Window?

or even more simple

Sub clearDebugConsole()
    For i = 0 To 100
        Debug.Print ""
    Next i
End Sub

What is a callback in java

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

Paul Jakubik, Callback Implementations in C++.

Access camera from a browser

The HTML5 spec does allow accessing the webcamera, but last I checked, it is far from finalized, and has very, very little browser support.

This is a link to get you started: http://www.html5rocks.com/en/tutorials/getusermedia/intro/

You'll probably have to use flash if you want it to work cross-browser.

W3 draft

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

Find a class somewhere inside dozens of JAR files?

A bit late to the party, but nevertheless...

I've been using JarBrowser to find in which jar a particular class is present. It's got an easy to use GUI which allows you to browse through the contents of all the jars in the selected path.

Move a view up only when the keyboard covers an input field

Here's my version after reading the documentation provided by Apple and the previous posts. One thing I noticed is that the textView was not handled when covered by the keyboard. Unfortunately, Apple's documentation won't work because, for whatever reason, the keyboard is called AFTER the textViewDidBeginEditing is called. I handled this by calling a central method that checks if the keyboard is displayed AND if a textView or textField is being edited. This way, the process is only fired when BOTH conditions exists.

Another point with textViews is that their height may be such that the keyboard clips the bottom of the textView and would not adjust if the Top-Left point of the was in view. So, the code I wrote actually takes the screen-referenced Bottom-Left point of any textView or textField and sees if it falls in the screen-referenced coordinates of the presented keyboard implying that the keyboard covers some portion of it.

let aRect : CGRect = scrollView.convertRect(activeFieldRect!, toView: nil)
    if (CGRectContainsPoint(keyboardRect!, CGPointMake(aRect.origin.x, aRect.maxY))) {
        // scroll textView/textField into view
    }

If you're using a navigation controller, the subclass also sets the scroll view automatic adjustment for insets to false.

self.automaticallyAdjustsScrollViewInsets = false

It walks through each textView and textField to set delegates for handling

    for view in self.view.subviews {
        if view is UITextView {
            let tv = view as! UITextView
            tv.delegate = self
        } else if view is UITextField {
            let tf = view as! UITextField
            tf.delegate = self
        }
    }

Simply set your base class to the subclass created here for results.

import UIKit

class ScrollingFormViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate {

var activeFieldRect: CGRect?
var keyboardRect: CGRect?
var scrollView: UIScrollView!

override func viewDidLoad() {

    self.automaticallyAdjustsScrollViewInsets = false

    super.viewDidLoad()

    // Do any additional setup after loading the view.
    self.registerForKeyboardNotifications()
    for view in self.view.subviews {
        if view is UITextView {
            let tv = view as! UITextView
            tv.delegate = self
        } else if view is UITextField {
            let tf = view as! UITextField
            tf.delegate = self
        }
    }
    scrollView = UIScrollView(frame: self.view.frame)
    scrollView.scrollEnabled = false
    scrollView.showsVerticalScrollIndicator = false
    scrollView.showsHorizontalScrollIndicator = false
    scrollView.addSubview(self.view)
    self.view = scrollView
}

override func viewDidLayoutSubviews() {
    scrollView.sizeToFit()
    scrollView.contentSize = scrollView.frame.size
    super.viewDidLayoutSubviews()
}

deinit {
    self.deregisterFromKeyboardNotifications()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func registerForKeyboardNotifications()
{
    //Adding notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ScrollingFormViewController.keyboardWasShown), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ScrollingFormViewController.keyboardWillBeHidden), name: UIKeyboardWillHideNotification, object: nil)
}


func deregisterFromKeyboardNotifications()
{
    //Removing notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWasShown(notification: NSNotification)
{
    let info : NSDictionary = notification.userInfo!
    keyboardRect = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
    adjustForKeyboard()
}


func keyboardWillBeHidden(notification: NSNotification)
{
    keyboardRect = nil
    adjustForKeyboard()
}

func adjustForKeyboard() {
    if keyboardRect != nil && activeFieldRect != nil {
        let aRect : CGRect = scrollView.convertRect(activeFieldRect!, toView: nil)
        if (CGRectContainsPoint(keyboardRect!, CGPointMake(aRect.origin.x, aRect.maxY)))
        {
            scrollView.scrollEnabled = true
            let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardRect!.size.height, 0.0)
            scrollView.contentInset = contentInsets
            scrollView.scrollIndicatorInsets = contentInsets
            scrollView.scrollRectToVisible(activeFieldRect!, animated: true)
        }
    } else {
        let contentInsets : UIEdgeInsets = UIEdgeInsetsZero
        scrollView.contentInset = contentInsets
        scrollView.scrollIndicatorInsets = contentInsets
        scrollView.scrollEnabled = false
    }
}

func textViewDidBeginEditing(textView: UITextView) {
    activeFieldRect = textView.frame
    adjustForKeyboard()
}

func textViewDidEndEditing(textView: UITextView) {
    activeFieldRect = nil
    adjustForKeyboard()
}

func textFieldDidBeginEditing(textField: UITextField)
{
    activeFieldRect = textField.frame
    adjustForKeyboard()
}

func textFieldDidEndEditing(textField: UITextField)
{
    activeFieldRect = nil
    adjustForKeyboard()
}

}

How to pass variables from one php page to another without form?

If you are trying to access the variable from another PHP file directly, you can include that file with include() or include_once(), giving you access to that variable. Note that this will include the entire first file in the second file.

Why does Java have transient fields?

transient is used to indicate that a class field doesn't need to be serialized. Probably the best example is a Thread field. There's usually no reason to serialize a Thread, as its state is very 'flow specific'.

How do I put two increment statements in a C++ 'for' loop?

for (int i = 0; i != 5; ++i, ++j) 
    do_something(i, j);

What is a good regular expression to match a URL?

Regex if you want to ensure URL starts with HTTP/HTTPS:

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

If you do not require HTTP protocol:

[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

To try this out see http://regexr.com?37i6s, or for a version which is less restrictive http://regexr.com/3e6m0.

Example JavaScript implementation:

_x000D_
_x000D_
var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;_x000D_
var regex = new RegExp(expression);_x000D_
var t = 'www.google.com';_x000D_
_x000D_
if (t.match(regex)) {_x000D_
  alert("Successful match");_x000D_
} else {_x000D_
  alert("No match");_x000D_
}
_x000D_
_x000D_
_x000D_

Selecting fields from JSON output

Assuming you are dealing with a JSON-string in the input, you can parse it using the json package, see the documentation.

In the specific example you posted you would need

x = json.loads("""{
 "accountWide": true,
 "criteria": [
     {
         "description": "some description",
         "id": 7553,
         "max": 1,
         "orderIndex": 0
     }
  ]
 }""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']

CSS white space at bottom of page despite having both min-height and height tag

I find it quite remarkable that out of 6 answers, none of them have mentioned the real source of the problem.

Collapsing margins on the last p inside #fw-footer is where that extra space is originating from.

A sensible fix would be to add overflow: hidden to #fw-footer (or simply add margin: 0 on the last p).

You could also just move the script inside that last p outside of the p, and then remove the p entirely; there's no need to wrap a script in a p. The first p (#fw-foottext) has margin: 0 applied, so the problem won't happen with that one.


As an aside, you've broken the fix I gave you in this question:

CSS3 gradient background with unwanted white space at bottom

You need html { height: 100% } and body { min-height: 100% }.

At the moment, you have html { height: auto } being applied, which does not work:

(This happens with a window taller than the content on the page)

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Another option is to get a ".pem" (public key) file for that particular server, and install it locally into the heart of your JRE's "cacerts" file (use the keytool helper application), then it will be able to download from that server without complaint, without compromising the entire SSL structure of your running JVM and enabling download from other unknown cert servers...

WP -- Get posts by category?

add_shortcode( 'seriesposts', 'series_posts' );

function series_posts( $atts )
{ ob_start();

$myseriesoption = get_option( '_myseries', null );

$type = $myseriesoption;
$args=array(  'post_type' => $type,  'post_status' => 'publish',  'posts_per_page' => 5,  'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>'; 
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>'; 
endwhile;
echo '</ul>'; 
}
wp_reset_query();




return ob_get_clean(); }

//this will generate a shortcode function to be used on your site [seriesposts]

SELECT * FROM multiple tables. MySQL

In order to get rid of duplicates, you can group by drinks.id. But that way you'll get only one photo for each drinks.id (which photo you'll get depends on database internal implementation).

Though it is not documented, in case of MySQL, you'll get the photo with lowest id (in my experience I've never seen other behavior).

SELECT name, price, photo 
FROM drinks, drinks_photos 
WHERE drinks.id = drinks_id
GROUP BY drinks.id

jQuery selector for id starts with specific text

Use jquery starts with attribute selector

$('[id^=editDialog]')

Alternative solution - 1 (highly recommended)

A cleaner solution is to add a common class to each of the divs & use

$('.commonClass').

But you can use the first one if html markup is not in your hands & cannot change it for some reason.

Alternative solution - 2 (not recommended if n is a large number) (as per @Mihai Stancu's suggestion)

$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')

Note: If there are 2 or 3 selectors and if the list doesn't change, this is probably a viable solution but it is not extensible because we have to update the selectors when there is a new ID in town.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Thanks Friend, i got an answer. This is only possible because of your help. you all give me a ray of hope towards resolving this problem.

Here is the code:

package facebook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Facebook {
    public static void main(String args[]){
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.facebook.com");
        WebElement email= driver.findElement(By.id("email"));
        Actions builder = new Actions(driver);
        Actions seriesOfActions = builder.moveToElement(email).click().sendKeys(email, "[email protected]");
        seriesOfActions.perform();
        WebElement pass = driver.findElement(By.id("pass"));
        WebElement login =driver.findElement(By.id("u_0_b"));
        Actions seriesOfAction = builder.moveToElement(pass).click().sendKeys(pass, "naveench").click(login);
        seriesOfAction.perform();
        driver.
    }    
}

Is there a simple, elegant way to define singletons?

I'm very unsure about this, but my project uses 'convention singletons' (not enforced singletons), that is, if I have a class called DataController, I define this in the same module:

_data_controller = None
def GetDataController():
    global _data_controller
    if _data_controller is None:
        _data_controller = DataController()
    return _data_controller

It is not elegant, since it's a full six lines. But all my singletons use this pattern, and it's at least very explicit (which is pythonic).

Executing multi-line statements in the one-line command-line?

single/double quotes and backslash everywhere:

$ python -c 'exec("import sys\nfor i in range(10): print \"bob\"")'

Much better:

$ python -c '
> import sys
> for i in range(10):
>   print "bob"
> '

Matching a space in regex

I am using a regex to make sure that I only allow letters, number and a space

Then it is as simple as adding a space to what you've already got:

$newtag = preg_replace("/[^a-zA-Z0-9 ]/", "", $tag);

(note, I removed the s| which seemed unintentional? Certainly the s was redundant; you can restore the | if you need it)

If you specifically want *a* space, as in only a single one, you will need a more complex expression than this, and might want to consider a separate non-regex piece of logic.

How to get all checked checkboxes

In IE9+, Chrome or Firefox you can do:

var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');

How to check for the type of a template parameter?

In C++17, we can use variants.

To use std::variant, you need to include the header:

#include <variant>

After that, you may add std::variant in your code like this:

using Type = std::variant<Animal, Person>;

template <class T>
void foo(Type type) {
    if (std::is_same_v<type, Animal>) {
        // Do stuff...
    } else {
        // Do stuff...
    }
}

Git push rejected after feature branch rebase

For me following easy steps works:

1. git checkout myFeature
2. git rebase master
3. git push --force-with-lease
4. git branch -f master HEAD
5. git checkout master
6. git pull

After doing all above, we can delete myFeature branch as well by following command:

git push origin --delete myFeature

Replacing spaces with underscores in JavaScript?

Just using replace:

_x000D_
_x000D_
var text = 'Hello World';_x000D_
    _x000D_
new_text = text.replace(' ', '_');_x000D_
    _x000D_
console.log(new_text);
_x000D_
_x000D_
_x000D_

How might I convert a double to the nearest integer value?

Use Math.round(), possibly in conjunction with MidpointRounding.AwayFromZero

eg:

Math.Round(1.2) ==> 1
Math.Round(1.5) ==> 2
Math.Round(2.5) ==> 2
Math.Round(2.5, MidpointRounding.AwayFromZero) ==> 3

How to run a cronjob every X minutes?

2 steps to check if a cronjob is working :

  1. Login on the server with the user that execute the cronjob
  2. Manually run php command :

    /usr/bin/php /mydomain.in/cromail.php

And check if any error is displayed

grabbing first row in a mysql query only

You can get the total number of rows containing a specific name using:

SELECT COUNT(*) FROM tbl_foo WHERE name = 'sarmen'

Given the count, you can now get the nth row using:

SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT (n - 1), 1

Where 1 <= n <= COUNT(*) from the first query.

Example:

getting the 3rd row

SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT 2, 1

Is there a CSS selector by class prefix?

It's not doable with CSS2.1, but it is possible with CSS3 attribute substring-matching selectors (which are supported in IE7+):

div[class^="status-"], div[class*=" status-"]

Notice the space character in the second attribute selector. This picks up div elements whose class attribute meets either of these conditions:

  • [class^="status-"] — starts with "status-"

  • [class*=" status-"] — contains the substring "status-" occurring directly after a space character. Class names are separated by whitespace per the HTML spec, hence the significant space character. This checks any other classes after the first if multiple classes are specified, and adds a bonus of checking the first class in case the attribute value is space-padded (which can happen with some applications that output class attributes dynamically).

Naturally, this also works in jQuery, as demonstrated here.

The reason you need to combine two attribute selectors as described above is because an attribute selector such as [class*="status-"] will match the following element, which may be undesirable:

<div id='D' class='foo-class foo-status-bar bar-class'></div>

If you can ensure that such a scenario will never happen, then you are free to use such a selector for the sake of simplicity. However, the combination above is much more robust.

If you have control over the HTML source or the application generating the markup, it may be simpler to just make the status- prefix its own status class instead as Gumbo suggests.

Creating a dictionary from a CSV file

You need a Python DictReader class. More help can be found from here

import csv

with open('file_name.csv', 'rt') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print row

Passing two command parameters using a WPF binding

This task can also be solved with a different approach. Instead of programming a converter and enlarging the code in the XAML, you can also aggregate the various parameters in the ViewModel. As a result, the ViewModel then has one more property that contains all parameters.

An example of my current application, which also let me deal with the topic. A generic RelayCommand is required: https://stackoverflow.com/a/22286816/7678085

The ViewModelBase is extended here by a command SaveAndClose. The generic type is a named tuple that represents the various parameters.

public ICommand SaveAndCloseCommand => saveAndCloseCommand ??= new RelayCommand<(IBaseModel Item, Window Window)>
    (execute =>
    {
        execute.Item.Save();
        execute.Window?.Close(); // if NULL it isn't closed.
    },
    canExecute =>
    {
        return canExecute.Item?.IsItemValide ?? false;
    });
private ICommand saveAndCloseCommand;

Then it contains a property according to the generic type:

public (IBaseModel Item, Window Window) SaveAndCloseParameter 
{ 
    get => saveAndCloseParameter ; 
    set 
    {
        SetProperty(ref saveAndCloseParameter, value);
    }
}
private (IBaseModel Item, Window Window) saveAndCloseParameter;

The XAML code of the view then looks like this: (Pay attention to the classic click event)

<Button 
    Command="{Binding SaveAndCloseCommand}" 
    CommandParameter="{Binding SaveAndCloseParameter}" 
    Click="ButtonApply_Click" 
    Content="Apply"
    Height="25" Width="100" />
<Button 
    Command="{Binding SaveAndCloseCommand}" 
    CommandParameter="{Binding SaveAndCloseParameter}" 
    Click="ButtonSave_Click" 
    Content="Save"
    Height="25" Width="100" />

and in the code behind of the view, then evaluating the click events, which then set the parameter property.

private void ButtonApply_Click(object sender, RoutedEventArgs e)
{
    computerViewModel.SaveAndCloseParameter = (computerViewModel.Computer, null);
}

private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
    computerViewModel.SaveAndCloseParameter = (computerViewModel.Computer, this);
}

Personally, I think that using the click events is not a break with the MVVM pattern. The program flow control is still located in the area of ??the ViewModel.

How can I make a time delay in Python?

There are five methods which I know: time.sleep(), pygame.time.wait(), matplotlib's pyplot.pause(), .after(), and asyncio.sleep().


time.sleep() example (do not use if using tkinter):

import time
print('Hello')
time.sleep(5) # Number of seconds
print('Bye')

pygame.time.wait() example (not recommended if you are not using the pygame window, but you could exit the window instantly):

import pygame
# If you are going to use the time module
# don't do "from pygame import *"
pygame.init()
print('Hello')
pygame.time.wait(5000) # Milliseconds
print('Bye')

matplotlib's function pyplot.pause() example (not recommended if you are not using the graph, but you could exit the graph instantly):

import matplotlib
print('Hello')
matplotlib.pyplot.pause(5) # Seconds
print('Bye')

The .after() method (best with Tkinter):

import tkinter as tk # Tkinter for Python&nbsp;2
root = tk.Tk()
print('Hello')
def ohhi():
    print('Oh, hi!')
root.after(5000, ohhi) # Milliseconds and then a function
print('Bye')

Finally, the asyncio.sleep() method:

import asyncio
asyncio.sleep(5)

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

Based on the documentation the origin parameter is optional and it defaults to the user's location.

... Defaults to most relevant starting location, such as user location, if available. If none, the resulting map may provide a blank form to allow a user to enter the origin....

ex: https://www.google.com/maps/dir/?api=1&destination=Pike+Place+Market+Seattle+WA&travelmode=bicycling

For me this works on Desktop, IOS and Android.

How to specify Memory & CPU limit in docker compose version 3

I know the topic is a bit old and seems stale, but anyway I was able to use these options:

    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M

when using 3.7 version of docker-compose

What helped in my case, was using this command:

docker-compose --compatibility up

--compatibility flag stands for (taken from the documentation):

If set, Compose will attempt to convert deploy keys in v3 files to their non-Swarm equivalent

Think it's great, that I don't have to revert my docker-compose file back to v2.

Gather multiple sets of columns

In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract, the following code replicates the extract(...) line in Hadleys' answer:

df %>% 
    gather(question_number, value, starts_with("Q3.")) %>%
    mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
    select(id, time, loop_number, question_number, value) %>% 
    spread(key = question_number, value = value)

The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate in my original solution in the comments to split this column into two columns with equivalent info, a loop_number column and a question_number column. spread can then be used to transform the long form data, which are key value pairs (question_number, value) to wide form data.

Removing Java 8 JDK from Mac

I was able to unistall jdk 8 in mavericks successfully doing the following steps:

Run this command to just remove the JDK

sudo rm -rf /Library/Java/JavaVirtualMachines/jdk<version>.jdk

Run these commands if you want to remove plugins

sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/PrivilegedHelperTools/com.oracle.java.JavaUpdateHelper
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.Helper-Tool.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "https://maven.fabric.io/public" }
}

Detail:

You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'
}

Blog

Press enter in textbox to and execute button command

there you go.

private void YurTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            YourButton_Click(this, new EventArgs());
        }
    }

Regex match digits, comma and semicolon?

You are 90% of the way there.

^[0-9,;]+$

Starting with the carat ^ indicates a beginning of line.

The [ indicates a character set

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ;.

The closing ] indicates the end of the character set.

The plus + indicates that one or more of the "previous item" must be present. In this case it means that you must have one or more of the characters in the previously declared character set.

The dollar $ indicates the end of the line.

Calculate the number of business days between two dates?

Here's another example you can choose the weekend dates as well,

  public int GetBuisnessDays(DateTime StartDate, DateTime EndDate)
    {
        int counter = 0;

        if (StartDate.Date == EndDate.Date)
        {
            if (StartDate.DayOfWeek != DayOfWeek.Saturday && StartDate.DayOfWeek != DayOfWeek.Friday)
                return 1;
            return 0;
        }

        while (StartDate <= EndDate)
        {
            if (StartDate.DayOfWeek != DayOfWeek.Saturday && StartDate.DayOfWeek != DayOfWeek.Friday)
                ++counter;
            StartDate = StartDate.AddDays(1);
        }

        return counter;
    }

Android Button setOnClickListener Design

Implement OnClickListener() on your Activity...

public class MyActivity extends Activity implements View.OnClickListener {
}

For each button use...

buttonX.setOnClickListener(this);

In your Activity onClick() method test for which button it is...

@Override
public void onClick(View view) {
    if (View.equals(buttonX))
        // Do something
}

Also in onClick you could use view.getId() to get the resource ID and then use that in a switch/case block to identify each button and perform the relevant action.

how to get param in method post spring mvc?

  1. Spring annotations will work fine if you remove enctype="multipart/form-data".

    @RequestParam(value="txtEmail", required=false)
    
  2. You can even get the parameters from the request object .

    request.getParameter(paramName);
    
  3. Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.

  4. Configure the Multi-part resolver if you want to receive enctype="multipart/form-data".

    <bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="250000"/>
    </bean>
    

Refer the Spring documentation.

PostgreSQL return result set as JSON array?

TL;DR

SELECT json_agg(t) FROM t

for a JSON array of objects, and

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )
FROM t

for a JSON object of arrays.

List of objects

This section describes how to generate a JSON array of objects, with each row being converted to a single object. The result looks like this:

[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a":3,"b":"value3"}]

9.3 and up

The json_agg function produces this result out of the box. It automatically figures out how to convert its input into JSON and aggregates it into an array.

SELECT json_agg(t) FROM t

There is no jsonb (introduced in 9.4) version of json_agg. You can either aggregate the rows into an array and then convert them:

SELECT to_jsonb(array_agg(t)) FROM t

or combine json_agg with a cast:

SELECT json_agg(t)::jsonb FROM t

My testing suggests that aggregating them into an array first is a little faster. I suspect that this is because the cast has to parse the entire JSON result.

9.2

9.2 does not have the json_agg or to_json functions, so you need to use the older array_to_json:

SELECT array_to_json(array_agg(t)) FROM t

You can optionally include a row_to_json call in the query:

SELECT array_to_json(array_agg(row_to_json(t))) FROM t

This converts each row to a JSON object, aggregates the JSON objects as an array, and then converts the array to a JSON array.

I wasn't able to discern any significant performance difference between the two.

Object of lists

This section describes how to generate a JSON object, with each key being a column in the table and each value being an array of the values of the column. It's the result that looks like this:

{"a":[1,2,3], "b":["value1","value2","value3"]}

9.5 and up

We can leverage the json_build_object function:

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )
FROM t

You can also aggregate the columns, creating a single row, and then convert that into an object:

SELECT to_json(r)
FROM (
    SELECT
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

Note that aliasing the arrays is absolutely required to ensure that the object has the desired names.

Which one is clearer is a matter of opinion. If using the json_build_object function, I highly recommend putting one key/value pair on a line to improve readability.

You could also use array_agg in place of json_agg, but my testing indicates that json_agg is slightly faster.

There is no jsonb version of the json_build_object function. You can aggregate into a single row and convert:

SELECT to_jsonb(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Unlike the other queries for this kind of result, array_agg seems to be a little faster when using to_jsonb. I suspect this is due to overhead parsing and validating the JSON result of json_agg.

Or you can use an explicit cast:

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )::jsonb
FROM t

The to_jsonb version allows you to avoid the cast and is faster, according to my testing; again, I suspect this is due to overhead of parsing and validating the result.

9.4 and 9.3

The json_build_object function was new to 9.5, so you have to aggregate and convert to an object in previous versions:

SELECT to_json(r)
FROM (
    SELECT
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

or

SELECT to_jsonb(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

depending on whether you want json or jsonb.

(9.3 does not have jsonb.)

9.2

In 9.2, not even to_json exists. You must use row_to_json:

SELECT row_to_json(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Documentation

Find the documentation for the JSON functions in JSON functions.

json_agg is on the aggregate functions page.

Design

If performance is important, ensure you benchmark your queries against your own schema and data, rather than trust my testing.

Whether it's a good design or not really depends on your specific application. In terms of maintainability, I don't see any particular problem. It simplifies your app code and means there's less to maintain in that portion of the app. If PG can give you exactly the result you need out of the box, the only reason I can think of to not use it would be performance considerations. Don't reinvent the wheel and all.

Nulls

Aggregate functions typically give back NULL when they operate over zero rows. If this is a possibility, you might want to use COALESCE to avoid them. A couple of examples:

SELECT COALESCE(json_agg(t), '[]'::json) FROM t

Or

SELECT to_jsonb(COALESCE(array_agg(t), ARRAY[]::t[])) FROM t

Credit to Hannes Landeholm for pointing this out

Codesign error: Provisioning profile cannot be found after deleting expired profile

I just encountered this problem in my Xcode 4. To fix it, you need to put all the correct provisions into both Debug and Release config.

I was trying to submit (by archiving) my app. So I just change the Debug provisions to "Don't Code Sign", and the Release provision to my app's appstore provision.

This fix it and enables me to archive normally. Hope that helps.

No numeric types to aggregate - change in groupby() behaviour?

How are you generating your data?

See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.

In [31]: data
Out[31]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)

look ?


Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float).

You can also call frame.astype(float)

Docker: Copying files from Docker container to host

docker cp containerId:source_path destination_path

containerId can be obtained from the command docker ps -a

source path should be absolute. for example, if the application/service directory starts from the app in your docker container the path would be /app/some_directory/file

example : docker cp d86844abc129:/app/server/output/server-test.png C:/Users/someone/Desktop/output

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

My problem was with TIMEZONE in emulator genymotion. Change TIMEZONE ANDROID EMULATOR equal TIMEZONE SERVER, solved problem.

reference

What is the difference between max-device-width and max-width for mobile web?

max-width is the width of the target display area, e.g. the browser; max-device-width is the width of the device's entire rendering area, i.e. the actual device screen.

• If you are using the max-device-width, when you change the size of the browser window on your desktop, the CSS style won't change to different media query setting;

• If you are using the max-width, when you change the size of the browser on your desktop, the CSS will change to different media query setting and you might be shown with the styling for mobiles, such as touch-friendly menus.

Separators for Navigation

Simply use the separator image as a background image on the li.

To get it to only appear in between list items, position the image to the left of the li, but not on the first one.

For example:

#nav li + li {
    background:url('seperator.gif') no-repeat top left;
    padding-left: 10px
}

This CSS adds the image to every list item that follows another list item - in other words all of them but the first.

NB. Be aware the adjacent selector (li + li) doesn't work in IE6, so you will have to just add the background image to the conventional li (with a conditional stylesheet) and perhaps apply a negative margin to one of the edges.

Why call super() in a constructor?

A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.

When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.

Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.

As a side note, some say that it's generally best to make that call manually for reasons of clarity.

In what cases do I use malloc and/or new?

The new and delete operators can operate on classes and structures, whereas malloc and free only work with blocks of memory that need to be cast.

Using new/delete will help to improve your code as you will not need to cast allocated memory to the required data structure.

Creating multiline strings in JavaScript

This is one fairly economical approach, at least in terms of the source code:

function s() {
    var args = [],index;
    for (index = 0; index< arguments.length; index++) {
        args.push (arguments [index]);
    }
    return args.join ("\n");
}
console.log (s (
    "This is the first line",
    "and this is the second",
    "finally a third"
));

function s() {return arguments.join ("\n")} 

would be nicer of course if the "arguments" property were a proper array.

A second version might use "" to do the join for cases when you want to control the line breaks in a very long string.

addClass and removeClass in jQuery - not removing class

I think that the problem is in the nesting of the elements. Once you attach an event to the outer element the clicks on the inner elements are actually firing the same click event for the outer element. So, you actually never go to the second state. What you can do is to check the clicked element. And if it is the close button then to avoid the class changing. Here is my solution:

var element = $(".clickable");
var closeButton = element.find(".close_button");
var onElementClick = function(e) {
    if(e.target !== closeButton[0]) {
        element.removeClass("spot").addClass("grown");
        element.off("click");
        closeButton.on("click", onCloseClick);
    }
}
var onCloseClick = function() {
    element.removeClass("grown").addClass("spot");
    closeButton.off("click");
    element.on("click", onElementClick);
}
element.on("click", onElementClick);

In addition I'm adding and removing event handlers.

JSFiddle -> http://jsfiddle.net/zmw9E/1/

How to get first 5 characters from string

An alternative way to get only one character.

$str = 'abcdefghij';
echo $str{5};

I would particularly not use this, but for the purpose of education. We can use that to answer the question:

$newString = '';
for ($i = 0; $i < 5; $i++) {
    $newString .= $str{$i};
}
echo $newString;

For anyone using that. Bear in mind curly brace syntax for accessing array elements and string offsets is deprecated from PHP 7.4

More information: https://wiki.php.net/rfc/deprecate_curly_braces_array_access

How to remove illegal characters from path and filenames?

I absolutely prefer the idea of Jeff Yates. It will work perfectly, if you slightly modify it:

string regex = String.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars())));
Regex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);

The improvement is just to escape the automaticially generated regex.

C# listView, how do I add items to columns 2, 3 and 4 etc?

One line that i've made and it works:

listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = randomArray["maintext"], SubItems = { randomArray["columntext2"], randomArray["columntext3"] } });

Apply function to each element of a list

Sometimes you need to apply a function to the members of a list in place. The following code worked for me:

>>> def func(a, i):
...     a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']

Please note, the output of map() is passed to the list constructor to ensure the list is converted in Python 3. The returned list filled with None values should be ignored, since our purpose was to convert list a in place

What is the difference between the HashMap and Map objects in Java?

In your second example the "map" reference is of type Map, which is an interface implemented by HashMap (and other types of Map). This interface is a contract saying that the object maps keys to values and supports various operations (e.g. put, get). It says nothing about the implementation of the Map (in this case a HashMap).

The second approach is generally preferred as you typically wouldn't want to expose the specific map implementation to methods using the Map or via an API definition.

How should I store GUID in MySQL tables?

if you have a char/varchar value formatted as the standard GUID, you can simply store it as BINARY(16) using the simple CAST(MyString AS BINARY16), without all those mind-boggling sequences of CONCAT + SUBSTR.

BINARY(16) fields are compared/sorted/indexed much faster than strings, and also take two times less space in the database

Remove element by id

// http://javascript.crockford.com/memory/leak.html
// cleans dom element to prevent memory leaks
function domPurge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        for (i = a.length - 1; i >= 0; i -= 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            domPurge(d.childNodes[i]);
       }
    }
}

function domRemove(id) {
    var elem = document.getElementById(id);
    domPurge(elem);
    return elem.parentNode.removeChild(elem);
}

Fastest way to determine if record exists

I've used this in the past and it doesn't require a full table scan to see if something exists. It's super fast...

UPDATE TableName SET column=value WHERE column=value
IF @@ROWCOUNT=0
BEGIN
     --Do work
END             

How can I remove the search bar and footer added by the jQuery DataTables plugin?

You can also not draw the header or footer at all by setting sDom: http://datatables.net/usage/options#sDom

'sDom': 't' 

will display JUST the table, no headers or footers or anything.

It's discussed some here: http://www.datatables.net/forums/discussion/2722/how-to-hide-empty-header-and-footer/p1

How to execute the start script with Nodemon

Add this to script object from your project's package.json file


    "start":"nodemon index.js"

It should be like this


    "scripts": {
        "start":"nodemon index.js"
    }

How to pass multiple parameters from ajax to mvc controller?

Try this;

function X (id,parameter1,parameter2,...) {
    $.ajax({

            url: '@Url.Action("Actionre", "controller")',+ id,
            type: "Get",
            data: { parameter1: parameter1, parameter2: parameter2,...}

    }).done(function(result) {

        your code...
    });
}

So controller method would looks like :

public ActionResult ActionName(id,parameter1, parameter2,...)
{
   Your Code .......
}

How can I replace a regex substring match in Javascript?

using str.replace(regex, $1);:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

if (str.match(regex)) {
    str = str.replace(regex, "$1" + "1" + "$2");
}

Edit: adaptation regarding the comment

What is the best way to implement nested dictionaries?

I like the idea of wrapping this in a class and implementing __getitem__ and __setitem__ such that they implemented a simple query language:

>>> d['new jersey/mercer county/plumbers'] = 3
>>> d['new jersey/mercer county/programmers'] = 81
>>> d['new jersey/mercer county/programmers']
81
>>> d['new jersey/mercer country']
<view which implicitly adds 'new jersey/mercer county' to queries/mutations>

If you wanted to get fancy you could also implement something like:

>>> d['*/*/programmers']
<view which would contain 'programmers' entries>

but mostly I think such a thing would be really fun to implement :D

Addition for BigDecimal

Just another example to add BigDecimals. Key point is that they are immutable and they can be initialized only in the constructor. Here is the code:

import java.util.*;
import java.math.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc;
        boolean first_right_number = false;
        BigDecimal initBigDecimal = BigDecimal.ZERO;
        BigDecimal add1 = BigDecimal.ZERO;
        BigDecimal add2 = BigDecimal.ZERO;

        while (!first_right_number)
        {
            System.out.print("Enter a first single numeric value: ");
            sc = new Scanner(System.in);
            if (sc.hasNextBigDecimal()) 
            {
                first_right_number = true;
                add1 = sc.nextBigDecimal();
            }
        }

        boolean second_right_number = false;
        while (!second_right_number)
        {
            System.out.print("Enter a second single numeric value: ");
            sc = new Scanner(System.in);
            if (sc.hasNextBigDecimal()) 
            {
                second_right_number = true;
                add2 = sc.nextBigDecimal();
            }
        }
        BigDecimal result = initBigDecimal.add(add1).add(add2);
        System.out.println("Sum of the 2 numbers is: " + result.toString());
    }
}

How to get child process from parent process

I've written a script to get all child process pids of a parent process. Here is the code. Hope it will help.

function getcpid() {
    cpids=`pgrep -P $1|xargs`
#    echo "cpids=$cpids"
    for cpid in $cpids;
    do
        echo "$cpid"
        getcpid $cpid
    done
}

getcpid $1

iOS application: how to clear notifications?

If you have pending scheduled local notifications and don't want to use cancelAllLocalNotifications to clear old ones in Notification Center, you can also do the following:

[UIApplication sharedApplication].scheduledLocalNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;

It appears that if you set the scheduledLocalNotifications it clears the old ones in Notification Center, and by setting it to itself, you retain the pending local notifications.

Java and SQLite

There is a new project SQLJet that is a pure Java implementation of SQLite. It doesn't support all of the SQLite features yet, but may be a very good option for some of the Java projects that work with SQLite databases.

How to fix broken paste clipboard in VNC on Windows

You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.

convert date string to mysql datetime field

If these strings are currently in the db, you can skip php by using mysql's STR_TO_DATE() function.

I assume the strings use a format like month/day/year where month and day are always 2 digits, and year is 4 digits.

UPDATE some_table
   SET new_column = STR_TO_DATE(old_column, '%m/%d/%Y')

You can support other date formats by using other format specifiers.

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

exports.handler = async (event) => {
    let query = event.queryStringParameters;
    console.log(`id: ${query.id}`);
    const response = {
        statusCode: 200,
        body: "Hi",
    };
    return response;
};

How to tell if a <script> tag failed to load

onerror Event

*Update August 2017: onerror is fired by Chrome and Firefox. onload is fired by Internet Explorer. Edge fires neither onerror nor onload. I wouldnt use this method but it could work in some cases. See also

<link> onerror do not work in IE

*

Definition and Usage The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).

Tip: When used on audio/video media, related events that occurs when there is some kind of disturbance to the media loading process, are:

  • onabort
  • onemptied
  • onstalled
  • onsuspend

In HTML:

element onerror="myScript">

In JavaScript, using the addEventListener() method:

object.addEventListener("error", myScript);

Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.

Example Execute a JavaScript if an error occurs when loading an image:

img src="image.gif" onerror="myFunction()">

Simple way to calculate median with MySQL

SELECT 
    SUBSTRING_INDEX(
        SUBSTRING_INDEX(
            GROUP_CONCAT(field ORDER BY field),
            ',',
            ((
                ROUND(
                    LENGTH(GROUP_CONCAT(field)) - 
                    LENGTH(
                        REPLACE(
                            GROUP_CONCAT(field),
                            ',',
                            ''
                        )
                    )
                ) / 2) + 1
            )),
            ',',
            -1
        )
FROM
    table

The above seems to work for me.

std::string to char*

Here is one more robust version from Protocol Buffer

char* string_as_array(string* str)
{
    return str->empty() ? NULL : &*str->begin();
}

// test codes
std::string mystr("you are here");
char* pstr = string_as_array(&mystr);
cout << pstr << endl; // you are here

PivotTable to show values, not sum of values

I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.

Assuming your data is in ColumnA:C and has column labels in Row 1, also that Month is formatted mmm(this last for ease of sorting):

  1. Sort the data by Name then Month
  2. Enter in D2 =IF(AND(A2=A1,C2=C1),D1+1,1) (One way to deal with what is the tricky issue of multiple entries for the same person for the same month).
  3. Create a pivot table from A1:D(last occupied row no.)
  4. Say insert in F1.
  5. Layout as in screenshot.

SO12803305 example

I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.

  1. Copy pivot table and Paste Special/Values to, say, L1.
  2. Delete top row of copied range with shift cells up.
  3. Insert new cell at L1 and shift down.
  4. Key 'Name' into L1.
  5. Filter copied range and for ColumnL, select Row Labels and numeric values.
  6. Delete contents of L2:L(last selected cell)
  7. Delete blank rows in copied range with shift cells up (may best via adding a column that counts all 12 months). Hopefully result should be as highlighted in yellow.

Happy to explain further/try again (I've not really tested this) if does not suit.

EDIT (To avoid second block of steps above and facilitate updating for source data changes)

.0. Before first step 2. add a blank row at the very top and move A2:D2 up.
.2. Adjust cell references accordingly (in D3 =IF(AND(A3=A2,C3=C2),D2+1,1).
.3. Create pivot table from A:D

.6. Overwrite Row Labels with Name.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1, ColumnG and rows and columns that show (blank).

additional example

Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).

Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank) into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

Multiple submit buttons on HTML form – designate one button as default

If you're using jQuery, this solution from a comment made here is pretty slick:

$(function(){
    $('form').each(function () {
        var thisform = $(this);
        thisform.prepend(thisform.find('button.default').clone().css({
            position: 'absolute',
            left: '-999px',
            top: '-999px',
            height: 0,
            width: 0
        }));
    });
});

Just add class="default" to the button you want to be the default. It puts a hidden copy of that button right at the beginning of the form.

Volatile Vs Atomic

There are two important concepts in multithreading environment:

  1. atomicity
  2. visibility

The volatile keyword eradicates visibility problems, but it does not deal with atomicity. volatile will prevent the compiler from reordering instructions which involve a write and a subsequent read of a volatile variable; e.g. k++. Here, k++ is not a single machine instruction, but three:

  1. copy the value to a register;
  2. increment the value;
  3. place it back.

So, even if you declare a variable as volatile, this will not make this operation atomic; this means another thread can see a intermediate result which is a stale or unwanted value for the other thread.

On the other hand, AtomicInteger, AtomicReference are based on the Compare and swap instruction. CAS has three operands: a memory location V on which to operate, the expected old value A, and the new value B. CAS atomically updates V to the new value B, but only if the value in V matches the expected old value A; otherwise, it does nothing. In either case, it returns the value currently in V. The compareAndSet() methods of AtomicInteger and AtomicReference take advantage of this functionality, if it is supported by the underlying processor; if it is not, then the JVM implements it via spin lock.

Insert an element at a specific index in a list and return the updated list

The shortest I got: b = a[:2] + [3] + a[2:]

>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

How do I run a simple bit of code in a new thread?

// following declaration of delegate ,,,
public delegate long GetEnergyUsageDelegate(DateTime lastRunTime, 
                                            DateTime procDateTime);

// following inside of some client method
GetEnergyUsageDelegate nrgDel = GetEnergyUsage;
IAsyncResult aR = nrgDel.BeginInvoke(lastRunTime, procDT, null, null);
while (!aR.IsCompleted) Thread.Sleep(500);
int usageCnt = nrgDel.EndInvoke(aR);

Charles your code(above) is not correct. You do not need to spin wait for completion. EndInvoke will block until the WaitHandle is signaled.

If you want to block until completion you simply need to

nrgDel.EndInvoke(nrgDel.BeginInvoke(lastRuntime,procDT,null,null));

or alternatively

ar.AsyncWaitHandle.WaitOne();

But what is the point of issuing anyc calls if you block? You might as well just use a synchronous call. A better bet would be to not block and pass in a lambda for cleanup:

nrgDel.BeginInvoke(lastRuntime,procDT,(ar)=> {ar.EndInvoke(ar);},null);

One thing to keep in mind is that you must call EndInvoke. A lot of people forget this and end up leaking the WaitHandle as most async implementations release the waithandle in EndInvoke.

How to markdown nested list items in Bitbucket?

4 spaces do the trick even inside definition list:

Endpoint
: `/listAgencies`

Method
: `GET`

Arguments
:   * `level` - bla-bla.
    * `withDisabled` - should we include disabled `AGENT`s.
    * `userId` - bla-bla.

I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).

Create a symbolic link of directory in Ubuntu

That's what ln is documented to do when the target already exists and is a directory. If you want /etc/nginx to be a symlink rather than contain a symlink, you had better not create it as a directory first!

SQL - select distinct only on one column

Since you don't care, I chose the max ID for each number.

select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id

Query Explanation

 select 
    tbl.*  -- give me all the data from the base table (tbl) 
 from 
    tbl    
    inner join (  -- only return rows in tbl which match this subquery
        select 
            max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
        from 
            tbl 
        group by 
            NUMBER            -- how to group rows for the MAX aggregation
    ) maxID
        on maxID.maxID = tbl.id -- join condition ie only return rows in tbl 
                                -- whose ID is also a MAX ID for a given NUMBER

Class 'ViewController' has no initializers in swift

The error could be improved, but the problem with your first version is you have a member variable, delegate, that does not have a default value. All variables in Swift must always have a value. That means that you have to set it up in an initializer which you do not have or you could provide it a default value in-line.

When you make it optional, you allow it to be nil by default, removing the need to explicitly give it a value or initialize it.

How to delete a cookie using jQuery?

You can also delete cookies without using jquery.cookie plugin:

document.cookie = 'NAMEOFYOURCOOKIE' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

how to find 2d array size in c++

Use an std::vector.

std::vector< std::vector<int> > my_array; /* 2D Array */

my_array.size(); /* size of y */
my_array[0].size(); /* size of x */

Or, if you can only use a good ol' array, you can use sizeof.

sizeof( my_array ); /* y size */
sizeof( my_array[0] ); /* x size */

How to check if one DateTime is greater than the other in C#

        if (new DateTime(5000) > new DateTime(1000))
        {
            Console.WriteLine("i win");
        }

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

javascript:location.href=%22googlechrome%22+location.href.substring(4);

Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

Source

Works for me.

When to use cla(), clf() or close() for clearing a plot in matplotlib?

There is just a caveat that I discovered today. If you have a function that is calling a plot a lot of times you better use plt.close(fig) instead of fig.clf() somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).

So the the following script will produce an empty list:

for i in range(5):
    fig = plot_figure()
    plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())

Whereas this one will produce a list with five figures on it.

for i in range(5):
    fig = plot_figure()
    fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())

From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.

If you want to try a complete script there you have:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    plt.close(fig)

print(plt.get_fignums())

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    fig.clf()

print(plt.get_fignums())

If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted

Python datetime to string without microsecond component

I found this to be the simplest way.

>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>> 

How to append output to the end of a text file

You can use the >> operator. This will append data from a command to the end of a text file.

To test this try running:

echo "Hi this is a test" >> textfile.txt

Do this a couple of times and then run:

cat textfile.txt

You'll see your text has been appended several times to the textfile.txt file.

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

Input type=password, don't let browser remember the password

As for security issues, here is what a security consultant will tell you on the whole field issue (this is from an actual independent security audit):

HTML Autocomplete Enabled – Password fields in HTML forms have autocomplete enabled. Most browsers have a facility to remember user credentials entered into HTML forms.

Relative Risk: Low

Affected Systems/Devices: o https://*******/

I also agree this should cover any field that contains truly private data. I feel that it is alright to force a person to always type their credit card information, CVC code, passwords, usernames, etc whenever that site is going to access anything that should be kept secure [universally or by legal compliance requirements]. For example: purchase forms, bank/credit sites, tax sites, medical data, federal, nuclear, etc - not Sites like Stack Overflow or Facebook.

Other types of sites - e.g. TimeStar Online for clocking in and out of work - it's stupid, since I always use the same PC/account at work, that I can't save the credentials on that site - strangely enough I can on my Android but not on an iPad. Even shared PCs this wouldn't be too bad since clocking in/out for someone else really doesn't do anything but annoy your supervisor. (They have to go in and delete the erroneous punches - just choose not to save on public PCs).

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

I know, I am late but here is the correct way of doing it. using base64. This technique will convert the array to string.

import base64
import numpy as np
random_array = np.random.randn(32,32)
string_repr = base64.binascii.b2a_base64(random_array).decode("ascii")
array = np.frombuffer(base64.binascii.a2b_base64(string_repr.encode("ascii"))) 

For array to string

Convert binary data to a line of ASCII characters in base64 coding and decode to ASCII to get string repr.

For string to array

First, encode the string in ASCII format then Convert a block of base64 data back to binary and return the binary data.

How can I calculate the difference between two ArrayLists?

You are just comparing strings.

Put the values in ArrayList A as keys in HashTable A.
Put the values in ArrayList B as keys in HashTable B.

Then, for each key in HashTable A, remove it from HashTable B if it exists.

What you are left with in HashTable B are the strings (keys) that were not values in ArrayList A.

C# (3.0) example added in response to request for code:

List<string> listA = new List<string>{"2009-05-18","2009-05-19","2009-05-21'"};
List<string> listB = new List<string>{"2009-05-18","2009-05-18","2009-05-19","2009-05-19","2009-05-20","2009-05-21","2009-05-21","2009-05-22"};

HashSet<string> hashA = new HashSet<string>();
HashSet<string> hashB = new HashSet<string>();

foreach (string dateStrA in listA) hashA.Add(dateStrA);
foreach (string dateStrB in listB) hashB.Add(dateStrB);

foreach (string dateStrA in hashA)
{
    if (hashB.Contains(dateStrA)) hashB.Remove(dateStrA);
}

List<string> result = hashB.ToList<string>();

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

I had this issue with a WinForms Project using VS 2015. My solution was:

  1. right click the Project
  2. select properties
  3. check "Prefer 32-bit"
  4. Platform target: Any CPU

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

pySerial write() won't take my string

You have found the root cause. Alternately do like this:

ser.write(bytes(b'your_commands'))

Add attribute 'checked' on click jquery

$( this ).attr( 'checked', 'checked' )

just attr( 'checked' ) will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />

Edit:

Based on comments, a more appropriate manipulation would be:

$( this ).attr( 'checked', true )

And a straight javascript method, more appropriate and efficient:

this.checked = true;

Thanks @Andy E for that.

Codeigniter - no input file specified

My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:

<IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On

    # If your website begins from a folder e.g localhost/my_project then 
    # you have to change it to: RewriteBase /my_project/
    # If your site begins from the root e.g. example.local/ then
    # let it as it is
    RewriteBase /

    # Protect application and system files from being viewed when the index.php is missing
    RewriteCond $1 ^(application|system|private|logs)

    # Rewrite to index.php/access_denied/URL
    RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

    # Allow these directories and files to be displayed directly:
    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)

    # No rewriting
    RewriteRule ^(.*)$ - [PT,L]

    # Rewrite to index.php/URL
    RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>

Maven artifact and groupId naming

However, I disagree the official definition of Guide to naming conventions on groupId, artifactId, and version which proposes the groupId must start with a reversed domain name you control.

com means this project belongs to a company, and org means this project belongs to a social organization. These are alright, but for those strange domain like xxx.tv, xxx.uk, xxx.cn, it does not make sense to name the groupId started with "tv.","cn.", the groupId should deliver the basic information of the project rather than the domain.

Set Background cell color in PHPExcel

$sheet->getStyle('A1')->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'FF0000')
        )
    )
);

Source: http://bayu.freelancer.web.id/2010/07/16/phpexcel-advanced-read-write-excel-made-simple/

Push JSON Objects to array in localStorage

There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.

Step 1:

The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:

var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));

The above code should only be run once and only if you are not already storing an array in your localStorage session variable. If you are already doing this skip to step 2.

Step 2:

Modify your function like so:

function SaveDataToLocalStorage(data)
{
    var a = [];
    // Parse the serialized data back into an aray of objects
    a = JSON.parse(localStorage.getItem('session')) || [];
    // Push the new data (whether it be an object or anything else) onto the array
    a.push(data);
    // Alert the array value
    alert(a);  // Should be something like [Object array]
    // Re-serialize the array back into a string and store it in localStorage
    localStorage.setItem('session', JSON.stringify(a));
}

This should take care of the rest for you. When you parse it out, it will become an array of objects.

Hope this helps.

Oracle: SQL query that returns rows with only numeric values

If you use Oracle 10 or higher you can use regexp functions as codaddict suggested. In earlier versions translate function will help you:

select * from tablename  where translate(x, '.1234567890', '.') is null;

More info about Oracle translate function can be found here or in official documentation "SQL Reference"

UPD: If you have signs or spaces in your numbers you can add "+-" characters to the second parameter of translate function.

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

Implicit type conversion rules in C++ operators

This answer is directed in large part at a comment made by @RafalDowgird:

"The minimum size of operations is int." - This would be very strange (what about architectures that efficiently support char/short operations?) Is this really in the C++ spec?

Keep in mind that the C++ standard has the all-important "as-if" rule. See section 1.8: Program Execution:

3) This provision is sometimes called the "as-if" rule, because an implementation is free to disregard any requirement of the Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program.

The compiler cannot set an int to be 8 bits in size, even if it were the fastest, since the standard mandates a 16-bit minimum int.

Therefore, in the case of a theoretical computer with super-fast 8-bit operations, the implicit promotion to int for arithmetic could matter. However, for many operations, you cannot tell if the compiler actually did the operations in the precision of an int and then converted to a char to store in your variable, or if the operations were done in char all along.

For example, consider unsigned char = unsigned char + unsigned char + unsigned char, where addition would overflow (let's assume a value of 200 for each). If you promoted to int, you would get 600, which would then be implicitly down cast into an unsigned char, which would wrap modulo 256, thus giving a final result of 88. If you did no such promotions,you'd have to wrap between the first two additions, which would reduce the problem from 200 + 200 + 200 to 144 + 200, which is 344, which reduces to 88. In other words, the program does not know the difference, so the compiler is free to ignore the mandate to perform intermediate operations in int if the operands have a lower ranking than int.

This is true in general of addition, subtraction, and multiplication. It is not true in general for division or modulus.

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

A lot of the times the implementation will exist in the same namespace as the interface. So, I came up with this:

    public class InterfaceConverter : JsonConverter
    {
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.ReadFrom(reader);
        var typeVariable = this.GetTypeVariable(token);
        if (TypeExtensions.TryParse(typeVariable, out var implimentation))
        { }
        else if (!typeof(IEnumerable).IsAssignableFrom(objectType))
        {
            implimentation = this.GetImplimentedType(objectType);
        }
        else
        {
            var genericArgumentTypes = objectType.GetGenericArguments();
            var innerType = genericArgumentTypes.FirstOrDefault();
            if (innerType == null)
            {
                implimentation = typeof(IEnumerable);
            }
            else
            {
                Type genericType = null;
                if (token.HasAny())
                {
                    var firstItem = token[0];
                    var genericTypeVariable = this.GetTypeVariable(firstItem);
                    TypeExtensions.TryParse(genericTypeVariable, out genericType);
                }

                genericType = genericType ?? this.GetImplimentedType(innerType);
                implimentation = typeof(IEnumerable<>);
                implimentation = implimentation.MakeGenericType(genericType);
            }
        }

        return JsonConvert.DeserializeObject(token.ToString(), implimentation);
    }

    public override bool CanConvert(Type objectType)
    {
        return !typeof(IEnumerable).IsAssignableFrom(objectType) && objectType.IsInterface || typeof(IEnumerable).IsAssignableFrom(objectType) && objectType.GetGenericArguments().Any(t => t.IsInterface);
    }

    protected Type GetImplimentedType(Type interfaceType)
    {
        if (!interfaceType.IsInterface)
        {
            return interfaceType;
        }

        var implimentationQualifiedName = interfaceType.AssemblyQualifiedName?.Replace(interfaceType.Name, interfaceType.Name.Substring(1));
        return implimentationQualifiedName == null ? interfaceType : Type.GetType(implimentationQualifiedName) ?? interfaceType;
    }

    protected string GetTypeVariable(JToken token)
    {
        if (!token.HasAny())
        {
            return null;
        }

        return token.Type != JTokenType.Object ? null : token.Value<string>("$type");
    }
}

Therefore, you can include this globally like so:

public static JsonSerializerSettings StandardSerializerSettings => new JsonSerializerSettings
    {
        Converters = new List<JsonConverter>
        {
            new InterfaceConverter()
        }
    };

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How do I declare an array with a custom class?

You need a parameterless constructor to be able to create an instance of your class. Your current constructor requires two input string parameters.

Normally C++ implies having such a constructor (=default parameterless constructor) if there is no other constructor declared. By declaring your first constructor with two parameters you overwrite this default behaviour and now you have to declare this constructor explicitly.

Here is the working code:

#include <iostream> 
#include <string>  // <-- you need this if you want to use string type

using namespace std; 

class name { 
  public: 
    string first; 
    string last; 

  name(string a, string b){ 
    first = a; 
    last = b; 

  }

  name ()  // <-- this is your explicit parameterless constructor
  {}

}; 

int main (int argc, const char * argv[]) 
{ 

  const int howManyNames = 3; 

  name someName[howManyNames]; 

  return 0; 
}

(BTW, you need to include to make the code compilable.)

An alternative way is to initialize your instances explicitly on declaration

  name someName[howManyNames] = { {"Ivan", "The Terrible"}, {"Catherine", "The Great"} };

How do I create a basic UIButton programmatically?

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
           action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(10.0, 100.0, 300.0, 20.0);
[self.view addSubview:button];

How do you select a particular option in a SELECT element in jQuery?

i'll go with:-

$("select#my-select option") .each(function() { this.selected = (this.text == myVal); });

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

We have 1 MB - 3 KB RAM = 2^23 - 3*2^13 bits = 8388608 - 24576 = 8364032 bits available.

We are given 10^6 numbers in a 10^8 range. This gives an average gap of ~100 < 2^7 = 128

Let's first consider the simpler problem of fairly evenly spaced numbers when all gaps are < 128. This is easy. Just store the first number and the 7-bit gaps:

(27 bits) + 10^6 7-bit gap numbers = 7000027 bits required

Note repeated numbers have gaps of 0.

But what if we have gaps larger than 127?

OK, let's say a gap size < 127 is represented directly, but a gap size of 127 is followed by a continuous 8-bit encoding for the actual gap length:

 10xxxxxx xxxxxxxx                       = 127 .. 16,383
 110xxxxx xxxxxxxx xxxxxxxx              = 16384 .. 2,097,151

etc.

Note this number representation describes its own length so we know when the next gap number starts.

With just small gaps < 127, this still requires 7000027 bits.

There can be up to (10^8)/(2^7) = 781250 23-bit gap number, requiring an extra 16*781,250 = 12,500,000 bits which is too much. We need a more compact and slowly increasing representation of gaps.

The average gap size is 100 so if we reorder them as [100, 99, 101, 98, 102, ..., 2, 198, 1, 199, 0, 200, 201, 202, ...] and index this with a dense binary Fibonacci base encoding with no pairs of zeros (for example, 11011=8+5+2+1=16) with numbers delimited by '00' then I think we can keep the gap representation short enough, but it needs more analysis.

X-Frame-Options on apache

See X-Frame-Options header on error response

You can simply add following line to .htaccess

Header always unset X-Frame-Options

How to add extra whitespace in PHP?

PHP (typically) generates HTML output for a web-site.

When displaying HTML, the browser (typically) collapses all whitespace in text into a single space. Sometimes, between tags, it even collapses whitespace to nothing.

In order to persuade the browser to display whitespace, you need to include special tags like &nbsp; or <br/> in your HTML to add non-breaking whitespace or new lines, respectively.

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Try:

SELECT convert(nvarchar(10), SA.[RequestStartDate], 103) as 'Service Start Date', 
       convert(nvarchar(10), SA.[RequestEndDate], 103) as 'Service End Date', 
FROM
(......)SA
WHERE......

Or:

SELECT format(SA.[RequestStartDate], 'dd/MM/yyyy') as 'Service Start Date', 
       format(SA.[RequestEndDate], 'dd/MM/yyyy') as 'Service End Date', 
FROM
(......)SA
WHERE......

Is there a way to get a collection of all the Models in your Rails app?

I can't comment yet, but I think sj26 answer should be the top answer. Just a hint:

Rails.application.eager_load! unless Rails.configuration.cache_classes
ActiveRecord::Base.descendants

How to get directory size in PHP

It works perfectly fine .

     public static function folderSize($dir)
     {
        $size = 0;

        foreach (glob(rtrim($dir, '/') . '/*', GLOB_NOSORT) as $each) {
            $func_name = __FUNCTION__;
            $size += is_file($each) ? filesize($each) : static::$func_name($each);
        }

        return $size;
      }

How do you easily create empty matrices javascript?

The question is slightly ambiguous, since None can translate into either undefined or null. null is a better choice:

var a = [], b;
var i, j;
for (i = 0; i < 9; i++) {
  for (j = 0, b = []; j < 9; j++) {
    b.push(null);
  }
  a.push(b);
}

If undefined, you can be sloppy and just don't bother, everything is undefined anyway. :)

An error occurred while collecting items to be installed (Access is denied)

Installig Eclispe ADT from market place solved this problem for me.

How to get exit code when using Python subprocess communicate method?

exitcode = data.wait(). The child process will be blocked If it writes to standard output/error, and/or reads from standard input, and there are no peers.

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

It just means that the server cannot find your image.

Remember The image path must be relative to the CSS file location

Check the path and if the image file exist.

Adjust width of input field to its input

I really liked Lyth's answer, but also really wanted it to:

  1. Handle backspace and delete
  2. Not require you to manually add an adjacent tag.
  3. Enforce a min width.
  4. Automatically be applied to elements with a specific class

I adapted his JSFiddle and came up with this. One improvement not present in this fiddle would be to use something like the jQuery CSS Parser to actually read the initial width from the input.textbox-autosize rule, and use that as the minWidth. Right I'm simply using an attribute on the , which makes for a compact demo but is not ideal. as it requires an extra attribute on each input. You might also just want to put the minWidth as 100 right in the JavaScript.

HTML:

<div id='applicationHost'>
<div>Name:   <input class='textbox-autosize' data-min-width='100' type="text" /></div>
<div>Email:  <input class='textbox-autosize' data-min-width='100' type="email" /></div>
<div>Points: <input class='textbox-autosize' data-min-width='100' type="number" /></div>
</div>

CSS:

#applicationHost {
    font-family: courier;
    white-space: pre;
}

input.textbox-autosize, span.invisible-autosize-helper {
    padding:0;
    font-size:12px;
    font-family:Sans-serif; 
    white-space:pre;
}
input.textbox-autosize {
    width: 100px; /* Initial width of textboxes */
}

/*
In order for the measurements to work out, your input and the invisible
span need to have the same styling.
*/

JavaScript:

$('#applicationHost').on('keyup', '.textbox-autosize', function(e) {
    // Add an arbitary buffer of 15 pixels.
    var whitespaceBuffer = 15;
    var je = $(this);
    var minWidth = parseInt(je.attr('data-min-width'));
    var newVal = je.val();
    var sizingSpanClass = 'invisible-autosize-helper';
    var $span = je.siblings('span.' + sizingSpanClass).first();
    // If this element hasn't been created yet, we'll create it now.
    if ($span.length === 0) {
        $span = $('<span/>', {
            'class': sizingSpanClass,
            'style': 'display: none;'
        });
        je.parent().append($span);
    }
    $span = je.siblings('span').first();
    $span.text(newVal) ; // the hidden span takes 
    // the value of the input
    $inputSize = $span.width();
    $inputSize += whitespaceBuffer;
    if($inputSize > minWidth)
        je.css("width", $inputSize) ; // apply width of the span to the input
    else
        je.css("width", minWidth) ; // Ensure we're at the min width
});

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

List distinct values in a vector in R

If the data is actually a factor then you can use the levels() function, e.g.

levels( data$product_code )

If it's not a factor, but it should be, you can convert it to factor first by using the factor() function, e.g.

levels( factor( data$product_code ) )

Another option, as mentioned above, is the unique() function:

unique( data$product_code )

The main difference between the two (when applied to a factor) is that levels will return a character vector in the order of levels, including any levels that are coded but do not occur. unique will return a factor in the order the values first appear, with any non-occurring levels omitted (though still included in levels of the returned factor).

What is the difference between SAX and DOM?

In just a few words...

SAX (Simple API for XML): Is a stream-based processor. You only have a tiny part in memory at any time and you "sniff" the XML stream by implementing callback code for events like tagStarted() etc. It uses almost no memory, but you can't do "DOM" stuff, like use xpath or traverse trees.

DOM (Document Object Model): You load the whole thing into memory - it's a massive memory hog. You can blow memory with even medium sized documents. But you can use xpath and traverse the tree etc.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

How to initialize a JavaScript Date to a particular time zone

You can specify a time zone offset on new Date(), for example:

new Date('Feb 28 2013 19:00:00 EST')

or

new Date('Feb 28 2013 19:00:00 GMT-0500')

Since Date store UTC time ( i.e. getTime returns in UTC ), javascript will them convert the time into UTC, and when you call things like toString javascript will convert the UTC time into browser's local timezone and return the string in local timezone, i.e. If I'm using UTC+8:

> new Date('Feb 28 2013 19:00:00 GMT-0500').toString()
< "Fri Mar 01 2013 08:00:00 GMT+0800 (CST)"

Also you can use normal getHours/Minute/Second method:

> new Date('Feb 28 2013 19:00:00 GMT-0500').getHours()
< 8

( This 8 means after the time is converted into my local time - UTC+8, the hours number is 8. )

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

Go to Build Gradle (Module:app) Change the following. In my case, I choose 25.0.3

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.cesarhcq.viisolutions"
        minSdkVersion 15
        targetSdkVersion 25

After that, it works fine!

Specifying trust store information in spring boot application.properties

Although I am commenting late. But I have used this method to do the job. Here when I am running my spring application I am providing the application yaml file via -Dspring.config.location=file:/location-to-file/config-server-vault-application.yml which contains all of my properties

config-server-vault-application.yml
***********************************
server:
  port: 8888
  ssl:
    trust-store: /trust-store/config-server-trust-store.jks
    trust-store-password: config-server
    trust-store-type: pkcs12

************************************
Java Code
************************************
@SpringBootApplication
public class ConfigServerApplication {

 public static void main(String[] args) throws IOException {
    setUpTrustStoreForApplication();
    SpringApplication.run(ConfigServerApplication.class, args);
 }

 private static void setUpTrustStoreForApplication() throws IOException {
    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    List<PropertySource<?>> applicationYamlPropertySource = loader.load(
            "config-application-properties", new UrlResource(System.getProperty("spring.config.location")));
    Map<String, Object> source = ((MapPropertySource) applicationYamlPropertySource.get(0)).getSource();
    System.setProperty("javax.net.ssl.trustStore", source.get("server.ssl.trust-store").toString());
    System.setProperty("javax.net.ssl.trustStorePassword", source.get("server.ssl.trust-store-password").toString());
  }
}

PostgreSQL column 'foo' does not exist

I fixed it by changing the quotation mark (") with apostrophe (') inside Values. For instance:

insert into trucks ("id","datetime") VALUES (862,"10-09-2002 09:15:59");

Becomes this:

insert into trucks ("id","datetime") VALUES (862,'10-09-2002 09:15:59');

Assuming datetime column is VarChar.

How can I pass a username/password in the header to a SOAP WCF Service

Answers that suggest that the header provided in the question are supported out of the box by WCF are incorrect. The header in the question contains a Nonce and a Created timestamp in the UsernameToken, which is an official part of the WS-Security specification that WCF does not support. WCF only supports username and password out of the box.

If all you need to do is add a username and password, then Sergey's answer is the least-effort approach. If you need to add any other fields, you will need to supply custom classes to support them.

A somewhat more elegant approach that I found was to override the ClientCredentials, ClientCredentialsSecurityTokenManager and WSSecurityTokenizer classes to support the additional properties. I've provided a link to the blog post where the approach is discussed in detail, but here is the sample code for the overrides:

public class CustomCredentials : ClientCredentials
{
    public CustomCredentials()
    { }

    protected CustomCredentials(CustomCredentials cc)
        : base(cc)
    { }

    public override System.IdentityModel.Selectors.SecurityTokenManager CreateSecurityTokenManager()
    {
        return new CustomSecurityTokenManager(this);
    }

    protected override ClientCredentials CloneCore()
    {
        return new CustomCredentials(this);
    }
}

public class CustomSecurityTokenManager : ClientCredentialsSecurityTokenManager
{
    public CustomSecurityTokenManager(CustomCredentials cred)
        : base(cred)
    { }

    public override System.IdentityModel.Selectors.SecurityTokenSerializer CreateSecurityTokenSerializer(System.IdentityModel.Selectors.SecurityTokenVersion version)
    {
        return new CustomTokenSerializer(System.ServiceModel.Security.SecurityVersion.WSSecurity11);
    }
}

public class CustomTokenSerializer : WSSecurityTokenSerializer
{
    public CustomTokenSerializer(SecurityVersion sv)
        : base(sv)
    { }

    protected override void WriteTokenCore(System.Xml.XmlWriter writer,
                                            System.IdentityModel.Tokens.SecurityToken token)
    {
        UserNameSecurityToken userToken = token as UserNameSecurityToken;

        string tokennamespace = "o";

        DateTime created = DateTime.Now;
        string createdStr = created.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

        // unique Nonce value - encode with SHA-1 for 'randomness'
        // in theory the nonce could just be the GUID by itself
        string phrase = Guid.NewGuid().ToString();
        var nonce = GetSHA1String(phrase);

        // in this case password is plain text
        // for digest mode password needs to be encoded as:
        // PasswordAsDigest = Base64(SHA-1(Nonce + Created + Password))
        // and profile needs to change to
        //string password = GetSHA1String(nonce + createdStr + userToken.Password);

        string password = userToken.Password;

        writer.WriteRaw(string.Format(
        "<{0}:UsernameToken u:Id=\"" + token.Id +
        "\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">" +
        "<{0}:Username>" + userToken.UserName + "</{0}:Username>" +
        "<{0}:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">" +
        password + "</{0}:Password>" +
        "<{0}:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">" +
        nonce + "</{0}:Nonce>" +
        "<u:Created>" + createdStr + "</u:Created></{0}:UsernameToken>", tokennamespace));
    }

    protected string GetSHA1String(string phrase)
    {
        SHA1CryptoServiceProvider sha1Hasher = new SHA1CryptoServiceProvider();
        byte[] hashedDataBytes = sha1Hasher.ComputeHash(Encoding.UTF8.GetBytes(phrase));
        return Convert.ToBase64String(hashedDataBytes);
    }

}

Before creating the client, you create the custom binding and manually add the security, encoding and transport elements to it. Then, replace the default ClientCredentials with your custom implementation and set the username and password as you would normally:

var security = TransportSecurityBindingElement.CreateUserNameOverTransportBindingElement();
    security.IncludeTimestamp = false;
    security.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256;
    security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;

var encoding = new TextMessageEncodingBindingElement();
encoding.MessageVersion = MessageVersion.Soap11;

var transport = new HttpsTransportBindingElement();
transport.MaxReceivedMessageSize = 20000000; // 20 megs

binding.Elements.Add(security);
binding.Elements.Add(encoding);
binding.Elements.Add(transport);

RealTimeOnlineClient client = new RealTimeOnlineClient(binding,
    new EndpointAddress(url));

    client.ChannelFactory.Endpoint.EndpointBehaviors.Remove(client.ClientCredentials);
client.ChannelFactory.Endpoint.EndpointBehaviors.Add(new CustomCredentials());

client.ClientCredentials.UserName.UserName = username;
client.ClientCredentials.UserName.Password = password;

Bootstrap 3 2-column form layout

You can use the bootstrap grid system. as Yoann said


 <div class="container">
    <div class="row">
        <form role="form">
           <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Name</label>
                        <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
                    </div>
                    <div class="clearfix"></div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Confirm Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
                    </div>
          </form>
         <div class="clearfix">
      </div>
    </div>
</div>

How to get the ASCII value of a character

The accepted answer is correct, but there is a more clever/efficient way to do this if you need to convert a whole bunch of ASCII characters to their ASCII codes at once. Instead of doing:

for ch in mystr:
    code = ord(ch)

or the slightly faster:

for code in map(ord, mystr):

you convert to Python native types that iterate the codes directly. On Python 3, it's trivial:

for code in mystr.encode('ascii'):

and on Python 2.6/2.7, it's only slightly more involved because it doesn't have a Py3 style bytes object (bytes is an alias for str, which iterates by character), but they do have bytearray:

# If mystr is definitely str, not unicode
for code in bytearray(mystr):

# If mystr could be either str or unicode
for code in bytearray(mystr, 'ascii'):

Encoding as a type that natively iterates by ordinal means the conversion goes much faster; in local tests on both Py2.7 and Py3.5, iterating a str to get its ASCII codes using map(ord, mystr) starts off taking about twice as long for a len 10 str than using bytearray(mystr) on Py2 or mystr.encode('ascii') on Py3, and as the str gets longer, the multiplier paid for map(ord, mystr) rises to ~6.5x-7x.

The only downside is that the conversion is all at once, so your first result might take a little longer, and a truly enormous str would have a proportionately large temporary bytes/bytearray, but unless this forces you into page thrashing, this isn't likely to matter.

Text-decoration: none not working

I have an answer:

<a href="#">
    <div class="widget">  
        <div class="title" style="text-decoration: none;">Underlined. Why?</div>  
    </div>
</a>?

It works.

Refresh Fragment at reload

I had the same issue but none of the above worked for mine. either there was a backstack problem (after loading when user pressed back it would to go the same fragment again) or it didnt call the onCreaetView

finally i did this:

public void transactFragment(Fragment fragment, boolean reload) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    if (reload) {
        getSupportFragmentManager().popBackStack();
    }
    transaction.replace(R.id.main_activity_frame_layout, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

good point is you dont need the tag or id of the fragment either. if you want to reload

Observable Finally on Subscribe

The only thing which worked for me is this

fetchData()
  .subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //Called when operation is complete (both success and error)
  });

Making PHP var_dump() values display one line per value

I didn't wanna stop using var_dump($variable);die(); and using pre tags and loops seems overkill to me, so since I am looking at the dump in a browser, I just right click the page and choose Inspect (I use Chrome). The Elements section of the Developer Tools show the variable in a very readable format.

Return the most recent record from ElasticSearch index

Do you have _timestamp enabled in your doc mapping?

{
    "doctype": {
        "_timestamp": {
            "enabled": "true",
            "store": "yes"
        },
        "properties": {
            ...
        }
    }
}

You can check your mapping here:

http://localhost:9200/_all/_mapping

If so I think this might work to get most recent:

{
  "query": {
    "match_all": {}
  },
  "size": 1,
  "sort": [
    {
      "_timestamp": {
        "order": "desc"
      }
    }
  ]
}

How to insert a new line in strings in Android

I would personally prefer using "\n". This just puts a line break in Linux or Android.

For example,

String str = "I am the first part of the info being emailed.\nI am the second part.\n\nI am the third part.";

Output

I am the first part of the info being emailed.
I am the second part.

I am the third part.

A more generalized way would be to use,

System.getProperty("line.separator")

For example,

String str = "I am the first part of the info being emailed." + System.getProperty("line.separator") + "I am the second part." + System.getProperty("line.separator") + System.getProperty("line.separator") + "I am the third part.";

brings the same output as above. Here, the static getProperty() method of the System class can be used to get the "line.seperator" for the particular OS.

But this is not necessary at all, as the OS here is fixed, that is, Android. So, calling a method every time is a heavy and unnecessary operation.

Moreover, this also increases your code length and makes it look kind of messy. A "\n" is sweet and simple.

How to timeout a thread

Assuming the thread code is out of your control:

From the Java documentation mentioned above:

What if a thread doesn't respond to Thread.interrupt?

In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.

Bottom Line:

Make sure all threads can be interrupted, or else you need specific knowledge of the thread - like having a flag to set. Maybe you can require that the task be given to you along with the code needed to stop it - define an interface with a stop() method. You can also warn when you failed to stop a task.