Programs & Examples On #Markitup

markItUp! is a JavaScript plug-in that allows any textarea to be turned into a markup editor.

How to add calendar events in Android?

i used the code below, it solves my problem to add event in default device calendar in ICS and also on version less that ICS

    if (Build.VERSION.SDK_INT >= 14) {
        Intent intent = new Intent(Intent.ACTION_INSERT)
        .setData(Events.CONTENT_URI)
        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
        .putExtra(Events.TITLE, "Yoga")
        .putExtra(Events.DESCRIPTION, "Group class")
        .putExtra(Events.EVENT_LOCATION, "The gym")
        .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
        .putExtra(Intent.EXTRA_EMAIL, "[email protected],[email protected]");
         startActivity(intent);
}

    else {
        Calendar cal = Calendar.getInstance();              
        Intent intent = new Intent(Intent.ACTION_EDIT);
        intent.setType("vnd.android.cursor.item/event");
        intent.putExtra("beginTime", cal.getTimeInMillis());
        intent.putExtra("allDay", true);
        intent.putExtra("rrule", "FREQ=YEARLY");
        intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
        intent.putExtra("title", "A Test Event from android app");
        startActivity(intent);
        }

Hope it would help.....

ImageView in circular through xml

Try this.

public class RoundedImageView extends android.support.v7.widget.AppCompatImageView {

    private int borderWidth = 4;
    private int viewWidth;
    private int viewHeight;
    private Bitmap image;
    private Paint paint;
    private Paint paintBorder;
    private BitmapShader shader;

    public RoundedImageView(Context context)
    {
        super(context);
        setup();
    }

    public RoundedImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        setup();
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        setup();
    }

    private void setup()
    {
        paint = new Paint();
        paint.setAntiAlias(true);

        paintBorder = new Paint();
        setBorderColor(Color.WHITE);
        paintBorder.setAntiAlias(true);
        this.setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);

        paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.WHITE);
    }

    public void setBorderWidth(int borderWidth)
    {
        this.borderWidth = borderWidth;
        this.invalidate();
    }

    public void setBorderColor(int borderColor)
    {
        if (paintBorder != null)
            paintBorder.setColor(borderColor);

        this.invalidate();
    }

    private void loadBitmap()
    {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();

        if (bitmapDrawable != null)
            image = bitmapDrawable.getBitmap();
    }

    @SuppressLint("DrawAllocation")
    @Override
    public void onDraw(Canvas canvas)
    {
        loadBitmap();

        if (image != null)
        {
            shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            paint.setShader(shader);
            int circleCenter = viewWidth / 2;
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth - 4.0f, paintBorder);
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter - 4.0f, paint);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec, widthMeasureSpec);

        viewWidth = width - (borderWidth * 2);
        viewHeight = height - (borderWidth * 2);

        setMeasuredDimension(width, height);
    }

    private int measureWidth(int measureSpec)
    {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY)
        {
            result = specSize;
        }
        else
        {
            // Measure the text
            result = viewWidth;
        }

        return result;
    }

    private int measureHeight(int measureSpecHeight, int measureSpecWidth)
    {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpecHeight);
        int specSize = MeasureSpec.getSize(measureSpecHeight);

        if (specMode == MeasureSpec.EXACTLY)
        {
            result = specSize;
        }
        else
        {
            result = viewHeight;
        }

        return (result + 2);
     }
 }

and use this ImageView in layout like:

<com.app.Demo.RoundedImageView
     android:id="@+id/iv_profileImage"
     android:layout_width="70dp"
     android:layout_height="70dp"
     android:layout_centerHorizontal="true"
    />

Tab space instead of multiple non-breaking spaces ("nbsp")?

There really isn't any easy way to insert multiple spaces inside (or in the middle) of a paragraph. Those suggesting you use CSS are missing the point. You may not always be trying to indent a paragraph from a side but, in fact, trying to put extra spaces in a particular spot of it.

In essence, in this case, the spaces become the content and not the style. I don't know why so many people don't see that. I guess the rigidity with which they try to enforce the separation of style and content rule (HTML was designed to do both from the beginning - there is nothing wrong with occasionally defining style of an unique element using appropriate tags without having to spend a lot more time on creating CSS style sheets and there is absolutely nothing unreadable about it when it's used in moderation. There is also something to be said for being able to do something quickly.) translates to how they can only consider whitespace characters as being used only for style and indentation.

And when there is no graceful way to insert spaces without having to rely on &emsp; and &nbsp; tags, I would argue that the resulting code becomes far more unreadible than if there was an appropriately named tag that would have allowed you to quickly insert a large number of spaces (or if, you know, spaces weren't needlessly consumed in the first place).

As it is though, as was said above, your best bet would be to use &emsp; to insert   in the correct place.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

find . -type f | 
sed -n "s/\(.*\)factory\.py$/& \1service\.py/p" | 
xargs -p -n 2 mv

eg will rename all files in the cwd with names ending in "factory.py" to be replaced with names ending in "service.py"

explanation:

1) in the sed cmd, the -n flag will suppress normal behavior of echoing input to output after the s/// command is applied, and the p option on s/// will force writing to output if a substitution is made. since a sub will only be made on match, sed will only have output for files ending in "factory.py"

2) in the s/// replacement string, we use "& " to interpolate the entire matching string, followed by a space character, into the replacement. because of this, it's vital that our RE matches the entire filename. after the space char, we use "\1service.py" to interpolate the string we gulped before "factory.py", followed by "service.py", replacing it. So for more complex transformations youll have to change the args to s/// (with an re still matching the entire filename)

example output:

foo_factory.py foo_service.py
bar_factory.py bar_service.py

3) we use xargs with -n 2 to consume the output of sed 2 delimited strings at a time, passing these to mv (i also put the -p option in there so you can feel safe when running this). voila.

Setting WPF image source in code

If you already have a stream and know the format, you can use something like this:

static ImageSource PngStreamToImageSource (Stream pngStream) {
    var decoder = new PngBitmapDecoder(pngStream,
        BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
    return decoder.Frames[0];
}

Is there any way to do HTTP PUT in python

Using urllib3

To do that, you will need to manually encode query parameters in the URL.

>>> import urllib3
>>> http = urllib3.PoolManager()
>>> from urllib.parse import urlencode
>>> encoded_args = urlencode({"name":"Zion","salary":"1123","age":"23"})
>>> url = 'http://dummy.restapiexample.com/api/v1/update/15410' + encoded_args
>>> r = http.request('PUT', url)
>>> import json
>>> json.loads(r.data.decode('utf-8'))
{'status': 'success', 'data': [], 'message': 'Successfully! Record has been updated.'}

Using requests

>>> import requests
>>> r = requests.put('https://httpbin.org/put', data = {'key':'value'})
>>> r.status_code
200

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Regarding this part:

When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.

The easiest solution is to avoid the problem entirely by properly configuring Notepad++.

Try Settings -> Preferences -> New document -> Encoding -> choose UTF-8 without BOM, and check Apply to opened ANSI files.

notepad++ UTF-8 apply to opened ANSI files

That way all the opened ANSI files will be treated as UTF-8 without BOM.

For explanation what's going on, read the comments below this answer.

To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

To make it clear, in addition to @SLaks' answer, that meant you need to change this line :

List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);

to something like this :

RootObject datalist = JsonConvert.DeserializeObject<RootObject>(jsonstring);

Recursive query in SQL Server

Try this:

;WITH CTE
AS
(
    SELECT DISTINCT
        M1.Product_ID Group_ID,
        M1.Product_ID
    FROM matches M1
        LEFT JOIN matches M2
            ON M1.Product_Id = M2.matching_Product_Id
    WHERE M2.matching_Product_Id IS NULL
    UNION ALL
    SELECT
        C.Group_ID,
        M.matching_Product_Id
    FROM CTE C
        JOIN matches M
            ON C.Product_ID = M.Product_ID
)
SELECT * FROM CTE ORDER BY Group_ID

You can use OPTION(MAXRECURSION n) to control recursion depth.

SQL FIDDLE DEMO

ORA-28000: the account is locked error getting frequently

Way to unlock the user :

$ sqlplus  /nolog
SQL > conn sys as sysdba
SQL > ALTER USER USER_NAME ACCOUNT UNLOCK;

and open new terminal

SQL > sqlplus / as sysdba
connected
SQL > conn username/password  //which username u gave before unlock
  • it will ask new password:password
  • it will ask re-type password:password
  • press enter u will get loggedin

How does Java resolve a relative path in new File()?

The working directory is a common concept across virtually all operating systems and program languages etc. It's the directory in which your program is running. This is usually (but not always, there are ways to change it) the directory the application is in.

Relative paths are ones that start without a drive specifier. So in linux they don't start with a /, in windows they don't start with a C:\, etc. These always start from your working directory.

Absolute paths are the ones that start with a drive (or machine for network paths) specifier. They always go from the start of that drive.

Remove Safari/Chrome textinput/textarea glow

Edit (11 years later): Don't do this unless you're going to provide a fallback to indicate which element is active. Otherwise, this harms accessibility as it essentially removes the indication showing which element in a document has focus. Imagine being a keyboard user and not really knowing what element you can interact with. Let accessibility trump aesthetics here.

textarea, select, input, button { outline: none; }

Although, it's been argued that keeping the glow/outline is actually beneficial for accessibility as it can help users see which Element is currently focused.

You can also use the pseudo-element ':focus' to only target the inputs when the user has them selected.

Demo: https://jsfiddle.net/JohnnyWalkerDesign/xm3zu0cf/

How to close a window using jQuery

just window.close() is OK, why should write in jQuery?

What is App.config in C#.NET? How to use it?

Simply, App.config is an XML based file format that holds the Application Level Configurations.

Example:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="key" value="test" />
  </appSettings>
</configuration>

You can access the configurations by using ConfigurationManager as shown in the piece of code snippet below:

var value = System.Configuration.ConfigurationManager.AppSettings["key"];
// value is now "test"

Note: ConfigurationSettings is obsolete method to retrieve configuration information.

var value = System.Configuration.ConfigurationSettings.AppSettings["key"];

How to check a string for a special character?

Everyone else's method doesn't account for whitespaces. Obviously nobody really considers a whitespace a special character.

Use this method to detect special characters not including whitespaces:

import re

def detect_special_characer(pass_string): 
  regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]') 
  if(regex.search(pass_string) == None): 
    res = False
  else: 
    res = True
  return(res)

How to dismiss notification after action has been clicked

I found that when you use the action buttons in expanded notifications, you have to write extra code and you are more constrained.

You have to manually cancel your notification when the user clicks an action button. The notification is only cancelled automatically for the default action.

Also if you start a broadcast receiver from the button, the notification drawer doesn't close.

I ended up creating a new NotificationActivity to address these issues. This intermediary activity without any UI cancels the notification and then starts the activity I really wanted to start from the notification.

I've posted sample code in a related post Clicking Android Notification Actions does not close Notification drawer.

JavaScript: set dropdown selected item based on option text

var textToFind = 'Google';

var dd = document.getElementById('MyDropDown');
for (var i = 0; i < dd.options.length; i++) {
    if (dd.options[i].text === textToFind) {
        dd.selectedIndex = i;
        break;
    }
}

Get a particular cell value from HTML table using JavaScript

You can get cell value with JS even when click on the cell:

.......................

      <head>

        <title>Search students by courses/professors</title>

        <script type="text/javascript">

        function ChangeColor(tableRow, highLight)
        {
           if (highLight){
               tableRow.style.backgroundColor = '00CCCC';
           }

        else{
             tableRow.style.backgroundColor = 'white';
            }   
      }

      function DoNav(theUrl)
      {
      document.location.href = theUrl;
      }
      </script>

    </head>
    <body>

         <table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">

                <% for (Course cs : courses){ %>

                <tr onmouseover="ChangeColor(this, true);" 
                    onmouseout="ChangeColor(this, false);" 
                    onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">

                     <td name = "title" align = "center"><%= cs.getTitle() %></td>

                </tr>
               <%}%>

    ........................
    </body>

I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.

The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:

onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"

This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.

I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.

The example is working.I've seen.

How does delete[] know it's an array?

Agree that the compiler doesn't know if it is an array or not. It is up to the programmer.

The compiler sometimes keep track of how many objects need to be deleted by over-allocating enough to store the array size, but not always necessary.

For a complete specification when extra storage is allocated, please refer to C++ ABI (how compilers are implemented): Itanium C++ ABI: Array Operator new Cookies

New line character in VB.Net?

In this case, I can use vbNewLine, vbCrLf or "\r\n".

How to put Google Maps V2 on a Fragment using ViewPager

When you add yor map use:

getChildFragmentManager().beginTransaction()
    .replace(R.id.menu_map_container, mapFragment, "f" + shabbatIndex).commit();

instead of .add and instead of getFragmentManager.

Injection of autowired dependencies failed;

public class Organization {

    @Id
    @Column(name="org_id")
    @GeneratedValue
    private int id;

    @Column(name="org_name")
    private String name;

    @Column(name="org_office_address1")
    private String address1;

    @Column(name="org_office_addres2")
    private String address2;

    @Column(name="city")
    private String city;

    @Column(name="state")
    private String state;

    @Column(name="country")
    private String country;

    @JsonIgnore
    @OneToOne
    @JoinColumn(name="pkg_id")
    private int pkgId;

    public int getPkgId() {
        return pkgId;
    }

    public void setPkgId(int pkgId) {
        this.pkgId = pkgId;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Column(name="pincode")
    private String pincode;

    @OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);

    @Column(name="status")
    private String status = "ACTIVE";

    @Column(name="project_id")
    private int redmineProjectId;

    public int getRedmineProjectId() {
        return redmineProjectId;
    }

    public void setRedmineProjectId(int redmineProjectId) {
        this.redmineProjectId = redmineProjectId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Set<OrganizationBranch> getOrganizationBranch() {
        return organizationBranch;
    }

    public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
        this.organizationBranch = organizationBranch;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }
}

You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired

What does "<>" mean in Oracle

not equals. See here for a list of conditions

Java: Check if command line arguments are null

To expand upon this point:

It is possible that the args variable itself will be null, but not via normal execution. Normal execution will use java.exe as the entry point from the command line. However, I have seen some programs that use compiled C++ code with JNI to use the jvm.dll, bypassing the java.exe entirely. In this case, it is possible to pass NULL to the main method, in which case args will be null.

I recommend always checking if ((args == null) || (args.length == 0)), or if ((args != null) && (args.length > 0)) depending on your need.

Save child objects automatically using JPA Hibernate

Here are the ways to assign parent object in child object of Bi-directional relations ?

Suppose you have a relation say One-To-Many,then for each parent object,a set of child object exists. In bi-directional relations,each child object will have reference to its parent.

eg : Each Department will have list of Employees and each Employee is part of some department.This is called Bi directional relations.

To achieve this, one way is to assign parent in child object while persisting parent object

Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);

List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChilds(children);

session.save(parent);

Other way is, you can do using hibernate Intercepter,this way helps you not to write above code for all models.

Hibernate interceptor provide apis to do your own work before perform any DB operation.Likewise onSave of object, we can assign parent object in child objects using reflection.

public class CustomEntityInterceptor extends EmptyInterceptor {

    @Override
    public boolean onSave(
            final Object entity, final Serializable id, final Object[] state, final String[] propertyNames,
            final Type[] types) {
        if (types != null) {
            for (int i = 0; i < types.length; i++) {
                if (types[i].isCollectionType()) {
                    String propertyName = propertyNames[i];
                    propertyName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
                    try {
                        Method method = entity.getClass().getMethod("get" + propertyName);
                        List<Object> objectList = (List<Object>) method.invoke(entity);

                        if (objectList != null) {
                            for (Object object : objectList) {
                                String entityName = entity.getClass().getSimpleName();
                                Method eachMethod = object.getClass().getMethod("set" + entityName, entity.getClass());
                                eachMethod.invoke(object, entity);
                            }
                        }

                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return true;
    }

}

And you can register Intercepter to configuration as

new Configuration().setInterceptor( new CustomEntityInterceptor() );

Marquee text in Android

Here is an example:

public class TextViewMarquee extends Activity {
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) this.findViewById(R.id.mywidget);  
        tv.setSelected(true);  // Set focus to the textview
    }
}

The xml file with the textview:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/mywidget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:textColor="#ff4500"
        android:text="Simple application that shows how to use marquee, with a long text" />
</RelativeLayout>

How can I view array structure in JavaScript with alert()?

Better use Firebug (chrome console etc) and use console.dir()

Youtube - downloading a playlist - youtube-dl

Removing the v=...& part from the url, and only keep the list=... part. The main problem being the special character &, interpreted by the shell.

You can also quote your 'url' in your command.

More information here (for instance) :

https://askubuntu.com/questions/564567/how-to-download-playlist-from-youtube-dl

Vue-router redirect on page not found (404)

I think you should be able to use a default route handler and redirect from there to a page outside the app, as detailed below:

const ROUTER_INSTANCE = new VueRouter({
    mode: "history",
    routes: [
        { path: "/", component: HomeComponent },
        // ... other routes ...
        // and finally the default route, when none of the above matches:
        { path: "*", component: PageNotFound }
    ]
})

In the above PageNotFound component definition, you can specify the actual redirect, that will take you out of the app entirely:

Vue.component("page-not-found", {
    template: "",
    created: function() {
        // Redirect outside the app using plain old javascript
        window.location.href = "/my-new-404-page.html";
    }
}

You may do it either on created hook as shown above, or mounted hook also.

Please note:

  1. I have not verified the above. You need to build a production version of app, ensure that the above redirect happens. You cannot test this in vue-cli as it requires server side handling.

  2. Usually in single page apps, server sends out the same index.html along with app scripts for all route requests, especially if you have set <base href="/">. This will fail for your /404-page.html unless your server treats it as a special case and serves the static page.

Let me know if it works!

Update for Vue 3 onward:

You'll need to replace the '*' path property with '/:pathMatch(.*)*' if you're using Vue 3 as the old catch-all path of '*' is no longer supported. The route would then look something like this:

{ path: '/:pathMatch(.*)*', component: PathNotFound },

See the docs for more info on this update.

How to add Button over image using CSS?

If I understood correctly, I would change the HTML to something like this:

<div id="shop">
    <div class="content">
        <img src="http://placehold.it/182x121"/> 
        <a href="#">Counter-Strike 1.6 Steam</a>
    </div>
</div>

Then I would be able to use position:absolute and position:relative to force the blue button down.

I have created a jsfiddle: http://jsfiddle.net/y9w99/

jQuery UI " $("#datepicker").datepicker is not a function"

Also check the permissions for the directory you download the files into. For some reason when I downloaded this, by default it was saved in a folder with no access allowed! It took forever to figure out that was the problem, but I just had to change the permission for the directory and it's contents - setting it so EVERYONE = READ ONLY. Works great now.

"inconsistent use of tabs and spaces in indentation"

I had the same error. I had to add several code lines to an existing *.py file. In Notepad++ it did not work.

After adding the code lines and saving, I got the same error. When I opened the same file in PyCharm and added the lines, the error disappeared.

I want to multiply two columns in a pandas DataFrame and add the result into a new column

For me, this is the clearest and most intuitive:

values = []
for action in ['Sell','Buy']:
    amounts = orders_df['Amounts'][orders_df['Action'==action]].values
    if action == 'Sell':
        prices = orders_df['Prices'][orders_df['Action'==action]].values
    else:
        prices = -1*orders_df['Prices'][orders_df['Action'==action]].values
    values += list(amounts*prices)  
orders_df['Values'] = values

The .values method returns a numpy array allowing you to easily multiply element-wise and then you can cumulatively generate a list by 'adding' to it.

Initialize class fields in constructor or at declaration?

My rules:

  1. Don't initialize with the default values in declaration (null, false, 0, 0.0…).
  2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
  3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
  4. Be consistent in your practice (the most important rule).

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

OpenSSL and error in reading openssl.conf file

If you have installed Apache with OpenSSL navigate to bin directory. In my case D:\apache\bin.

*These commands also work if you have stand alone installation of openssl.

Run these commands:

openssl req -config d:\apache\conf\openssl.cnf -new -out d:\apache\conf\server.csr -keyout d:\apache\conf\server.pem
openssl rsa -in d:\apache\conf\server.pem -out d:\apache\conf\server.key
openssl x509 -in d:\apache\conf\server.csr -out d:\apache\conf\server.crt -req -signkey d:\apache\conf\server.key -days 365

*This will create self-signed certificate that you can use for development purposes

Again if you have Apache installed in the httpd.conf stick these:

  <IfModule ssl_module>
    SSLEngine on
    SSLCertificateFile "D:/apache/conf/server.crt"
    SSLCertificateKeyFile "D:/apache/conf/server.key"
  </IfModule>

When creating a service with sc.exe how to pass in context parameters?

I had issues getting this to work on Windows 7. It seemed to ignore the first argument I passed in so I used binPath= "C:\path\to\service.exe -bogusarg -realarg1 -realarg2" and it worked.

How do I grant myself admin access to a local SQL Server instance?

Open a command prompt window. If you have a default instance of SQL Server already running, run the following command on the command prompt to stop the SQL Server service:

net stop mssqlserver

Now go to the directory where SQL server is installed. The directory can for instance be one of these:

C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn
C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn

Figure out your MSSQL directory and CD into it as such:

CD C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn

Now run the following command to start SQL Server in single user mode. As SQLCMD is being specified, only one SQLCMD connection can be made (from another command prompt window).

sqlservr -m"SQLCMD"

Now, open another command prompt window as the same user as the one that started SQL Server in single user mode above, and in it, run:

sqlcmd

And press enter. Now you can execute SQL statements against the SQL Server instance running in single user mode:

create login [<<DOMAIN\USERNAME>>] from windows;

-- For older versions of SQL Server:
EXEC sys.sp_addsrvrolemember @loginame = N'<<DOMAIN\USERNAME>>', @rolename = N'sysadmin';

-- For newer versions of SQL Server:
ALTER SERVER ROLE [sysadmin] ADD MEMBER [<<DOMAIN\USERNAME>>];

GO

Source.

UPDATED Do not forget a semicolon after ALTER SERVER ROLE [sysadmin] ADD MEMBER [<<DOMAIN\USERNAME>>]; and do not add extra semicolon after GO or the command never executes.

How can I check whether a numpy array is empty or not?

Why would we want to check if an array is empty? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append is a frequent novice error.

Using a list in if alist: hinges on its boolean value:

In [102]: bool([])                                                                       
Out[102]: False
In [103]: bool([1])                                                                      
Out[103]: True

But trying to do the same with an array produces (in version 1.18):

In [104]: bool(np.array([]))                                                             
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value 
   of an empty array is ambiguous. Returning False, but in 
   future this will result in an error. Use `array.size > 0` to 
   check that an array is not empty.
  #!/usr/bin/python3
Out[104]: False

In [105]: bool(np.array([1]))                                                            
Out[105]: True

and bool(np.array([1,2]) produces the infamous ambiguity error.

edit

The accepted answer suggests size:

In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0

But I (and most others) check the shape more than the size:

In [13]: x.shape
Out[13]: (0,)

Another thing in its favor is that it 'maps' on to an empty list:

In [14]: x.tolist()
Out[14]: []

But there are other other arrays with 0 size, that aren't 'empty' in that last sense:

In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True

np.array([[],[]]) is also size 0, but shape (2,0) and len 2.

While the concept of an empty list is well defined, an empty array is not well defined. One empty list is equal to another. The same can't be said for a size 0 array.

The answer really depends on

  • what do you mean by 'empty'?
  • what are you really test for?

How to remove the last character from a string?

Most answers here forgot about surrogate pairs.

For instance, the character (codepoint U+1D56B) does not fit into a single char, so in order to be represented, it must form a surrogate pair of two chars.

If one simply applies the currently accepted answer (using str.substring(0, str.length() - 1), one splices the surrogate pair, leading to unexpected results.

One should also include a check whether the last character is a surrogate pair:

public static String removeLastChar(String str) {
    Objects.requireNonNull(str, "The string should not be null");
    if (str.isEmpty()) {
        return str;
    }

    char lastChar = str.charAt(str.length() - 1);
    int cut = Character.isSurrogate(lastChar) ? 2 : 1;
    return str.substring(0, str.length() - cut);
}

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

Replace substring with another substring C++

std::string replace(std::string str, std::string substr1, std::string substr2)
{
    for (size_t index = str.find(substr1, 0); index != std::string::npos && substr1.length(); index = str.find(substr1, index + substr2.length() ) )
        str.replace(index, substr1.length(), substr2);
    return str;
}

Short solution where you don't need any extra Libraries.

Posting raw image data as multipart/form-data in curl

As of PHP 5.6 @$filePath will not work in CURLOPT_POSTFIELDS without CURLOPT_SAFE_UPLOAD being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.

$fields = [
    'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);

Sorting list based on values from another list

You can create a pandas Series, using the primary list as data and the other list as index, and then just sort by the index:

import pandas as pd
pd.Series(data=X,index=Y).sort_index().tolist()

output:

['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

Can attributes be added dynamically in C#?

Well, just to be different, I found an article that references using Reflection.Emit to do so.

Here's the link: http://www.codeproject.com/KB/cs/dotnetattributes.aspx , you will also want to look into some of the comments at the bottom of the article, because possible approaches are discussed.

Running the new Intel emulator for Android

I had the same issue, solved it by Installing the Intel Hardware Accelerated Execution Manager. Download it with the SDK Manager, it's in Extras. After this, go to the folder

[Android SDK Root]\extras\intel\Hardware_Accelerated_Execution_Manager

then run IntelHaxm.exe and install.

Here the link of the Intel Hardware Accelerated IntelHaxm.exe for Microsoft Windows,Mac OS* X, and Linux Ubuntu

enter image description here

You'll get the following message if you don't have virtualization enabled in your BIOS:

enter image description here

What is getattr() exactly and how do I use it?

It is also clarifying from https://www.programiz.com/python-programming/methods/built-in/getattr

class Person:
    age = 23
    name = "Adam"

person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)

The age is: 23

The age is: 23

class Person:
    age = 23
    name = "Adam"

person = Person()

# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))

# when no default value is provided
print('The sex is:', getattr(person, 'sex'))

The sex is: Male

AttributeError: 'Person' object has no attribute 'sex'

When do I have to use interfaces instead of abstract classes?

With support of default methods in interface since launch of Java 8, the gap between interface and abstract classes has been reduced but still they have major differences.

  1. Variables in interface are public static final. But abstract class can have other type of variables like private, protected etc

  2. Methods in interface are public or public static but methods in abstract class can be private and protected too

  3. Use abstract class to establish relation between interrelated objects. Use interface to establish relation between unrelated classes.

Have a look at this article for special properties of interface in java 8. static modifier for default methods in interface causes compile time error in derived error if you want to use @override.

This article explains why default methods have been introduced in java 8 : To enhance the Collections API in Java 8 to support lambda expressions.

Have a look at oracle documentation too to understand the differences in better way.

Have a look at this related SE questions with code example to understand things in better way:

How should I have explained the difference between an Interface and an Abstract class?

How do I get a file name from a full path with PHP?

basename() has a bug when processing Asian characters like Chinese.

I use this:

function get_basename($filename)
{
    return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}

How to save local data in a Swift app?

For Swift 4.0, this got easier:

let defaults = UserDefaults.standard
//Set
defaults.set(passwordTextField.text, forKey: "Password")
//Get
let myPassword = defaults.string(forKey: "Password")

How do I create a URL shortener?

Why not just generate a random string and append it to the base URL? This is a very simplified version of doing this in C#.

static string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
static string baseUrl = "https://google.com/";

private static string RandomString(int length)
{
    char[] s = new char[length];
    Random rnd = new Random();
    for (int x = 0; x < length; x++)
    {
        s[x] = chars[rnd.Next(chars.Length)];
    }
    Thread.Sleep(10);

    return new String(s);
}

Then just add the append the random string to the baseURL:

string tinyURL = baseUrl + RandomString(5);

Remember this is a very simplified version of doing this and it's possible the RandomString method could create duplicate strings. In production you would want to take in account for duplicate strings to ensure you will always have a unique URL. I have some code that takes account for duplicate strings by querying a database table I could share if anyone is interested.

Bigger Glyphicons

Here's how I do it:

<span style="font-size:1.5em;" class="glyphicon glyphicon-th-list"></span>

This allows you to change size on the fly. Works best for ad hoc requirements to change the size, rather than changing the css and having it apply to all.

How to get the title of HTML page with JavaScript?

Put in the URL bar and then click enter:

javascript:alert(document.title);

You can select and copy the text from the alert depending on the website and the web browser you are using.

Inserting one list into another list in java?

An object is only once in memory. Your first addition to list just adds the object references.

anotherList.addAll will also just add the references. So still only 100 objects in memory.

If you change list by adding/removing elements, anotherList won't be changed. But if you change any object in list, then it's content will be also changed, when accessing it from anotherList, because the same reference is being pointed to from both lists.

CSS @font-face not working in ie

1) Try putting an absolute link not relative link to your eot font - somehow old IE just don't know in which folder the css file is 2) make 2 extra @font-face declarations so it should look like this:

@font-face { /* for modern browsers and modern IE */
    font-family: "Futura";
    src: url("../fonts/Futura_Medium_BT.eot"); 
    src: url("../fonts/Futura_Medium_BT.eot?#iefix") format("embedded-opentype"), 
    url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); 
}
@font-face{ /* for old IE */
  font-family: "Futura_IE"; 
  src: url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot);
}

@font-face{ /* for old IE */
  font-family: "Futura_IE2"; 
  src:url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot?#iefix) 
  format("embedded-opentype");
}

.p{ font-family: "Futura", "Futura_IE", "Futura_IE2", Arial, sans-serif;

This is an example for wordpress template - absolute link should point from where your start index file is.

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

find all subsets that sum to a particular value

My backtracking solution :- Sort the array , then apply the backtracking.

void _find(int arr[],int end,vector<int> &v,int start,int target){
        if(target==0){
        for(int i = 0;i<v.size();i++){
            cout<<v[i]<<" ";
        }
        cout<<endl;
    }

    else{
        for(int i =  start;i<=end && target >= arr[i];i++){
            v.push_back(arr[i]);
            _find(arr,end,v,i+1,target-arr[i]);
            v.pop_back();
        }
    }
}

How to store and retrieve a dictionary with redis

If you don't know exactly how to organize data in Redis, I did some performance tests, including the results parsing. The dictonary I used (d) had 437.084 keys (md5 format), and the values of this form:

{"path": "G:\tests\2687.3575.json",
 "info": {"f": "foo", "b": "bar"},
 "score": 2.5}

First Test (inserting data into a redis key-value mapping):

conn.hmset('my_dict', d)  # 437.084 keys added in 8.98s

conn.info()['used_memory_human']  # 166.94 Mb

for key in d:
    json.loads(conn.hget('my_dict', key).decode('utf-8').replace("'", '"'))
    #  41.1 s

import ast
for key in d:
    ast.literal_eval(conn.hget('my_dict', key).decode('utf-8'))
    #  1min 3s

conn.delete('my_dict')  # 526 ms

Second Test (inserting data directly into Redis keys):

for key in d:
    conn.hmset(key, d[key])  # 437.084 keys added in 1min 20s

conn.info()['used_memory_human']  # 326.22 Mb

for key in d:
    json.loads(conn.hgetall(key)[b'info'].decode('utf-8').replace("'", '"'))
    #  1min 11s

for key in d:
    conn.delete(key)
    #  37.3s

As you can see, in the second test, only 'info' values have to be parsed, because the hgetall(key) already returns a dict, but not a nested one.

And of course, the best example of using Redis as python's dicts, is the First Test

CSS background-image - What is the correct usage?

just write in your css file like bellow

background:url("images/logo.jpg")

Export data from Chrome developer tool

I don't see an export or save as option.

I filtered out all the unwanted requests using -.css -.js -.woff then right clicked on one of the requests then Copy > Copy all as HAR

Then pasted the content into a text editor and saved it.

Count elements with jQuery

use the .size() method or .length attribute

Create ArrayList from array

// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray); 

Aligning label and textbox on same line (left and right)

You can do it with a table, like this:

<table width="100%">
  <tr>
    <td style="width: 50%">Left Text</td>
    <td style="width: 50%; text-align: right;">Right Text</td>
  </tr>
</table>

Or, you can do it with CSS like this:

<div style="float: left;">
    Left text
</div>
<div style="float: right;">
    Right text
</div>

Linear Layout and weight in Android

Below are the changes (Marked in BOLD) in your code:

<LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="0dp" //changes made here
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" /> //changes made here

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="0dp" //changes made here
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" /> //changes made here

  </LinearLayout>

Since your LinearLayout has orientation as horizontal, therefore you will need to keep your width only as 0dp. for using weights in that direction . (If your orientation was vertical, you would have kept your height only 0dp).

Since there are 2 views and you have placed android:layout_weight="1" for both the views, it means it will divide the two views equally in horizontal direction (or by width).

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

Substring a string from the end of the string

What about

string s = "Hello Marco !";
s = s.Substring(0, s.Length - 2);

How to create an integer-for-loop in Ruby?

x.times do |i|
    something(i+1)
end

How to compare binary files to check if they are the same?

md5sum binary1 binary2

If the md5sum is same, binaries are same

E.g

md5sum new*
89c60189c3fa7ab5c96ae121ec43bd4a  new.txt
89c60189c3fa7ab5c96ae121ec43bd4a  new1.txt
root@TinyDistro:~# cat new*
aa55 aa55 0000 8010 7738
aa55 aa55 0000 8010 7738


root@TinyDistro:~# cat new*
aa55 aa55 000 8010 7738
aa55 aa55 0000 8010 7738
root@TinyDistro:~# md5sum new*
4a7f86919d4ac00c6206e11fca462c6f  new.txt
89c60189c3fa7ab5c96ae121ec43bd4a  new1.txt

"Line contains NULL byte" in CSV reader (Python)

This will tell you what line is the problem.

import csv

lines = []
with open('output.txt','r') as f:
    for line in f.readlines():
        lines.append(line[:-1])

with open('corrected.csv','w') as correct:
    writer = csv.writer(correct, dialect = 'excel')
    with open('input.csv', 'r') as mycsv:
        reader = csv.reader(mycsv)
        try:
            for i, row in enumerate(reader):
                if row[0] not in lines:
                   writer.writerow(row)
        except csv.Error:
            print('csv choked on line %s' % (i+1))
            raise

Perhaps this from daniweb would be helpful:

I'm getting this error when reading from a csv file: "Runtime Error! line contains NULL byte". Any idea about the root cause of this error?

...

Ok, I got it and thought I'd post the solution. Simply yet caused me grief... Used file was saved in a .xls format instead of a .csv Didn't catch this because the file name itself had the .csv extension while the type was still .xls

Change all files and folders permissions of a directory to 644/755

Do both in a single pass with:

find -type f ... -o -type d ...

As in, find type f OR type d, and do the first ... for files and the second ... for dirs. Specifically:

find -type f -exec chmod --changes 644 {} + -o -type d -exec chmod --changes 755 {} +

Leave off the --changes if you want it to work silently.

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Unicode characters in URLs

What Tgr said. Background:

http://www.example.com/düsseldorf?neighbourhood=Lörick

That's not a URI. But it is an IRI.

You can't include an IRI in an HTML4 document; the type of attributes like href is defined as URI and not IRI. Some browsers will handle an IRI here anyway, but it's not really a good idea.

To encode an IRI into a URI, take the path and query parts, UTF-8-encode them then percent-encode the non-ASCII bytes:

http://www.example.com/d%C3%BCsseldorf?neighbourhood=L%C3%B6rick

If there are non-ASCII characters in the hostname part of the IRI, eg. http://??.???/, they have be encoded using Punycode instead.

Now you have a URI. It's an ugly URI. But most browsers will hide that for you: copy and paste it into the address bar or follow it in a link and you'll see it displayed with the original Unicode characters. Wikipedia have been using this for years, eg.:

http://en.wikipedia.org/wiki/?

The one browser whose behaviour is unpredictable and doesn't always display the pretty IRI version is...

...well, you know.

Xpath: select div that contains class AND whose specific child element contains text

You can change your second condition to check only the span element:

...and contains(div/span, 'someText')]

If the span isn't always inside another div you can also use

...and contains(.//span, 'someText')]

This searches for the span anywhere inside the div.

MySQL default datetime through phpmyadmin

You can't set CURRENT_TIMESTAMP as default value with DATETIME.

But you can do it with TIMESTAMP.

See the difference here.

Words from this blog

The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.

The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.

setup.py examples?

I recommend the setup.py of the Python Packaging User Guide's example project.

The Python Packaging User Guide "aims to be the authoritative resource on how to package, publish and install Python distributions using current tools".

How to upload file using Selenium WebDriver in Java

Find the tag as type="file". this the main tag which is supported by selenium. If you are able to build your XPath with same when it is recommended.

  • use sendkeys for the button having browse option(The button which will open your window box to select files)
  • Now click on the button which is going to upload your file

As below :-

driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"Lighthouse.jpg"");
Thread.sleep(5000);    
driver.findElement(By.xpath("//button[@id='Upload']")).click(); 

For multiple file upload put all files one by one by sendkeys and then click on upload

driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"Lighthouse.jpg"");  
driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"home.jpg");
driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"tsquare.jpg");
Thread.sleep(5000); 
driver.findElement(By.xpath("//button[@id='Upload']")).click(); // Upload button

What does "wrong number of arguments (1 for 0)" mean in Ruby?

I assume you called a function with an argument which was defined without taking any.

def f()
  puts "hello world"
end

f(1)   # <= wrong number of arguments (1 for 0)

How to get domain URL and application name?

The application name come from getContextPath.

I find this graphic from Agile Software Craftsmanship HttpServletRequest Path Decoding sorts out all the different methods that are available:

enter image description here

Linker command failed with exit code 1 - duplicate symbol __TMRbBp

I had similar issues with Version 9.2 (9C40b), the solution is

0) Close Xcode
1) Open project folder in terminal
2) pod update
3) open .
4) open project by clicking Project.xcworkspace

Include headers when using SELECT INTO OUTFILE?

Here is a way to get the header titles from the column names dynamically.

/* Change table_name and database_name */
SET @table_name = 'table_name';
SET @table_schema = 'database_name';
SET @default_group_concat_max_len = (SELECT @@group_concat_max_len);

/* Sets Group Concat Max Limit larger for tables with a lot of columns */
SET SESSION group_concat_max_len = 1000000;

SET @col_names = (
  SELECT GROUP_CONCAT(QUOTE(`column_name`)) AS columns
  FROM information_schema.columns
  WHERE table_schema = @table_schema
  AND table_name = @table_name);

SET @cols = CONCAT('(SELECT ', @col_names, ')');

SET @query = CONCAT('(SELECT * FROM ', @table_schema, '.', @table_name,
  ' INTO OUTFILE \'/tmp/your_csv_file.csv\'
  FIELDS ENCLOSED BY \'\\\'\' TERMINATED BY \'\t\' ESCAPED BY \'\'
  LINES TERMINATED BY \'\n\')');

/* Concatenates column names to query */
SET @sql = CONCAT(@cols, ' UNION ALL ', @query);

/* Resets Group Contact Max Limit back to original value */
SET SESSION group_concat_max_len = @default_group_concat_max_len;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Test if something is not undefined in JavaScript

typeof:

var foo;
if (typeof foo == "undefined"){
  //do stuff
}

Default parameters with C++ constructors

If creating constructors with arguments is bad (as many would argue), then making them with default arguments is even worse. I've recently started to come around to the opinion that ctor arguments are bad, because your ctor logic should be as minimal as possible. How do you deal with error handling in the ctor, should somebody pass in an argument that doesn't make any sense? You can either throw an exception, which is bad news unless all of your callers are prepared to wrap any "new" calls inside of try blocks, or setting some "is-initialized" member variable, which is kind of a dirty hack.

Therefore, the only way to make sure that the arguments passed into the initialization stage of your object is to set up a separate initialize() method where you can check the return code.

The use of default arguments is bad for two reasons; first of all, if you want to add another argument to the ctor, then you are stuck putting it at the beginning and changing the entire API. Furthermore, most programmers are accustomed to figuring out an API by the way that it's used in practice -- this is especially true for non-public API's used inside of an organization where formal documentation may not exist. When other programmers see that the majority of the calls don't contain any arguments, they will do the same, remaining blissfully unaware of the default behavior your default arguments impose on them.

Also, it's worth noting that the google C++ style guide shuns both ctor arguments (unless absolutely necessary), and default arguments to functions or methods.

Python method for reading keypress?

See the MSDN getch docs. Specifically:

The _getch and_getwch functions read a single character from the console without echoing the character. None of these functions can be used to read CTRL+C. When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.

The Python function returns a character. you can use ord() to get an integer value you can test, for example keycode = ord(msvcrt.getch()).

So if you read an 0x00 or 0xE0, read it a second time to get the key code for an arrow or function key. From experimentation, 0x00 precedes F1-F10 (0x3B-0x44) and 0xE0 precedes arrow keys and Ins/Del/Home/End/PageUp/PageDown.

Access cell value of datatable

string abc= dt.Rows[0]["column name"].ToString();

How to set the default value for radio buttons in AngularJS?

<div ng-app="" ng-controller="myCntrl">    
        <input type="radio" ng-model="people" value="1"/><label>1</label>
        <input type="radio" ng-model="people" value="2"/><label>2</label>
        <input type="radio" ng-model="people" value="3"/><label>3</label>
</div>
<script>
    function myCntrl($scope){
        $scope.people=1;
    }
</script>

What does the "On Error Resume Next" statement do?

When an error occurs, the execution will continue on the next line without interrupting the script.

Is either GET or POST more secure than the other?

There is no added security.

Post data does not show up in the history and/or log files but if the data should be kept secure, you need SSL.
Otherwise, anybody sniffing the wire can read your data anyway.

Batch command date and time in file name

Your question seems to be solved, but ...

I'm not sure if you take the right solution for your problem.
I suppose you try to compress each day the actual project code.

It's possible with ZIP and 1980 this was a good solution, but today you should use a repository system, like subversion or git or ..., but not a zip-file.

Ok, perhaps it could be that I'm wrong.

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

How to list all `env` properties within jenkins pipeline job?

According to Jenkins documentation for declarative pipeline:

sh 'printenv'

For Jenkins scripted pipeline:

echo sh(script: 'env|sort', returnStdout: true)

The above also sorts your env vars for convenience.

MySQL: determine which database is selected?

slightly off-topic (using the CLI instead of PHP), but still worth knowing: You can set the prompt to display the default database by using any of the following

mysql --prompt='\d> '
export MYSQL_PS1='\d> '

or once inside

prompt \d>\_
\R \d>\_

How to create a private class method?

As of ruby 2.3.0

class Check
  def self.first_method
    second_method
  end

  private
  def self.second_method
    puts "well I executed"
  end
end

Check.first_method
#=> well I executed

How to find a text inside SQL Server procedures / triggers?

SELECT ROUTINE_TYPE, ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_DEFINITION LIKE '%Your Text%' 

Initialize a string in C to empty string

Assuming your array called 'string' already exists, try

string[0] = '\0';

\0 is the explicit NUL terminator, required to mark the end of string.

RSA Public Key format

Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser

RSA Public Key

-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----

Encrypted Private Key

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----

CRL

-----BEGIN X509 CRL-----
-----END X509 CRL-----

CRT

-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

CSR

-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----

NEW CSR

-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----

PEM

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

PKCS7

-----BEGIN PKCS7-----
-----END PKCS7-----

PRIVATE KEY

-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----

DSA KEY

-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----

Elliptic Curve

-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----

PGP Private Key

-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----

PGP Public Key

-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----

Dynamic SQL results into temp table in SQL Stored procedure

DECLARE @EmpGroup INT =3 ,
        @IsActive BIT=1

DECLARE @tblEmpMaster AS TABLE
        (EmpCode VARCHAR(20),EmpName VARCHAR(50),EmpAddress VARCHAR(500))

INSERT INTO @tblEmpMaster EXECUTE SPGetEmpList @EmpGroup,@IsActive

SELECT * FROM @tblEmpMaster

Find if a textbox is disabled or not using jquery

You can find if the textbox is disabled using is method by passing :disabled selector to it. Try this.

if($('textbox').is(':disabled')){
     //textbox is disabled
}

check if variable empty

empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:

if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}

CertificateException: No name matching ssl.someUrl.de found

It looks like the certificate of the server you are trying to connect to doesn't match its hostname.

When an HTTPS client connects to a server, it verifies that the hostname in the certificate matches the hostname of the server. It's not enough for a certificate to be trusted, it has to match the server you want to talk to too. (As an analogy, even if you trust a passport to be legitimate, you still have to check that it's the one for the person you want to talk to, not just any passport you would trust to be legitimate.)

In HTTP, this is done by checking that:

  • the certificate contains a DNS subject alternative name (this is a standard extension) entry matching the hostname;

  • failing that, the last CN of your subject distinguished name (this is the main name if you want) matches the hostname. (See RFC 2818.)

It's hard to tell what the subject alternative name is without having the certificate (although, if you connect with your browser and check its content in more details, you should be able to see it.) The subject distinguished name seems to be:

[email protected], CN=plesk, OU=Plesk, O=Parallels, L=Herndon, ST=Virginia, C=US

(It would thus need to be CN=ssl.someUrl.de instead of CN=plesk, if you don't have a subject alternative name with DNS:ssl.someUrl.de already; my guess is that you don't.)

You may be able to bypass the hostname verification using HttpsURLConnection.setHostnameVerifier(..). It shouldn't be too hard to write a custom HostnameVerifier that bybasses the verification, although I would suggest doing it only when the certificate its the one concerned here specifically. You should be able to get that using the SSLSession argument and its getPeerCertificates() method.

(In addition, you don't need to set the javax.net.ssl.* properties the way you've done it, since you're using the default values anyway.)

Alternatively, if you have control over the server you're connecting to and its certificate, you can create a certificate of it that matches the naming rules above (CN should be sufficient, although subject alternative name is an improvement). If a self-signed certificate is good enough for what you name, make sure its common name (CN) is the host name you're trying to talk to (no the full URL, just the hostname).

How to remove html special chars?

Either decode them using html_entity_decode or remove them using preg_replace:

$Content = preg_replace("/&#?[a-z0-9]+;/i","",$Content); 

(From here)

EDIT: Alternative according to Jacco's comment

might be nice to replace the '+' with {2,8} or something. This will limit the chance of replacing entire sentences when an unencoded '&' is present.

$Content = preg_replace("/&#?[a-z0-9]{2,8};/i","",$Content); 

Undo working copy modifications of one file in Git?

I restore my files using the SHA id, What i do is git checkout <sha hash id> <file name>

jQuery vs document.querySelectorAll

To understand why jQuery is so popular, it's important to understand where we're coming from!

About a decade ago, top browsers were IE6, Netscape 8 and Firefox 1.5. Back in those days, there were little cross-browser ways to select an element from the DOM besides Document.getElementById().

So, when jQuery was released back in 2006, it was pretty revolutionary. Back then, jQuery set the standard for how to easily select / change HTML elements and trigger events, because its flexibility and browser support were unprecedented.

Now, more than a decade later, a lot of features that made jQuery so popular have become included in the javaScript standard:

These weren't generally available back in 2005. The fact that they are today obviously begs the question of why we should use jQuery at all. And indeed, people are increasingly wondering whether we should use jQuery at all.

So, if you think you understand JavaScript well enough to do without jQuery, please do! Don't feel forced to use jQuery, just because so many others are doing it!

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

Packing and byte alignment, as described in the C FAQ here:

It's for alignment. Many processors can't access 2- and 4-byte quantities (e.g. ints and long ints) if they're crammed in every-which-way.

Suppose you have this structure:

struct {
    char a[3];
    short int b;
    long int c;
    char d[3];
};

Now, you might think that it ought to be possible to pack this structure into memory like this:

+-------+-------+-------+-------+
|           a           |   b   |
+-------+-------+-------+-------+
|   b   |           c           |
+-------+-------+-------+-------+
|   c   |           d           |
+-------+-------+-------+-------+

But it's much, much easier on the processor if the compiler arranges it like this:

+-------+-------+-------+
|           a           |
+-------+-------+-------+
|       b       |
+-------+-------+-------+-------+
|               c               |
+-------+-------+-------+-------+
|           d           |
+-------+-------+-------+

In the packed version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers will pad the structure (as if with extra, invisible fields) like this:

+-------+-------+-------+-------+
|           a           | pad1  |
+-------+-------+-------+-------+
|       b       |     pad2      |
+-------+-------+-------+-------+
|               c               |
+-------+-------+-------+-------+
|           d           | pad3  |
+-------+-------+-------+-------+

What is a tracking branch?

The Pro Git book mentions:

Tracking branches are local branches that have a direct relationship to a remote branch

Not exactly. The SO question "Having a hard time understanding git-fetch" includes:

There's no such concept of local tracking branches, only remote tracking branches.
So origin/master is a remote tracking branch for master in the origin repo.

But actually, once you establish an upstream branch relationship between:

  • a local branch like master
  • and a remote tracking branch like origin/master

Then you can consider master as a local tracking branch: It tracks the remote tracking branch origin/master which, in turn, tracks the master branch of the upstream repo origin.

alt text

Calculate days between two Dates in Java 8

Use the DAYS in enum java.time.temporal.ChronoUnit . Below is the Sample Code :

Output : *Number of days between the start date : 2015-03-01 and end date : 2016-03-03 is ==> 368. **Number of days between the start date : 2016-03-03 and end date : 2015-03-01 is ==> -368*

package com.bitiknow.date;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

/**
 * 
 * @author pradeep
 *
 */
public class LocalDateTimeTry {
    public static void main(String[] args) {

        // Date in String format.
        String dateString = "2015-03-01";

        // Converting date to Java8 Local date
        LocalDate startDate = LocalDate.parse(dateString);
        LocalDate endtDate = LocalDate.now();
        // Range = End date - Start date
        Long range = ChronoUnit.DAYS.between(startDate, endtDate);
        System.out.println("Number of days between the start date : " + dateString + " and end date : " + endtDate
                + " is  ==> " + range);

        range = ChronoUnit.DAYS.between(endtDate, startDate);
        System.out.println("Number of days between the start date : " + endtDate + " and end date : " + dateString
                + " is  ==> " + range);

    }

}

Reactive forms - disabled attribute

disabling of mat form fields is exempted if you are using form validation,so do make sure that your form field does not have any validations like(validators.required),this worked for me. for ex:

editUserPhone: new FormControl({value:' ',disabled:true})

this makes the phone numbers of user to be non editable.

How can I change Eclipse theme?

Update December 2012 (19 months later):

The blog post "Jin Mingjian: Eclipse Darker Theme" mentions this GitHub repo "eclipse themes - darker":

enter image description here

The big fun is that, the codes are minimized by using Eclipse4 platform technologies like dependency injection.
It proves that again, the concise codes and advanced features could be achieved by contributing or extending with the external form (like library, framework).
New language is not necessary just for this kind of purpose.


Update July 2012 (14 months later):

With the latest Eclipse4.2 (June 2012, "Juno") release, you can implement what I originally described below: a CSS-based fully dark theme for Eclipse.
See the article by Lars Vogel in "Eclipse 4 is beautiful – Create your own Eclipse 4 theme":

Eclipse fully dark theme

If you want to play with it, you only need to write a plug-in, create a CSS file and use the org.eclipse.e4.ui.css.swt.theme extension point to point to your file.
If you export your plug-in, place it in the “dropins” folder of your Eclipse installation and your styling is available.


Original answer: August 2011

With Eclipse 3.x, theme is only for the editors, as you can see in the site "Eclipse Color Themes".
Anything around that is managed by windows system colors.
That is what you need to change to have any influence on Eclipse global colors around editors.

Eclipse 4 will provide much advance theme options: See "Eclipse 4.0 – So you can theme me Part 1" and "Eclipse 4.0 RCP: Dynamic CSS Theme Switching".

dark theme

Use Font Awesome icon as CSS content

You should have font-weight set to 900 for Font Awesome 5 Free font-family to work.

This is the working one:

.css-selector::before {
   font-family: 'Font Awesome 5 Free';
   content: "\f101";
   font-weight: 900;
}

Python urllib2 Basic Auth Problem

Here's what I'm using to deal with a similar problem I encountered while trying to access MailChimp's API. This does the same thing, just formatted nicer.

import urllib2
import base64

chimpConfig = {
    "headers" : {
    "Content-Type": "application/json",
    "Authorization": "Basic " + base64.encodestring("hayden:MYSECRETAPIKEY").replace('\n', '')
    },
    "url": 'https://us12.api.mailchimp.com/3.0/'}

#perform authentication
datas = None
request = urllib2.Request(chimpConfig["url"], datas, chimpConfig["headers"])
result = urllib2.urlopen(request)

How to get a vCard (.vcf file) into Android contacts from website

What i have also noticed is that you have to save the file as Unicode, UTF-8, no BOM in an Windows format with CRLF (Carriage Return, Line Feed). Because if you don't, the import will break. (Saying something about weird chars in the file)

Good luck :) Sid

How to implement a queue using two stacks?

here is my solution in java using linkedlist.

class queue<T>{
static class Node<T>{
    private T data;
    private Node<T> next;
    Node(T data){
        this.data = data;
        next = null;
    }
}
Node firstTop;
Node secondTop;

void push(T data){
    Node temp = new Node(data);
    temp.next = firstTop;
    firstTop = temp;
}

void pop(){
    if(firstTop == null){
        return;
    }
    Node temp = firstTop;
    while(temp != null){
        Node temp1 = new Node(temp.data);
        temp1.next = secondTop;
        secondTop = temp1;
        temp = temp.next;
    }
    secondTop = secondTop.next;
    firstTop = null;
    while(secondTop != null){
        Node temp3 = new Node(secondTop.data);
        temp3.next = firstTop;
        firstTop = temp3;
        secondTop = secondTop.next;
    }
}

}

Note : In this case, pop operation is very time consuming. So i won't suggest to create a queue using two stack.

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

Try this may will help you.Go to "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.

Reset AutoIncrement in SQL Server after Delete

If you're using MySQL, try this:

ALTER TABLE tablename AUTO_INCREMENT = 1

Installing RubyGems in Windows

To setup you Ruby development environment on Windows:

  1. Install Ruby via RubyInstaller: http://rubyinstaller.org/downloads/

  2. Check your ruby version: Start - Run - type in cmd to open a windows console

  3. Type in ruby -v
  4. You will get something like that: ruby 2.0.0p353 (2013-11-22) [i386-mingw32]

For Ruby 2.4 or later, run the extra installation at the end to install the DevelopmentKit. If you forgot to do that, run ridk install in your windows console to install it.

For earlier versions:

  1. Download and install DevelopmentKit from the same download page as Ruby Installer. Choose an ?exe file corresponding to your environment (32 bits or 64 bits and working with your version of Ruby).
  2. Follow the installation instructions for DevelopmentKit described at: https://github.com/oneclick/rubyinstaller/wiki/Development-Kit#installation-instructions. Adapt it for Windows.
  3. After installing DevelopmentKit you can install all needed gems by just running from the command prompt (windows console or terminal): gem install {gem name}. For example, to install rails, just run gem install rails.

Hope this helps.

How to import existing Android project into Eclipse?

This error message appears when the source code you try to import is inside an existing workspace.

Put your source code in a directory OUTSIDE any existing workspace and then import

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

In case it helps anyone, the C# equivalent of ZloiAdun's answer is:

element.SendKeys(Keys.Control + "a");
element.SendKeys("55");

Creating a textarea with auto-resize

This code works for pasting and select delete also.

_x000D_
_x000D_
onKeyPressTextMessage = function(){_x000D_
   var textArea = event.currentTarget;_x000D_
     textArea.style.height = 'auto';_x000D_
     textArea.style.height = textArea.scrollHeight + 'px';_x000D_
};
_x000D_
<textarea onkeyup="onKeyPressTextMessage(event)" name="welcomeContentTmpl" id="welcomeContent" onblur="onblurWelcomeTitle(event)" rows="2" cols="40" maxlength="320"></textarea>
_x000D_
_x000D_
_x000D_

Here is the JSFiddle

How to increase space between dotted border dots

So starting with the answer given and applying the fact that CSS3 allows multiple settings - the below code is useful for creating a complete box:

_x000D_
_x000D_
#border {_x000D_
  width: 200px;_x000D_
  height: 100px;_x000D_
  background: yellow;_x000D_
  text-align: center;_x000D_
  line-height: 100px;_x000D_
  background: linear-gradient(to right, orange 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(blue 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(to right, green 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(red 50%, rgba(255, 255, 255, 0) 0%);_x000D_
  background-position: top, right, bottom, left;_x000D_
  background-repeat: repeat-x, repeat-y;_x000D_
  background-size: 10px 1px, 1px 10px;_x000D_
}
_x000D_
<div id="border">_x000D_
  bordered area_x000D_
</div>
_x000D_
_x000D_
_x000D_

Its worth noting that the 10px in the background size gives the area that the dash and gap will cover. The 50% of the background tag is how wide the dash actually is. It is therefore possible to have different length dashes on each border side.

How to change the style of the title attribute inside an anchor tag?

I thought i'd post my 20 lines JavaScript solution here. It is not perfect, but may be useful for some depending on what you need from your tooltips.

When to use it

  • Automatically styles the tooltip for all HTML elements with a TITLE attribute defined (this includes elements dynamically added to the document in the future)
  • No Javascript/HTML changes or hacks required for every tooltip (just the TITLE attribute, semantically clear)
  • Very light (adds about 300 bytes gzipped and minified)
  • You want only a very basic styleable tooltip

When NOT to use

  • Requires jQuery, so do not use if you don't use jQuery
  • Bad support for nested elements that both have tooltips
  • You need more than one tooltip on the screen at the same time
  • You need the tooltip to disappear after some time

The code

// Use a closure to keep vars out of global scope
(function () {
    var ID = "tooltip", CLS_ON = "tooltip_ON", FOLLOW = true,
    DATA = "_tooltip", OFFSET_X = 20, OFFSET_Y = 10,
    showAt = function (e) {
        var ntop = e.pageY + OFFSET_Y, nleft = e.pageX + OFFSET_X;
        $("#" + ID).html($(e.target).data(DATA)).css({
            position: "absolute", top: ntop, left: nleft
        }).show();
    };
    $(document).on("mouseenter", "*[title]", function (e) {
        $(this).data(DATA, $(this).attr("title"));
        $(this).removeAttr("title").addClass(CLS_ON);
        $("<div id='" + ID + "' />").appendTo("body");
        showAt(e);
    });
    $(document).on("mouseleave", "." + CLS_ON, function (e) {
        $(this).attr("title", $(this).data(DATA)).removeClass(CLS_ON);
        $("#" + ID).remove();
    });
    if (FOLLOW) { $(document).on("mousemove", "." + CLS_ON, showAt); }
}());

Paste it anywhere, it should work even when you run this code before the DOM is ready (it just won't show your tooltips until DOM is ready).

Customize

You can change the var declarations on the second line to customize it a bit.

var ID = "tooltip"; // The ID of the styleable tooltip
var CLS_ON = "tooltip_ON"; // Does not matter, make it somewhat unique
var FOLLOW = true; // TRUE to enable mouse following, FALSE to have static tooltips
var DATA = "_tooltip"; // Does not matter, make it somewhat unique
var OFFSET_X = 20, OFFSET_Y = 10; // Tooltip's distance to the cursor

Style

You can now style your tooltips using the following CSS:

#tooltip {
    background: #fff;
    border: 1px solid red;
    padding: 3px 10px;
}

Replace the single quote (') character from a string

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'") or you can escape it inside single quotes ('\'').

To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:

>>> "didn't".replace("'", "")
'didnt'

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.

For RESTeasy, you should use CorsFilter. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.

See Also:

ANTLR: Is there a simple example?

Note: this answer is for ANTLR3! If you're looking for an ANTLR4 example, then this Q&A demonstrates how to create a simple expression parser, and evaluator using ANTLR4.


You first create a grammar. Below is a small grammar that you can use to evaluate expressions that are built using the 4 basic math operators: +, -, * and /. You can also group expressions using parenthesis.

Note that this grammar is just a very basic one: it does not handle unary operators (the minus in: -1+9) or decimals like .99 (without a leading number), to name just two shortcomings. This is just an example you can work on yourself.

Here's the contents of the grammar file Exp.g:

grammar Exp;

/* This will be the entry point of our parser. */
eval
    :    additionExp
    ;

/* Addition and subtraction have the lowest precedence. */
additionExp
    :    multiplyExp 
         ( '+' multiplyExp 
         | '-' multiplyExp
         )* 
    ;

/* Multiplication and division have a higher precedence. */
multiplyExp
    :    atomExp
         ( '*' atomExp 
         | '/' atomExp
         )* 
    ;

/* An expression atom is the smallest part of an expression: a number. Or 
   when we encounter parenthesis, we're making a recursive call back to the
   rule 'additionExp'. As you can see, an 'atomExp' has the highest precedence. */
atomExp
    :    Number
    |    '(' additionExp ')'
    ;

/* A number: can be an integer value, or a decimal value */
Number
    :    ('0'..'9')+ ('.' ('0'..'9')+)?
    ;

/* We're going to ignore all white space characters */
WS  
    :   (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
    ;

(Parser rules start with a lower case letter, and lexer rules start with a capital letter)

After creating the grammar, you'll want to generate a parser and lexer from it. Download the ANTLR jar and store it in the same directory as your grammar file.

Execute the following command on your shell/command prompt:

java -cp antlr-3.2.jar org.antlr.Tool Exp.g

It should not produce any error message, and the files ExpLexer.java, ExpParser.java and Exp.tokens should now be generated.

To see if it all works properly, create this test class:

import org.antlr.runtime.*;

public class ANTLRDemo {
    public static void main(String[] args) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream("12*(5-6)");
        ExpLexer lexer = new ExpLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        ExpParser parser = new ExpParser(tokens);
        parser.eval();
    }
}

and compile it:

// *nix/MacOS
javac -cp .:antlr-3.2.jar ANTLRDemo.java

// Windows
javac -cp .;antlr-3.2.jar ANTLRDemo.java

and then run it:

// *nix/MacOS
java -cp .:antlr-3.2.jar ANTLRDemo

// Windows
java -cp .;antlr-3.2.jar ANTLRDemo

If all goes well, nothing is being printed to the console. This means the parser did not find any error. When you change "12*(5-6)" into "12*(5-6" and then recompile and run it, there should be printed the following:

line 0:-1 mismatched input '<EOF>' expecting ')'

Okay, now we want to add a bit of Java code to the grammar so that the parser actually does something useful. Adding code can be done by placing { and } inside your grammar with some plain Java code inside it.

But first: all parser rules in the grammar file should return a primitive double value. You can do that by adding returns [double value] after each rule:

grammar Exp;

eval returns [double value]
    :    additionExp
    ;

additionExp returns [double value]
    :    multiplyExp 
         ( '+' multiplyExp 
         | '-' multiplyExp
         )* 
    ;

// ...

which needs little explanation: every rule is expected to return a double value. Now to "interact" with the return value double value (which is NOT inside a plain Java code block {...}) from inside a code block, you'll need to add a dollar sign in front of value:

grammar Exp;

/* This will be the entry point of our parser. */
eval returns [double value]                                                  
    :    additionExp { /* plain code block! */ System.out.println("value equals: "+$value); }
    ;

// ...

Here's the grammar but now with the Java code added:

grammar Exp;

eval returns [double value]
    :    exp=additionExp {$value = $exp.value;}
    ;

additionExp returns [double value]
    :    m1=multiplyExp       {$value =  $m1.value;} 
         ( '+' m2=multiplyExp {$value += $m2.value;} 
         | '-' m2=multiplyExp {$value -= $m2.value;}
         )* 
    ;

multiplyExp returns [double value]
    :    a1=atomExp       {$value =  $a1.value;}
         ( '*' a2=atomExp {$value *= $a2.value;} 
         | '/' a2=atomExp {$value /= $a2.value;}
         )* 
    ;

atomExp returns [double value]
    :    n=Number                {$value = Double.parseDouble($n.text);}
    |    '(' exp=additionExp ')' {$value = $exp.value;}
    ;

Number
    :    ('0'..'9')+ ('.' ('0'..'9')+)?
    ;

WS  
    :   (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
    ;

and since our eval rule now returns a double, change your ANTLRDemo.java into this:

import org.antlr.runtime.*;

public class ANTLRDemo {
    public static void main(String[] args) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream("12*(5-6)");
        ExpLexer lexer = new ExpLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        ExpParser parser = new ExpParser(tokens);
        System.out.println(parser.eval()); // print the value
    }
}

Again (re) generate a fresh lexer and parser from your grammar (1), compile all classes (2) and run ANTLRDemo (3):

// *nix/MacOS
java -cp antlr-3.2.jar org.antlr.Tool Exp.g   // 1
javac -cp .:antlr-3.2.jar ANTLRDemo.java      // 2
java -cp .:antlr-3.2.jar ANTLRDemo            // 3

// Windows
java -cp antlr-3.2.jar org.antlr.Tool Exp.g   // 1
javac -cp .;antlr-3.2.jar ANTLRDemo.java      // 2
java -cp .;antlr-3.2.jar ANTLRDemo            // 3

and you'll now see the outcome of the expression 12*(5-6) printed to your console!

Again: this is a very brief explanation. I encourage you to browse the ANTLR wiki and read some tutorials and/or play a bit with what I just posted.

Good luck!

EDIT:

This post shows how to extend the example above so that a Map<String, Double> can be provided that holds variables in the provided expression.

To get this code working with a current version of Antlr (June 2014) I needed to make a few changes. ANTLRStringStream needed to become ANTLRInputStream, the returned value needed to change from parser.eval() to parser.eval().value, and I needed to remove the WS clause at the end, because attribute values such as $channel are no longer allowed to appear in lexer actions.

Set Focus on EditText

Requesting focus isn't enough to show the keyboard.

To get focus and show the keyboard you would write something like this:

if(myEditText.requestFocus()) {
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}

EDIT: Adding extra info to the answer after the checkLiganame method was added.

In the checkLiganame method you check if the cursor is null. The cursor will always return an object, so the check for null doesn't do anything. However the problem is in the line db.close();

When you close the database connection, the Cursor becomes invalid and most probably is nulled.

So close the database after you've fetched the value.

Instead of checking the cursor for null, you should check if the number of rows returned are more than 0: if(cursor.getCount() > 0) and then set your boolean to true if so.

EDIT2: So here's some code for how to make it work. EDIT3: Sorry wrong code I added... ;S

First off, you need to clear focus if another EditText gets focus. This can be done with myEditText.clearFocus(). Then in your onFocusChangeListener you shouldn't really care if first EditText has focus or not, so the onFocusChangeListener could look something like this:

public class MainActivity extends Activity implements OnFocusChangeListener {
    private EditText editText1, editText2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText1 = (EditText) findViewById(R.id.editText1);
        editText1.setOnFocusChangeListener(this);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText2.setOnFocusChangeListener(this);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        String liganame = editText1.getText().toString();

        if(liganame.length() == 0) {
            if(editText1.requestFocus()) {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                editText2.clearFocus();
                Toast.makeText(MainActivity.this, "Dieser Liganame ist bereits vergeben", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Replace the first check if(liganame.length() == 0) with your own check, then it should work. Take note, that all the EditText views should have set their onFocusChangeListener to the same listener like I've done in the example.

Get selected item value from Bootstrap DropDown with specific ID

The selector would be #demolist.dropdown-menu li a note no space between id and class. However i would suggest a more generic approach:

<div class="input-group">                                            
    <input type="TextBox" Class="form-control datebox"></input>
    <div class="input-group-btn">
    <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
        <li><a href="#">C</a></li>
    </ul>
</div>


$(document).on('click', '.dropdown-menu li a', function() {
    $(this).parent().parent().parent().find('.datebox').val($(this).html());
}); 

by using a class rather than id, and using parent().find(), you can have as many of these on a page as you like, with no duplicated js

https connection using CURL from command line

You need to provide the entire certificate chain to curl, since curl no longer ships with any CA certs. Since the cacert option can only use one file, you need to concat the full chain info into 1 file

Copy the certificate chain (from your browser, for example) into DER encoded binary x.509(.cer). Do this for each cert.

Convert the certs into PEM, and concat them into 1 file.

openssl x509 -inform DES -in file1.cer -out file1.pem -text
openssl x509 -inform DES -in file2.cer -out file2.pem -text
openssl x509 -inform DES -in file3.cer -out file3.pem -text

cat *.pem > certRepo

curl --cacert certRepo -u user:passwd -X GET -H 'Content-Type: application/json' "https//somesecureserver.com/rest/field"

I wrote a blog on how to do this here: http://javamemento.blogspot.no/2015/10/using-curl-with-ssl-cert-chain.html

Autowiring two beans implementing same interface - how to set default bean to autowire?

The use of @Qualifier will solve the issue.
Explained as below example : 
public interface PersonType {} // MasterInterface

@Component(value="1.2") 
public class Person implements  PersonType { //Bean implementing the interface
@Qualifier("1.2")
    public void setPerson(PersonType person) {
        this.person = person;
    }
}

@Component(value="1.5")
public class NewPerson implements  PersonType { 
@Qualifier("1.5")
    public void setNewPerson(PersonType newPerson) {
        this.newPerson = newPerson;
    }
}

Now get the application context object in any component class :

Object obj= BeanFactoryAnnotationUtils.qualifiedBeanOfType((ctx).getAutowireCapableBeanFactory(), PersonType.class, type);//type is the qualifier id

you can the object of class of which qualifier id is passed.

How to split a string content into an array of strings in PowerShell?

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

Creating pdf files at runtime in c#

For this i looked into running LaTeX apps to generate a pdf. Although this option is likely to be far more complicated and heavy duty than the ones listed here.

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

You guys are going to laugh at this. I had an extra Listen 443 in ports.conf that shouldn't have been there. Removing that solved this.

How to increase font size in NeatBeans IDE?

For full control of ANY (non simplest editor, non head of tree) ui elements I recomend use plugin UI Editor for NetBeans

Settings in action

How to print colored text to the terminal?

I wrote a module that handles colors in Linux, OS X, and Windows. It supports all 16 colors on all platforms, you can set foreground and background colors at different times, and the string objects give sane results for things like len() and .capitalize().

https://github.com/Robpol86/colorclass

Example on Windows cmd.exe

Regular Expressions- Match Anything

Use .*, and make sure you are using your implementations' equivalent of single-line so you will match on line endings.

There is a great explanation here -> http://www.regular-expressions.info/dot.html

Images can't contain alpha channels or transparencies

Extending Roman B. answer. This is still a problem, I was uploading a cordova app. my solution using mogrify:

brew install imagemagick
* navigate to `platforms/ios/<your_app_name>/Images.xcassets/AppIcon.appiconset`*
mogrify -alpha off *.png

Then archived and validated successfully.

Difference between logical addresses, and physical addresses?

A logical address is a reference to memory location independent of the current assignment of data to memory. A physical address or absolute address is an actual location in main memory.

It is in chapter 7.2 of Stallings.

Android: How can I print a variable on eclipse console?

System.out.println and Log.d both go to LogCat, not the Console.

How to make a pure css based dropdown menu?

View code online on: WebCrafts.org

HTML code:

<body id="body">
<div id="navigation">
    <h2>
        Pure CSS Drop-down Menu
    </h2>
  <div id="nav" class="nav">
    <ul>
        <li><a href="#">Menu1</a></li>
        <li>
            <a href="#">Menu2</a>
          <ul>
                <li><a href="#">Sub-Menu1</a></li>
                <li>
                    <a href="#">Sub-Menu2</a>
                  <ul>
                        <li><a href="#">Demo1</a></li>
                      <li><a href="#">Demo2</a></li>
                    </ul>
                </li>
                <li><a href="#">Sub-Menu3</a></li>
                <li><a href="#">Sub-Menu4</a></li>
            </ul>
        </li>
        <li><a href="#">Menu3</a></li>
        <li><a href="#">Menu4</a></li>
    </ul>
  </div>
</div>
</body>

Css code:

body{
    background-color:#111;
}

#navigation{
    text-align:center;
}
#navigation h2{
    color:#DDD;
}

.nav{
    display:inline-block;
    z-index:5;
    font-weight:bold;
}
.nav ul{
    width:auto;
    list-style:none;
}

.nav ul li{
    display:inline-block;
}

.nav ul li a{
    text-decoration:none;
    text-align:center;
    color:#222;
    display:block;
    width:120px;
    line-height:30px;
    background-color:gray;
}

.nav ul li a:hover{
    background-color:#EEC;   
}
.nav ul li ul{
    margin-top:0px;
    padding-left:0px;
    position:absolute;
    display:none;
}

.nav ul li:hover ul{
    display:block;
}

.nav ul li ul li{
    display:block;
}

.nav ul li ul li ul{
    margin-left:100%;
    margin-top:-30px;
    visibility:hidden;
}

.nav ul li ul li:hover ul{
    margin-left:100%;
    visibility:visible;
}

How do I delete an item or object from an array using ng-click?

Pass the id that you want to remove from the array to the given function 

from the controller( Function can be in the same controller but prefer to keep it in a service)

    function removeInfo(id) {
    let item = bdays.filter(function(item) {
      return bdays.id=== id;
    })[0];
    let index = bdays.indexOf(item);
    data.device.splice(indexOfTabDetails, 1);
  }

Hibernate Error executing DDL via JDBC Statement

I have got this error when trying to create JPA entity with the name "User" (in Postgres) that is reserved. So the way it is resolved is to change the table name by @Table annotation:

@Entity
@Table(name="users")
public class User {..}

Or change the table name manually.

How can you find the height of text on an HTML canvas?

The canvas spec doesn't give us a method for measuring the height of a string. However, you can set the size of your text in pixels and you can usually figure out what the vertical bounds are relatively easily.

If you need something more precise then you could throw text onto the canvas and then get pixel data and figure out how many pixels are used vertically. This would be relatively simple, but not very efficient. You could do something like this (it works, but draws some text onto your canvas that you would want to remove):

function measureTextHeight(ctx, left, top, width, height) {

    // Draw the text in the specified area
    ctx.save();
    ctx.translate(left, top + Math.round(height * 0.8));
    ctx.mozDrawText('gM'); // This seems like tall text...  Doesn't it?
    ctx.restore();

    // Get the pixel data from the canvas
    var data = ctx.getImageData(left, top, width, height).data,
        first = false, 
        last = false,
        r = height,
        c = 0;

    // Find the last line with a non-white pixel
    while(!last && r) {
        r--;
        for(c = 0; c < width; c++) {
            if(data[r * width * 4 + c * 4 + 3]) {
                last = r;
                break;
            }
        }
    }

    // Find the first line with a non-white pixel
    while(r) {
        r--;
        for(c = 0; c < width; c++) {
            if(data[r * width * 4 + c * 4 + 3]) {
                first = r;
                break;
            }
        }

        // If we've got it then return the height
        if(first != r) return last - first;
    }

    // We screwed something up...  What do you expect from free code?
    return 0;
}

// Set the font
context.mozTextStyle = '32px Arial';

// Specify a context and a rect that is safe to draw in when calling measureTextHeight
var height = measureTextHeight(context, 0, 0, 50, 50);
console.log(height);

For Bespin they do fake a height by measuring the width of a lowercase 'm'... I don't know how this is used, and I would not recommend this method. Here is the relevant Bespin method:

var fixCanvas = function(ctx) {
    // upgrade Firefox 3.0.x text rendering to HTML 5 standard
    if (!ctx.fillText && ctx.mozDrawText) {
        ctx.fillText = function(textToDraw, x, y, maxWidth) {
            ctx.translate(x, y);
            ctx.mozTextStyle = ctx.font;
            ctx.mozDrawText(textToDraw);
            ctx.translate(-x, -y);
        }
    }

    if (!ctx.measureText && ctx.mozMeasureText) {
        ctx.measureText = function(text) {
            ctx.mozTextStyle = ctx.font;
            var width = ctx.mozMeasureText(text);
            return { width: width };
        }
    }

    if (ctx.measureText && !ctx.html5MeasureText) {
        ctx.html5MeasureText = ctx.measureText;
        ctx.measureText = function(text) {
            var textMetrics = ctx.html5MeasureText(text);

            // fake it 'til you make it
            textMetrics.ascent = ctx.html5MeasureText("m").width;

            return textMetrics;
        }
    }

    // for other browsers
    if (!ctx.fillText) {
        ctx.fillText = function() {}
    }

    if (!ctx.measureText) {
        ctx.measureText = function() { return 10; }
    }
};

MySQL SELECT WHERE datetime matches day (and not necessarily time)

... WHERE date_column >='2012-12-25' AND date_column <'2012-12-26' may potentially work better(if you have an index on date_column) than DATE.

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

For this case, where you want to get a Control of a Form and are receiving this error, then I have a little bypass for you.

Go to your Program.cs and change

Application.Run(new Form1());

to

public static Form1 form1 = new Form1(); // Place this var out of the constructor
Application.Run(form1);

Now you can access a control with

Program.form1.<Your control>

Also: Don't forget to set your Control-Access-Level to Public.

And yes I know, this answer does not fit to the question caller, but it fits to googlers who have this specific issue with controls.

Jenkins: Failed to connect to repository

I faced a similar issue when I tried to connect jenkins in my Windows server with my private GIT repo. Following is the error returned in the source code management section of Jenkins job

Failed to connect to repository : Command "git.exe ls-remote -h ssh://git@my_server/repo.git HEAD" returned status code 128: stdout: stderr: Load key "C:\Windows\TEMP\ssh4813927591749610777.key": invalid format git@my_server: Permission denied (publickey). fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

This error is thrown because jenkins is not able to pick the private ssh key from its user directory. I solved this in the following manner

Step 1

In the jenkins job, fill up the following info under Source Code Management

Repositories

Repository URL: ssh://git@my_server/repo.git
Credentials: -none-

Step 2

In my setup jenkins is running under local system account, so the user directory is C:\Windows\System32\config\systemprofile (This is the important thing in this setup that is not very obvious).

Now create ssh private and public keys using ssh-keygen -t rsa -C "key label" via git bash shell. The ssh private and public keys go under .ssh directory of your logged in user directory. Just copy the .ssh folder and paste it under C:\Windows\System32\config\systemprofile

Step 3

Add your public key to your GIT server account. Run the jenkins job and now you should be able to connect to the GIT account via ssh from jenkins.

Change windows hostname from command line

Use below command to change computer hostname remotely , Require system reboot after change..

psexec.exe -h -e \\\IPADDRESS -u USERNAME -p PASSWORD netdom renamecomputer CurrentComputerName /newname:NewComputerName /force

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

How to insert a row in an HTML table body in JavaScript

Add Column, Add Row, Delete Column, Delete Row. Simplest way

_x000D_
_x000D_
    function addColumn(myTable) {
      var table = document.getElementById(myTable);
      var row = table.getElementsByTagName('tr');
      for(i=0;i<row.length;i++){
        row[i].innerHTML = row[i].innerHTML + '<td></td>';
      }
    }
    function deleterow(tblId)
    {
        
      var table = document.getElementById(tblId);
      var row = table.getElementsByTagName('tr');
            if(row.length!='1'){
                row[row.length - 1].outerHTML='';
            }
    }
    function deleteColumn(tblId)
    {
        var allRows = document.getElementById(tblId).rows;
        for (var i=0; i<allRows.length; i++) {
            if (allRows[i].cells.length > 1) {
                allRows[i].deleteCell(-1);
            }
        }
    }
    function myFunction(myTable) {
      var table = document.getElementById(myTable);
      var row = table.getElementsByTagName('tr');
      var row = row[row.length-1].outerHTML;
      table.innerHTML = table.innerHTML + row;
      var row = table.getElementsByTagName('tr');
      var row = row[row.length-1].getElementsByTagName('td');
      for(i=0;i<row.length;i++){
        row[i].innerHTML = '';
      }
    }
_x000D_
    table, td {
      border: 1px solid black;
      border-collapse:collapse;
    }
    td {
      cursor:text;
      padding:10px;
    }
    td:empty:after{
      content:"Type here...";
      color:#cccccc;
    }
_x000D_
   <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <form>
    <p>
    <input type="button" value="+Column" onclick="addColumn('tblSample')">
    <input type="button" value="-Column" onclick="deleteColumn('tblSample')">
    <input type="button" value="+Row" onclick="myFunction('tblSample')">
    <input type="button" value="-Row" onclick="deleterow('tblSample')">
    </p>
    <table id="tblSample" contenteditable><tr><td></td></tr></table>
    </form>

    </body>
    </html>
_x000D_
_x000D_
_x000D_

Difference between clustered and nonclustered index

You really need to keep two issues apart:

1) the primary key is a logical construct - one of the candidate keys that uniquely and reliably identifies every row in your table. This can be anything, really - an INT, a GUID, a string - pick what makes most sense for your scenario.

2) the clustering key (the column or columns that define the "clustered index" on the table) - this is a physical storage-related thing, and here, a small, stable, ever-increasing data type is your best pick - INT or BIGINT as your default option.

By default, the primary key on a SQL Server table is also used as the clustering key - but that doesn't need to be that way!

One rule of thumb I would apply is this: any "regular" table (one that you use to store data in, that is a lookup table etc.) should have a clustering key. There's really no point not to have a clustering key. Actually, contrary to common believe, having a clustering key actually speeds up all the common operations - even inserts and deletes (since the table organization is different and usually better than with a heap - a table without a clustering key).

Kimberly Tripp, the Queen of Indexing has a great many excellent articles on the topic of why to have a clustering key, and what kind of columns to best use as your clustering key. Since you only get one per table, it's of utmost importance to pick the right clustering key - and not just any clustering key.

Marc

How to prevent Right Click option using jquery

$(document).mousedown(function(e) {
    if( e.button == 2 ) {
         e.preventDefault();
        return false;
    } 
});

How to fix HTTP 404 on Github Pages?

I had same issue.. Very strange issue.. My HTML was with space after title

> <title>
> 
> <script>

Fixed, after removing space

> <title>
> <script>

How to deal with page breaks when printing a large HTML table

Expanding from Sinan Ünür solution:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
<style type="text/css">
    table { page-break-inside:auto }
    div   { page-break-inside:avoid; } /* This is the key */
    thead { display:table-header-group }
    tfoot { display:table-footer-group }
</style>
</head>
<body>
    <table>
        <thead>
            <tr><th>heading</th></tr>
        </thead>
        <tfoot>
            <tr><td>notes</td></tr>
        </tfoot>
        <tr>
            <td><div>Long<br />cell<br />should'nt<br />be<br />cut</div></td>
        </tr>
        <tr>
            <td><div>Long<br />cell<br />should'nt<br />be<br />cut</div></td>
        </tr>
        <!-- 500 more rows -->
        <tr>
            <td>x</td>
        </tr>
    </tbody>
    </table>
</body>
</html>

It seems that page-break-inside:avoid in some browsers is only taken in consideration for block elements, not for cell, table, row neither inline-block.

If you try to display:block the TR tag, and use there page-break-inside:avoid, it works, but messes around with your table layout.

What is the difference between compare() and compareTo()?

The methods do not have to give the same answers. That depends on which objects/classes you call them.

If you are implementing your own classes which you know you want to compare at some stage, you may have them implement the Comparable interface and implement the compareTo() method accordingly.

If you are using some classes from an API which do not implement the Comparable interface, but you still want to compare them. I.e. for sorting. You may create your own class which implements the Comparator interface and in its compare() method you implement the logic.

How do I convert a Python program to a runnable .exe Windows program?

I use cx_Freeze. Works with Python 2 and 3, and I have tested it to work on Windows, Mac, and Linux.

cx_Freeze: http://cx-freeze.sourceforge.net/

Generate full SQL script from EF 5 Code First Migrations

To add to Matt wilson's answer I had a bunch of code-first entity classes but no database as I hadn't taken a backup. So I did the following on my Entity Framework project:

Open Package Manager console in Visual Studio and type the following:

Enable-Migrations

Add-Migration

Give your migration a name such as 'Initial' and then create the migration. Finally type the following:

Update-Database

Update-Database -Script -SourceMigration:0

The final command will create your database tables from your entity classes (provided your entity classes are well formed).

Maven project.build.directory

It points to your top level output directory (which by default is target):

https://web.archive.org/web/20150527103929/http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide

EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:

http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-properties.html#resource-filtering-sect-project-properties

If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.

    project.build.sourceDirectory
    project.build.scriptSourceDirectory
    project.build.testSourceDirectory
    project.build.outputDirectory
    project.build.testOutputDirectory
    project.build.directory

sourceDirectory, scriptSourceDirectory, and testSourceDirectory provide access to the source directories for the project. outputDirectory and testOutputDirectory provide access to the directories where Maven is going to put bytecode or other build output. directory refers to the directory which contains all of these output directories.

Moving x-axis to the top of a plot in matplotlib

You want set_ticks_position rather than set_label_position:

ax.xaxis.set_ticks_position('top') # the rest is the same

This gives me:

enter image description here

Count lines in large files

Hadoop is essentially providing a mechanism to perform something similar to what @Ivella is suggesting.

Hadoop's HDFS (Distributed file system) is going to take your 20GB file and save it across the cluster in blocks of a fixed size. Lets say you configure the block size to be 128MB, the file would be split into 20x8x128MB blocks.

You would then run a map reduce program over this data, essentially counting the lines for each block (in the map stage) and then reducing these block line counts into a final line count for the entire file.

As for performance, in general the bigger your cluster, the better the performance (more wc's running in parallel, over more independent disks), but there is some overhead in job orchestration that means that running the job on smaller files will not actually yield quicker throughput than running a local wc

Extracting text from HTML file using Python

Another example using BeautifulSoup4 in Python 2.7.9+

includes:

import urllib2
from bs4 import BeautifulSoup

Code:

def read_website_to_text(url):
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page, 'html.parser')
    for script in soup(["script", "style"]):
        script.extract() 
    text = soup.get_text()
    lines = (line.strip() for line in text.splitlines())
    chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
    text = '\n'.join(chunk for chunk in chunks if chunk)
    return str(text.encode('utf-8'))

Explained:

Read in the url data as html (using BeautifulSoup), remove all script and style elements, and also get just the text using .get_text(). Break into lines and remove leading and trailing space on each, then break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")). Then using text = '\n'.join, drop blank lines, finally return as sanctioned utf-8.

Notes:

Django ManyToMany filter()

Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct(). Otherwise you get one user multiple times:

users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()

What does T&& (double ampersand) mean in C++11?

It denotes an rvalue reference. Rvalue references will only bind to temporary objects, unless explicitly generated otherwise. They are used to make objects much more efficient under certain circumstances, and to provide a facility known as perfect forwarding, which greatly simplifies template code.

In C++03, you can't distinguish between a copy of a non-mutable lvalue and an rvalue.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(const std::string&);

In C++0x, this is not the case.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(std::string&&);

Consider the implementation behind these constructors. In the first case, the string has to perform a copy to retain value semantics, which involves a new heap allocation. However, in the second case, we know in advance that the object which was passed in to our constructor is immediately due for destruction, and it doesn't have to remain untouched. We can effectively just swap the internal pointers and not perform any copying at all in this scenario, which is substantially more efficient. Move semantics benefit any class which has expensive or prohibited copying of internally referenced resources. Consider the case of std::unique_ptr- now that our class can distinguish between temporaries and non-temporaries, we can make the move semantics work correctly so that the unique_ptr cannot be copied but can be moved, which means that std::unique_ptr can be legally stored in Standard containers, sorted, etc, whereas C++03's std::auto_ptr cannot.

Now we consider the other use of rvalue references- perfect forwarding. Consider the question of binding a reference to a reference.

std::string s;
std::string& ref = s;
(std::string&)& anotherref = ref; // usually expressed via template

Can't recall what C++03 says about this, but in C++0x, the resultant type when dealing with rvalue references is critical. An rvalue reference to a type T, where T is a reference type, becomes a reference of type T.

(std::string&)&& ref // ref is std::string&
(const std::string&)&& ref // ref is const std::string&
(std::string&&)&& ref // ref is std::string&&
(const std::string&&)&& ref // ref is const std::string&&

Consider the simplest template function- min and max. In C++03 you have to overload for all four combinations of const and non-const manually. In C++0x it's just one overload. Combined with variadic templates, this enables perfect forwarding.

template<typename A, typename B> auto min(A&& aref, B&& bref) {
    // for example, if you pass a const std::string& as first argument,
    // then A becomes const std::string& and by extension, aref becomes
    // const std::string&, completely maintaining it's type information.
    if (std::forward<A>(aref) < std::forward<B>(bref))
        return std::forward<A>(aref);
    else
        return std::forward<B>(bref);
}

I left off the return type deduction, because I can't recall how it's done offhand, but that min can accept any combination of lvalues, rvalues, const lvalues.

How can I find whitespace in a String?

package com.test;

public class Test {

    public static void main(String[] args) {

        String str = "TestCode ";
        if (str.indexOf(" ") > -1) {
            System.out.println("Yes");
        } else {
            System.out.println("Noo");
        }
    }
}

Python pandas insert list into a cell

I've got a solution that's pretty simple to implement.

Make a temporary class just to wrap the list object and later call the value from the class.

Here's a practical example:

  1. Let's say you want to insert list object into the dataframe.
df = pd.DataFrame([
    {'a': 1},
    {'a': 2},
    {'a': 3},
])

df.loc[:, 'b'] = [
    [1,2,4,2,], 
    [1,2,], 
    [4,5,6]
] # This works. Because the list has the same length as the rows of the dataframe

df.loc[:, 'c'] = [1,2,4,5,3] # This does not work. 

>>> ValueError: Must have equal len keys and value when setting with an iterable

## To force pandas to have list as value in each cell, wrap the list with a temporary class.

class Fake(object):
    def __init__(self, li_obj):
        self.obj = li_obj

df.loc[:, 'c'] = Fake([1,2,5,3,5,7,]) # This works. 

df.c = df.c.apply(lambda x: x.obj) # Now extract the value from the class. This works. 

Creating a fake class to do this might look like a hassle but it can have some practical applications. For an example you can use this with apply when the return value is list.

Pandas would normally refuse to insert list into a cell but if you use this method, you can force the insert.

How to use NSJSONSerialization

Your root json object is not a dictionary but an array:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

This might give you a clear picture of how to handle it:

NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

if (!jsonArray) {
  NSLog(@"Error parsing JSON: %@", e);
} else {
   for(NSDictionary *item in jsonArray) {
      NSLog(@"Item: %@", item);
   }
}

ValueError: math domain error

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.

How to tell if a string is not defined in a Bash shell script

~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO=""
~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO="a"
~> if [ -z $FOO ]; then echo "EMPTY"; fi
~> 

-z works for undefined variables too. To distinguish between an undefined and a defined you'd use the things listed here or, with clearer explanations, here.

Cleanest way is using expansion like in these examples. To get all your options check the Parameter Expansion section of the manual.

Alternate word:

~$ unset FOO
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
~$ FOO=""
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
DEFINED

Default value:

~$ FOO=""
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
~$ unset FOO
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
UNDEFINED

Of course you'd use one of these differently, putting the value you want instead of 'default value' and using the expansion directly, if appropriate.

Upload artifacts to Nexus, without Maven

No need to use these commands .. you can directly use the nexus web Interface in order to upload your JAR using GAV parameters.

enter image description here

So it is very simple.

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

An expansion for those who did a bit of fiddling around like I did.

The following work (from W3):

<input type="text" autofocus />
<input type="text" autofocus="" />
<input type="text" autofocus="autofocus" />
<input type="text" autofocus="AuToFoCuS" />

It is important to note that this does not work in CSS though. I.e. you can't use:

.first-input {
    autofocus:"autofocus"
}

At least it didn't work for me...

where to place CASE WHEN column IS NULL in this query

Not able to understand your actual problem but your case statement is incorrect

CASE 
WHEN 
TABLE3.COL3 IS NULL
THEN TABLE2.COL3
ELSE
TABLE3.COL3
END 
AS
COL4

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

So, finally I realized what the problem is. It is not a Jackson configuration issue as I doubted.

Actually the problem was in ApplesDO Class:

public class ApplesDO {

    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String apple) {
        this.apple = apple;
    }

    public ApplesDO(CustomType custom) {
        //constructor Code
    }
}

There was a custom constructor defined for the class making it the default constructor. Introducing a dummy constructor has made the error to go away:

public class ApplesDO {

    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String apple) {
        this.apple = apple;
    }

    public ApplesDO(CustomType custom) {
        //constructor Code
    }

    //Introducing the dummy constructor
    public ApplesDO() {
    }

}

powershell - extract file name and extension

If is from a text file and and presuming name file are surrounded by white spaces this is a way:

$a = get-content c:\myfile.txt

$b = $a | select-string -pattern "\s.+\..{3,4}\s" | select -ExpandProperty matches | select -ExpandProperty value

$b | % {"File name:{0} - Extension:{1}" -f $_.substring(0, $_.lastindexof('.')) , $_.substring($_.lastindexof('.'), ($_.length - $_.lastindexof('.'))) }

If is a file you can use something like this based on your needs:

$a = dir .\my.file.xlsx # or $a = get-item c:\my.file.xlsx 

$a
    Directory: Microsoft.PowerShell.Core\FileSystem::C:\ps


Mode           LastWriteTime       Length Name
----           -------------       ------ ----
-a---      25/01/10    11.51          624 my.file.xlsx


$a.BaseName
my.file
$a.Extension
.xlsx

Convert HTML Character Back to Text Using Java Standard Library

Here you have to just add jar file in lib jsoup in your application and then use this code.

import org.jsoup.Jsoup;

public class Encoder {
    public static void main(String args[]) {
        String s = Jsoup.parse("&lt;Fran&ccedil;ais&gt;").text();
        System.out.print(s);
    }
}

Link to download jsoup: http://jsoup.org/download

Can't choose class as main class in IntelliJ

Here is the complete procedure for IDEA IntelliJ 2019.3:

  1. File > Project Structure

  2. Under Project Settings > Modules

  3. Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.

  4. Apply changes.

Django - Static file not found

Another error can be not having your app listed in the INSTALLED_APPS listing like:

INSTALLED_APPS = [
    # ...
    'your_app',
]

Without having it in, you can face problems like not detecting your static files, basically all the files involving your app. Even though it can be correct as suggested in the correct answer by using:

STATICFILES_DIRS = (adding/path/of/your/app)

Can be one of the errors and should be reviewed if getting this error.

How do I iterate and modify Java Sets?

You could create a mutable wrapper of the primitive int and create a Set of those:

class MutableInteger
{
    private int value;
    public int getValue()
    {
        return value;
    }
    public void setValue(int value)
    {
        this.value = value;
    }
}

class Test
{
    public static void main(String[] args)
    {
        Set<MutableInteger> mySet = new HashSet<MutableInteger>();
        // populate the set
        // ....

        for (MutableInteger integer: mySet)
        {
            integer.setValue(integer.getValue() + 1);
        }
    }
}

Of course if you are using a HashSet you should implement the hash, equals method in your MutableInteger but that's outside the scope of this answer.

How to stop asynctask thread in android?

u can check onCancelled() once then :

protected Object doInBackground(Object... x) {

while (/* condition */) {
  if (isCancelled()) break;
}
return null;

}

Transport security has blocked a cleartext HTTP

Transport security is available on iOS 9.0 or later. You may have this warning when trying to call a WS inside your application:

Application Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

Adding the following to your Info.plist will disable ATS:

<key>NSAppTransportSecurity</key>
<dict>
     <key>NSAllowsArbitraryLoads</key><true/>
</dict>

What is Haskell used for in the real world?

What are some common uses for this language?

Rapid application development.

If you want to know "why Haskell?", then you need to consider advantages of functional programming languages (taken from https://c2.com/cgi/wiki?AdvantagesOfFunctionalProgramming):

  • Functional programs tend to be much more terse than their ImperativeLanguage counterparts. Often this leads to enhanced programmer productivity

  • FP encourages quick prototyping. As such, I think it is the best software design paradigm for ExtremeProgrammers... but what do I know?

  • FP is modular in the dimension of functionality, where ObjectOrientedProgramming is modular in the dimension of different components.

  • The ability to have your cake and eat it. Imagine you have a complex OO system processing messages - every component might make state changes depending on the message and then forward the message to some objects it has links to. Wouldn't it be just too cool to be able to easily roll back every change if some object deep in the call hierarchy decided the message is flawed? How about having a history of different states?

  • Many housekeeping tasks made for you: deconstructing data structures (PatternMatching), storing variable bindings (LexicalScope with closures), strong typing (TypeInference), GarbageCollection, storage allocation, whether to use boxed (pointer-to-value) or unboxed (value directly) representation...

  • Safe multithreading! Immutable data structures are not subject to data race conditions, and consequently don't have to be protected by locks. If you are always allocating new objects, rather than destructively manipulating existing ones, the locking can be hidden in the allocation and GarbageCollection system.

Apart from this Haskell has its own advantages such as:

  • Clear, intuitive syntax inspired by mathematical notation.
  • List comprehensions to create a list based on existing lists.
  • Lambda expressions: create functions without giving them explicit names. So it's easier to handle big formulas.
  • Haskell is completely referentially transparent. Any code that uses I/O must be marked as such. This way, it encourages you to separate code with side effects (e.g. putting text on the screen) from code without (calculations).
  • Lazy evaluation is a really nice feature:
    • Even if something would usually cause an error, it will still work as long as you don't use the result. For example, you could put 1 / 0 as the first item of a list and it will still work if you only used the second item.
    • It is easier to write search programs such as this sudoku solver because it doesn't load every combination at once—it just generates them as it goes along. You can do this in other languages, but only Haskell does this by default.

You can check out following links:

OpenCV - Saving images to a particular folder of choice

FOR MAC USERS if you are working with open cv

import cv2

cv2.imwrite('path_to_folder/image.jpg',image)

How to configure a HTTP proxy for svn

There are two common approaches for this:

If you are on Windows, you can also write http-proxy- options to Windows Registry. It's pretty handy if you need to apply proxy settings in Active Directory environment via Group Policy Objects.

Switching to landscape mode in Android Emulator

Ctrl + F11 works wonderfully on Ubuntu / Linux Mint.

Python: How to increase/reduce the fontsize of x and y tick labels?

You can set the fontsize directly in the call to set_xticklabels and set_yticklabels (as noted in previous answers). This will only affect one Axes at a time.

ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)

You can also set the ticklabel font size globally (i.e. for all figures/subplots in a script) using rcParams:

import matplotlib.pyplot as plt

plt.rc('xtick',labelsize=8)
plt.rc('ytick',labelsize=8)

Or, equivalently:

plt.rcParams['xtick.labelsize']=8
plt.rcParams['ytick.labelsize']=8

Finally, if this is a setting that you would like to be set for all your matplotlib plots, you could also set these two rcParams in your matplotlibrc file:

xtick.labelsize      : 8 # fontsize of the x tick labels
ytick.labelsize      : 8 # fontsize of the y tick labels

Change old commit message on Git

Just wanted to provide a different option for this. In my case, I usually work on my individual branches then merge to master, and the individual commits I do to my local are not that important.

Due to a git hook that checks for the appropriate ticket number on Jira but was case sensitive, I was prevented from pushing my code. Also, the commit was done long ago and I didn't want to count how many commits to go back on the rebase.

So what I did was to create a new branch from latest master and squash all commits from problem branch into a single commit on new branch. It was easier for me and I think it's good idea to have it here as future reference.

From latest master:

git checkout -b new-branch

Then

git merge --squash problem-branch
git commit -m "new message" 

Referece: https://github.com/rotati/wiki/wiki/Git:-Combine-all-messy-commits-into-one-commit-before-merging-to-Master-branch

How can I determine if a variable is 'undefined' or 'null'?

Since you are using jQuery, you can determine whether a variable is undefined or its value is null by using a single function.

var s; // undefined
jQuery.isEmptyObject(s); // will return true;

s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;

// usage
if(jQuery.isEmptyObject(s)){
    alert('Either variable: s is undefined or its value is null');
}else{
     alert('variable: s has value ' + s);
}

s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;

List an Array of Strings in alphabetical order

Here is code that works:

import java.util.Arrays;
import java.util.Collections;

public class Test
{
    public static void main(String[] args)
    {
        orderedGuests1(new String[] { "c", "a", "b" });
        orderedGuests2(new String[] { "c", "a", "b" });
    }

    public static void orderedGuests1(String[] hotel)
    {
        Arrays.sort(hotel);
        System.out.println(Arrays.toString(hotel));
    }

    public static void orderedGuests2(String[] hotel)
    {
        Collections.sort(Arrays.asList(hotel));
        System.out.println(Arrays.toString(hotel));
    }

}

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

R legend placement in a plot

You have to add the size of the legend box to the ylim range

#Plot an empty graph and legend to get the size of the legend
x <-1:10
y <-11:20
plot(x,y,type="n", xaxt="n", yaxt="n")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"),plot = FALSE)

#custom ylim. Add the height of legend to upper bound of the range
my.range <- range(y)
my.range[2] <- 1.04*(my.range[2]+my.legend.size$rect$h)

#draw the plot with custom ylim
plot(x,y,ylim=my.range, type="l")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"))

enter image description here

Add a new line to a text file in MS-DOS

echo Hello, > file.txt
echo.       >>file.txt
echo world  >>file.txt

and you can always run:

wordpad file.txt

on any version of Windows.


On Windows 2000 and above you can do:

( echo Hello, & echo. & echo world ) > file.txt

Another way of showing a message for a small amount of text is to create file.vbs containing:

Msgbox "Hello," & vbCrLf & vbCrLf & "world", 0, "Message"

Call it with

cscript /nologo file.vbs

Or use wscript if you don't need it to wait until they click OK.


The problem with the message you're writing is that the vertical bar (|) is the "pipe" operator. You'll need to escape it by using ^| instead of |.

P.S. it's spelled Pwned.

Adding calculated column(s) to a dataframe in pandas

The first four functions you list will work on vectors as well, with the exception that lower_wick needs to be adapted. Something like this,

def lower_wick_vec(o, l, c):
    min_oc = numpy.where(o > c, c, o)
    return min_oc - l

where o, l and c are vectors. You could do it this way instead which just takes the df as input and avoid using numpy, although it will be much slower:

def lower_wick_df(df):
    min_oc = df[['Open', 'Close']].min(axis=1)
    return min_oc - l

The other three will work on columns or vectors just as they are. Then you can finish off with

def is_hammer(df):
    lw = lower_wick_at_least_twice_real_body(df["Open"], df["Low"], df["Close"]) 
    cl = closed_in_top_half_of_range(df["High"], df["Low"], df["Close"])
    return cl & lw

Bit operators can perform set logic on boolean vectors, & for and, | for or etc. This is enough to completely vectorize the sample calculations you gave and should be relatively fast. You could probably speed up even more by temporarily working with the numpy arrays underlying the data while performing these calculations.

For the second part, I would recommend introducing a column indicating the pattern for each row and writing a family of functions which deal with each pattern. Then groupby the pattern and apply the appropriate function to each group.

Sql select rows containing part of string

You can use the LIKE operator to compare the content of a T-SQL string, e.g.

SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'.

The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".

How do I use Ruby for shell scripting?

There's a lot of good advice here, so I wanted to add a tiny bit more.

  1. Backticks (or back-ticks) let you do some scripting stuff a lot easier. Consider

    puts `find . | grep -i lib`
    
  2. If you run into problems with getting the output of backticks, the stuff is going to standard err instead of standard out. Use this advice

    out = `git status 2>&1`
    
  3. Backticks do string interpolation:

    blah = 'lib'
    `touch #{blah}`
    
  4. You can pipe inside Ruby, too. It's a link to my blog, but it links back here so it's okay :) There are probably more advanced things out there on this topic.

  5. As other people noted, if you want to get serious there is Rush: not just as a shell replacement (which is a bit too zany for me) but also as a library for your use in shell scripts and programs.


On Mac, Use Applescript inside Ruby for more power. Here's my shell_here script:

#!/usr/bin/env ruby
`env | pbcopy` 
cmd =  %Q@tell app "Terminal" to do script "$(paste_env)"@
puts cmd

`osascript -e "${cmd}"`

Why does npm install say I have unmet dependencies?

Take care about your angular version, if you work under angular 2.x.x so maybe you need to upgrade to angular 4.x.x

Some dependencies needs angular 4

Here is a tutorial for how to install angular 4 or update your project.

How can I use async/await at the top level?

i like this clever syntax to do async work from an entrypoint

void async function main() {
  await doSomeWork()
  await doMoreWork()
}()

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

Add Microsot.ReportViewer 2010 or 2012 in prerequisite of setup project then it first install Report Viewer if it's not present in "C:\Windows\assembly\GAC_MSIL..." and after installing, it installs set up project

How to change Toolbar home icon color

Change your Toolbar Theme to ThemeOverlay.AppCompat.Dark

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:orientation="vertical"
    app:theme="@style/ThemeOverlay.AppCompat.Dark">

</android.support.v7.widget.Toolbar>

and set it in activty

mToolbar = (Toolbar) findViewById(R.id.navigation);
setSupportActionBar(mToolbar);

ASP.NET MVC3 - textarea with @Html.EditorFor

Someone asked about adding attributes (specifically, 'rows' and 'cols'). If you're using Razor, you could just do this:

@Html.TextAreaFor(model => model.Text, new { cols = 35, @rows = 3 })

That works for me. The '@' is used to escape keywords so they are treated as variables/properties.

How to download a file via FTP with Python ftplib

Please note if you are downloading from the FTP to your local, you will need to use the following:

with open( filename, 'wb' ) as file :
        ftp.retrbinary('RETR %s' % filename, file.write)

Otherwise, the script will at your local file storage rather than the FTP.

I spent a few hours making the mistake myself.

Script below:

import ftplib

# Open the FTP connection
ftp = ftplib.FTP()
ftp.cwd('/where/files-are/located')


filenames = ftp.nlst()

for filename in filenames:

    with open( filename, 'wb' ) as file :
        ftp.retrbinary('RETR %s' % filename, file.write)

        file.close()

ftp.quit()

Detecting user leaving page with react-router

react-router v4 introduces a new way to block navigation using Prompt. Just add this to the component that you would like to block:

import { Prompt } from 'react-router'

const MyComponent = () => (
  <React.Fragment>
    <Prompt
      when={shouldBlockNavigation}
      message='You have unsaved changes, are you sure you want to leave?'
    />
    {/* Component JSX */}
  </React.Fragment>
)

This will block any routing, but not page refresh or closing. To block that, you'll need to add this (updating as needed with the appropriate React lifecycle):

componentDidUpdate = () => {
  if (shouldBlockNavigation) {
    window.onbeforeunload = () => true
  } else {
    window.onbeforeunload = undefined
  }
}

onbeforeunload has various support by browsers.