Programs & Examples On #Citrix

Citrix is name of a company which stands for many applications round about IT virtualization, especially for Microsoft products. Well known is Citrix XenApp.

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

How to construct a WebSocket URI relative to the page URI?

In typescript:

export class WebsocketUtils {

    public static websocketUrlByPath(path) {
        return this.websocketProtocolByLocation() +
            window.location.hostname +
            this.websocketPortWithColonByLocation() +
            window.location.pathname +
            path;
    }

    private static websocketProtocolByLocation() {
        return window.location.protocol === "https:" ? "wss://" : "ws://";
    }

    private static websocketPortWithColonByLocation() {
        const defaultPort = window.location.protocol === "https:" ? "443" : "80";
        if (window.location.port !== defaultPort) {
            return ":" + window.location.port;
        } else {
            return "";
        }
    }
}

Usage:

alert(WebsocketUtils.websocketUrlByPath("/websocket"));

How to split a long array into smaller arrays, with JavaScript

You can take a look at this code . Simple and Effective .

function chunkArrayInGroups(array, unit) {
var results = [],
length = Math.ceil(array.length / unit);

for (var i = 0; i < length; i++) {
    results.push(array.slice(i * unit, (i + 1) * unit));
}
 return results;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

How to return multiple values in one column (T-SQL)?

Sorry, read the question wrong the first time. You can do something like this:

declare @result varchar(max)

--must "initialize" result for this to work
select @result = ''

select @result = @result + alias
FROM aliases
WHERE username='Bob'

Change the jquery show()/hide() animation?

There are the slideDown, slideUp, and slideToggle functions native to jquery 1.3+, and they work quite nicely...

https://api.jquery.com/category/effects/

You can use slideDown just like this:

$("test").slideDown("slow");

And if you want to combine effects and really go nuts I'd take a look at the animate function which allows you to specify a number of CSS properties to shape tween or morph into. Pretty fancy stuff, that.

Learning to write a compiler

I liked the Crenshaw tutorial too, because it makes it absolutely clear that a compiler is just another program that reads some input and writes some out put.

Read it.

Work it if you want, but then look at another reference on how bigger and more complete compilers are really written.

And read On Trusting Trust, to get a clue about the unobvious things that can be done in this domain.

Recyclerview and handling different type of row inflation

getItemViewType(int position) is the key

In my opinion,the starting point to create this kind of recyclerView is the knowledge of this method. Since this method is optional to override therefore it is not visible in RecylerView class by default which in turn makes many developers(including me) wonder where to begin. Once you know that this method exists, creating such RecyclerView would be a cakewalk.

enter image description here

How to do it ?

You can create a RecyclerView with any number of different Views(ViewHolders). But for better readability lets take an example of RecyclerView with two Viewholders.
Remember these 3 simple steps and you will be good to go.

  • Override public int getItemViewType(int position)
  • Return different ViewHolders based on the ViewType in onCreateViewHolder() method
  • Populate View based on the itemViewType in onBindViewHolder() method

    Here is a code snippet for you

    public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    
        private static final int LAYOUT_ONE= 0;
        private static final int LAYOUT_TWO= 1;
    
        @Override
        public int getItemViewType(int position)
        {
            if(position==0)
               return LAYOUT_ONE;
            else
               return LAYOUT_TWO;
        }
    
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    
            View view =null;
            RecyclerView.ViewHolder viewHolder = null;
    
            if(viewType==LAYOUT_ONE)
            {
               view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
               viewHolder = new ViewHolderOne(view);
            }
            else
            {
               view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
               viewHolder= new ViewHolderTwo(view);
            }
    
            return viewHolder;
        }
    
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    
           if(holder.getItemViewType()== LAYOUT_ONE)
           {
               // Typecast Viewholder 
               // Set Viewholder properties 
               // Add any click listener if any 
           }
           else {
    
               ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
               vaultItemHolder.name.setText(displayText);
               vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       .......
                   }
               });
    
           }
    
       }
    
       /****************  VIEW HOLDER 1 ******************//
    
       public class ViewHolderOne extends RecyclerView.ViewHolder {
    
           public TextView name;
    
           public ViewHolderOne(View itemView) {
           super(itemView);
           name = (TextView)itemView.findViewById(R.id.displayName);
           }
       }
    
    
      //****************  VIEW HOLDER 2 ******************//
    
      public class ViewHolderTwo extends RecyclerView.ViewHolder{
    
           public ViewHolderTwo(View itemView) {
           super(itemView);
    
               ..... Do something
           }
      }
    }
    

GitHub Code:

Here is a project where I have implemented a RecyclerView with multiple ViewHolders.

How to make a DIV always float on the screen in top right corner?

Use position:fixed, as previously stated, IE6 doesn't recognize position:fixed, but with some css magic you can get IE6 to behave:

html, body {
    height: 100%;
    overflow:auto;
}
body #fixedElement {
    position:fixed !important;
    position: absolute; /*ie6 */
    bottom: 0;
}

The !important flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement use position:fixed in all browsers but IE, and in IE, position:absolute will take effect with bottom:0. This will simulate position:fixed for IE6

Find html label associated with a given input

I know this is old, but I had trouble with some solutions and pieced this together. I have tested this on Windows (Chrome, Firefox and MSIE) and OS X (Chrome and Safari) and believe this is the simplest solution. It works with these three style of attaching a label.

<label><input type="checkbox" class="c123" id="cb1" name="item1">item1</label>

<input type="checkbox" class="c123" id="cb2" name="item2">item2</input>

<input type="checkbox" class="c123" id="cb3" name="item3"><label for="cb3">item3</label>

Using jQuery:

$(".c123").click(function() {
    $cb = $(this);
    $lb = $(this).parent();
    alert( $cb.attr('id') + ' = ' + $lb.text() );
});

My JSFiddle: http://jsfiddle.net/pnosko/6PQCw/

subquery in codeigniter active record

It may be a little late for the original question but for future queries this might help. Best way to achieve this is Get the result of the inner query to an array like this

$this->db->select('id');
$result = $this->db->get('your_table');
return  $result->result_array();

And then use than array in the following active record clause

$this->db->where_not_in('id_of_another_table', 'previously_returned_array');

Hope this helps

How do I connect to this localhost from another computer on the same network?

This tool saved me a lot, since I have no Admin permission on my machine and already had nodejs installed. For some reason the configuration on my network does not give me access to other machines just pointing the IP on the browser.

# Using a local.dev vhost
$ browser-sync start --proxy

# Using a local.dev vhost with PORT
$ browser-sync start --proxy local.dev:8001

# Using a localhost address
$ browser-sync start --proxy localhost:8001

# Using a localhost address in a sub-dir
$ browser-sync start --proxy localhost:8080/site1

http://www.browsersync.io/docs/command-line/

Adding a slide effect to bootstrap dropdown

Also it's possible to avoid using JavaScript for drop-down effect, and use CSS3 transition, by adding this small piece of code to your style:

.dropdown .dropdown-menu {
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    -ms-transition: all 0.3s;
    -o-transition: all 0.3s;
    transition: all 0.3s;

    max-height: 0;
    display: block;
    overflow: hidden;
    opacity: 0;
}

.dropdown.open .dropdown-menu { /* For Bootstrap 4, use .dropdown.show instead of .dropdown.open */
    max-height: 300px;
    opacity: 1;
}

The only problem with this way is that you should manually specify max-height. If you set a very big value, your animation will be very quick.

It works like a charm if you know the approximate height of your dropdowns, otherwise you still can use javascript to set a precise max-height value.

Here is small example: DEMO


! There is small bug with padding in this solution, check Jacob Stamm's comment with solution.

Deserialize json object into dynamic object using Json.net

Yes it is possible. I have been doing that all the while.

dynamic Obj = JsonConvert.DeserializeObject(<your json string>);

It is a bit trickier for non native type. Suppose inside your Obj, there is a ClassA, and ClassB objects. They are all converted to JObject. What you need to do is:

ClassA ObjA = Obj.ObjA.ToObject<ClassA>();
ClassB ObjB = Obj.ObjB.ToObject<ClassB>();

Correct way to initialize empty slice

They are equivalent. See this code:

mySlice1 := make([]int, 0)
mySlice2 := []int{}
fmt.Println("mySlice1", cap(mySlice1))
fmt.Println("mySlice2", cap(mySlice2))

Output:

mySlice1 0
mySlice2 0

Both slices have 0 capacity which implies both slices have 0 length (cannot be greater than the capacity) which implies both slices have no elements. This means the 2 slices are identical in every aspect.

See similar questions:

What is the point of having nil slice and empty slice in golang?

nil slices vs non-nil slices vs empty slices in Go language

How to fix "The ConnectionString property has not been initialized"

Simply in Code Behind Page use:-

SqlConnection con = new SqlConnection("Data Source = DellPC; Initial Catalog = Account; user = sa; password = admin");

It Should Work Just Fine

ReflectionException: Class ClassName does not exist - Laravel

Perform a composer update, then composer dump-autoload.

If the above doesn't solve the problem, change the classmap in your composer.json file such that it contains the project-relative path to your php files:

"autoload-dev": {
    "classmap": [
        "tests/TestCase.php",
        "database/seeds/UserTableSeeder.php" //include the file with its path here
    ]
}, /** ... */

and soon after, perform a composer dump-autoload, and it should work now like a breeze!

Edit by @JMSamudio

If composer dump-autoload is not found, just enable this option composer config -g -- disable-tls true.

Create a rounded button / button with border-radius in Flutter

If anybody is looking for complete circular button than I achieved it this way.

Center(
            child: SizedBox.fromSize(
              size: Size(80, 80), // button width and height
              child: ClipOval(
                child: Material(
                  color: Colors.pink[300], // button color
                  child: InkWell(
                    splashColor: Colors.yellow, // splash color
                    onTap: () {}, // button pressed
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(Icons.linked_camera), // icon
                        Text("Picture"), // text
                      ],
                    ),
                  ),
                ),
              ),
            ),
          )

How to get option text value using AngularJS?

<div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>

AngularJS:

angular.module('ngrepeatSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.data = {
    model: null,
    availableOptions: [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ]
   };
}]);

taken from AngularJS docs

Refreshing data in RecyclerView and keeping its scroll position

I have not used Recyclerview but I did it on ListView. Sample code in Recyclerview:

setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        rowPos = mLayoutManager.findFirstVisibleItemPosition();

It is the listener when user is scrolling. The performance overhead is not significant. And the first visible position is accurate this way.

HTML table: keep the same width for columns

well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.

Rails 3 execute custom sql query without a model

You could also use find_by_sql

# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]

What __init__ and self do in Python?

Yep, you are right, these are oop constructs.

__init__ is the constructor for a class. The self parameter refers to the instance of the object (like this in C++).

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

The __init__ method gets called when memory for the object is allocated:

x = Point(1,2)

It is important to use the self parameter inside an object's method if you want to persist the value with the object. If, for instance, you implement the __init__ method like this:

class Point:
    def __init__(self, x, y):
        _x = x
        _y = y

Your x and y parameters would be stored in variables on the stack and would be discarded when the init method goes out of scope. Setting those variables as self._x and self._y sets those variables as members of the Point object (accessible for the lifetime of the object).

Filtering Pandas DataFrames on dates

How about using pyjanitor

It has cool features.

After pip install pyjanitor

import janitor

df_filtered = df.filter_date(your_date_column_name, start_date, end_date)

What's the difference between MyISAM and InnoDB?

MYISAM:

  1. MYISAM supports Table-level Locking
  2. MyISAM designed for need of speed
  3. MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
  4. MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
  5. MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.
  6. MYISAM supports fulltext search
  7. You can use MyISAM, if the table is more static with lots of select and less update and delete.

INNODB:

  1. InnoDB supports Row-level Locking
  2. InnoDB designed for maximum performance when processing high volume of data
  3. InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
  4. InnoDB stores its tables and indexes in a tablespace
  5. InnoDB supports transaction. You can commit and rollback with InnoDB

How to use find command to find all files with extensions from list?

find /path/to -regex ".*\.\(jpg\|gif\|png\|jpeg\)" > log

How to set the environmental variable LD_LIBRARY_PATH in linux

For some reason no one has mentioned the fact that the bashrc needs to be re-sourced after editing. You can either log out and log back in (like mentioned above) but you can also use the commands: source ~/.bashrc or . ~/.bashrc.

Session variables not working php

The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.

session_set_cookie_params(0)

Move seaborn plot legend to a different position?

This is how I was able to move the legend to a particular place inside the plot and change the aspect and size of the plot:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set(style="ticks")

figure_name = 'rater_violinplot.png'
figure_output_path = output_path + figure_name

viol_plot = sns.factorplot(x="Rater", 
                       y="Confidence", 
                       hue="Event Type", 
                       data=combo_df, 
                       palette="colorblind",
                       kind='violin',
                       size = 10,
                       aspect = 1.5,
                       legend=False)

viol_plot.ax.legend(loc=2)
viol_plot.fig.savefig(figure_output_path)  

Legend location changed

This worked for me to change the size and aspect of the plot as well as move the legend outside the plot area.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set(style="ticks")


figure_name = 'rater_violinplot.png'
figure_output_path = output_path + figure_name

viol_plot = sns.factorplot(x="Rater", 
                       y="Confidence", 
                       hue="Event Type", 
                       data=combo_df, 
                       palette="colorblind",
                       kind='violin',
                       size = 10,
                       aspect = 1.5,
                       legend_out=True)

viol_plot.fig.savefig(figure_output_path)  

violin plot with changed size, aspect and legend located outside

I figured this out from mwaskom's answer here and Fernando Hernandez's answer here.

CSS vertical alignment of inline/inline-block elements

vertical-align applies to the elements being aligned, not their parent element. To vertically align the div's children, do this instead:

div > * {
    vertical-align:middle;  // Align children to middle of line
}

See: http://jsfiddle.net/dfmx123/TFPx8/1186/

NOTE: vertical-align is relative to the current text line, not the full height of the parent div. If you wanted the parent div to be taller and still have the elements vertically centered, set the div's line-height property instead of its height. Follow jsfiddle link above for an example.

Java: Casting Object to Array type

What you've got (according to the debug image) is an object array containing a string array. So you need something like:

Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];

You haven't shown the type of values - if this is already Object[] then you could just use (String[])values[0].

Of course even with the cast to Object[] you could still do it in one statement, but it's ugly:

String[] strings = (String[]) ((Object[])values)[0];

How to install PyQt4 in anaconda?

Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:

conda install pyqt=4

This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example

conda install pyqt=4.11

would install the latest (or last) release of version 4.11.

Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.

How to override the properties of a CSS class using another CSS class

If you list the bakground-none class after the other classes, its properties will override those already set. There is no need to use !important here.

For example:

.red { background-color: red; }
.background-none { background: none; }

and

<a class="red background-none" href="#carousel">...</a>

The link will not have a red background. Please note that this only overrides properties that have a selector that is less or equally specific.

Clear dropdown using jQuery Select2

Since none of them all worked for me (select2 4.0.3) is went the std select way.

for(var i = selectbox.options.length - 1 ; i >= 0 ; i--)
    selectbox.remove(i);

Eloquent Collection: Counting and Detect Empty

I think you are looking for:

$result->isEmpty()

This is different from empty($result), which will not be true because the result will be an empty collection. Your suggestion of count($result) is also a good solution. I cannot find any reference in the docs

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

As pointed out by other answers, in python they return floats probably because of historical reasons to prevent overflow problems. However, they return integers in python 3.

>>> import math
>>> type(math.floor(3.1))
<class 'int'>
>>> type(math.ceil(3.1))
<class 'int'>

You can find more information in PEP 3141.

Optional query string parameters in ASP.NET Web API

It's possible to pass multiple parameters as a single model as vijay suggested. This works for GET when you use the FromUri parameter attribute. This tells WebAPI to fill the model from the query parameters.

The result is a cleaner controller action with just a single parameter. For more information see: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

public class BooksController : ApiController
  {
    // GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
    public string GetFindBooks([FromUri]BookQuery query)
    {
      // ...
    }
  }

  public class BookQuery
  {
    public string Author { get; set; }
    public string Title { get; set; }
    public string ISBN { get; set; }
    public string SomethingElse { get; set; }
    public DateTime? Date { get; set; }
  }

It even supports multiple parameters, as long as the properties don't conflict.

// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query, [FromUri]Paging paging)
{
  // ...
}

public class Paging
{
  public string Sort { get; set; }
  public int Skip { get; set; }
  public int Take { get; set; }
}

Update:
In order to ensure the values are optional make sure to use reference types or nullables (ex. int?) for the models properties.

Uninstall Node.JS using Linux command line?

If you have yum you could do:

yum remove nodesource-release* nodejs

yum clean all

And after that check if its deleted:

rpm -qa 'node|npm'

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

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

The reason why @Resource(name = "{your child class name}") works but @Autowired sometimes don't work is because of the difference of their Matching sequence

Matching sequence of @Autowire
Type, Qualifier, Name

Matching sequence of @Resource
Name, Type, Qualifier

The more detail explanation can be found here:
Inject and Resource and Autowired annotations

In this case, different child class inherited from the parent class or interface confuses @Autowire, because they are from same type; As @Resource use Name as first matching priority , it works.

Swift - How to convert String to Double

we can use CDouble value which will be obtained by myString.doubleValue

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

Accessing dict_keys element by index in Python3

In many cases, this may be an XY Problem. Why are you indexing your dictionary keys by position? Do you really need to? Until recently, dictionaries were not even ordered in Python, so accessing the first element was arbitrary.

I just translated some Python 2 code to Python 3:

keys = d.keys()
for (i, res) in enumerate(some_list):
    k = keys[i]
    # ...

which is not pretty, but not very bad either. At first, I was about to replace it by the monstrous

    k = next(itertools.islice(iter(keys), i, None))

before I realised this is all much better written as

for (k, res) in zip(d.keys(), some_list):

which works just fine.

I believe that in many other cases, indexing dictionary keys by position can be avoided. Although dictionaries are ordered in Python 3.7, relying on that is not pretty. The code above only works because the contents of some_list had been recently produced from the contents of d.

Have a hard look at your code if you really need to access a disk_keys element by index. Perhaps you don't need to.

How to split a string between letters and digits (or between digits and letters)?

I was doing this sort of thing for mission critical code. Like every fraction of a second counts because I need to process 180k entries in an unnoticeable amount of time. So I skipped the regex and split altogether and allowed for inline processing of each element (though adding them to an ArrayList<String> would be fine). If you want to do this exact thing but need it to be something like 20x faster...

void parseGroups(String text) {
    int last = 0;
    int state = 0;
    for (int i = 0, s = text.length(); i < s; i++) {
        switch (text.charAt(i)) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                if (state == 2) {
                    processElement(text.substring(last, i));
                    last = i;
                }
                state = 1;
                break;
            default:
                if (state == 1) {
                    processElement(text.substring(last, i));
                    last = i;
                }
                state = 2;
                break;
        }
    }
    processElement(text.substring(last));
}

CORS with POSTMAN

CORS (Cross-Origin Resource Sharing) and SOP (Same-Origin Policy) are server-side configurations that clients decide to enforce or not.

Related to clients

  • Most Browsers do enforce it to prevent issues related to CSRF attack.
  • Most Development tools don't care about it.

Create an array with random values

If you need it with random unique values from 0...length range:

const randomRange = length => {
  const results = []
  const possibleValues = Array.from({ length }, (value, i) => i)

  for (let i = 0; i < length; i += 1) {
    const possibleValuesRange = length - (length - possibleValues.length)
    const randomNumber = Math.floor(Math.random() * possibleValuesRange)
    const normalizedRandomNumber = randomNumber !== possibleValuesRange ? randomNumber : possibleValuesRange

    const [nextNumber] = possibleValues.splice(normalizedRandomNumber, 1)

    results.push(nextNumber)
  }

  return results
}

randomRange(5) // [3, 0, 1, 4, 2]

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

How can I compile and run c# program without using visual studio?

I use a batch script to compile and run C#:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /out:%1 %2

@echo off

if errorlevel 1 (
    pause
    exit
)

start %1 %1

I call it like this:

C:\bin\csc.bat "C:\code\MyProgram.exe" "C:\code\MyProgram.cs"

I also have a shortcut in Notepad++, which you can define by going to Run > Run...:

C:\bin\csc.bat "$(CURRENT_DIRECTORY)\$(NAME_PART).exe" "$(FULL_CURRENT_PATH)"

I assigned this shortcut to my F5 key for maximum laziness.

Is it possible to specify the schema when connecting to postgres with JDBC?

Don't forget SET SCHEMA 'myschema' which you could use in a separate Statement

SET SCHEMA 'value' is an alias for SET search_path TO value. Only one schema can be specified using this syntax.

And since 9.4 and possibly earlier versions on the JDBC driver, there is support for the setSchema(String schemaName) method.

How do I see which version of Swift I'm using?

Bonus contribution: I'm using a custom node.js script to extract a clean string for use with Jazzy documentation. You might get some use of this if you can find a place to work it into your dev process:

Invoked from a Bash script:

#!/bin/bash
swiftversion=$(node SwiftVerSlicer.js "${xcrun swift -version}");
echo $swiftversion

SwiftVerSlicer.js:

// begin script
const inputString = `${process.argv[2]}`
let searchTerm = (inputString.indexOf('(') - 1)//-1 cause whitespace
let version = inputString.slice(0,searchTerm)
console.log(version)
// end script

You can also use regex of course, but do whatever you like :]

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Run this script from SharePoint 2010 Management Shell as Administrator.

Disable double-tap "zoom" option in browser on touch devices

Here we go

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

Failed to resolve: com.google.firebase:firebase-core:16.0.1

If you use Firebase in a library module, you need to apply the google play services gradle plugin to it in addition to the app(s) module(s), but also, you need to beware of version 4.2.0 (and 4.1.0) which are broken, and use version 4.0.2 instead.

Here's the issue: https://github.com/google/play-services-plugins/issues/22

How do I find the maximum of 2 numbers?

I noticed that if you have divisions it rounds off to integer, it would be better to use:

c=float(max(a1,...,an))/b

Sorry for the late post!

How to generate the "create table" sql statement for an existing table in postgreSQL

Here is another solution to the old question. There have been many excellent answers to this question over the years and my attempt borrows heavily from them.

I used Andrey Lebedenko's solution as a starting point because its output was already very close to my requirements.

Features:

  • following common practice I have moved the foreign key constraints outside the table definition. They are now included as ALTER TABLE statements at the bottom. The reason is that a foreign key can also link to a column of the same table. In that fringe case the constraint can only be created after the table creation is completed. The create table statement would throw an error otherwise.
  • The layout and indenting looks nicer now (at least to my eye)
  • Drop command (commented out) in the header of the definition
  • The solution is offered here as a plpgsql function. The algorithm does however not use any procedural language. The function just wraps one single query that can be used in a pure sql context as well.
  • removed redundant subqueries
  • Identifiers are now quoted if they are identical to reserved postgresql language elements
  • replaced the string concatenation operator || with the appropriate string functions to improve performance, security and readability of the code. Note: the || operator produces NULL if one of the combined strings is NULL. It should only be used when that is the desired behaviour. (check out the usage in the code below for an example)

CREATE OR REPLACE FUNCTION public.wmv_get_table_definition (
    p_schema_name character varying,
    p_table_name character varying
)
    RETURNS SETOF TEXT
    AS $BODY$
BEGIN
    RETURN query 
    WITH table_rec AS (
        SELECT
            c.relname, n.nspname, c.oid
        FROM
            pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
        WHERE
            relkind = 'r'
            AND n.nspname = p_schema_name
            AND c.relname LIKE p_table_name
        ORDER BY
            c.relname
    ),
    col_rec AS (
        SELECT
            a.attname AS colname,
            pg_catalog.format_type(a.atttypid, a.atttypmod) AS coltype,
            a.attrelid AS oid,
            ' DEFAULT ' || (
                SELECT
                    pg_catalog.pg_get_expr(d.adbin, d.adrelid)
                FROM
                    pg_catalog.pg_attrdef d
                WHERE
                    d.adrelid = a.attrelid
                    AND d.adnum = a.attnum
                    AND a.atthasdef) AS column_default_value,
            CASE WHEN a.attnotnull = TRUE THEN
                'NOT NULL'
            ELSE
                'NULL'
            END AS column_not_null,
            a.attnum AS attnum
        FROM
            pg_catalog.pg_attribute a
        WHERE
            a.attnum > 0
            AND NOT a.attisdropped
        ORDER BY
            a.attnum
    ),
    con_rec AS (
        SELECT
            conrelid::regclass::text AS relname,
            n.nspname,
            conname,
            pg_get_constraintdef(c.oid) AS condef,
            contype,
            conrelid AS oid
        FROM
            pg_constraint c
            JOIN pg_namespace n ON n.oid = c.connamespace
    ),
    glue AS (
        SELECT
            format( E'-- %1$I.%2$I definition\n\n-- Drop table\n\n-- DROP TABLE IF EXISTS %1$I.%2$I\n\nCREATE TABLE %1$I.%2$I (\n', table_rec.nspname, table_rec.relname) AS top,
            format( E'\n);\n\n\n-- adempiere.wmv_ghgaudit foreign keys\n\n', table_rec.nspname, table_rec.relname) AS bottom,
            oid
        FROM
            table_rec
    ),
    cols AS (
        SELECT
            string_agg(format('    %I %s%s %s', colname, coltype, column_default_value, column_not_null), E',\n') AS lines,
            oid
        FROM
            col_rec
        GROUP BY
            oid
    ),
    constrnt AS (
        SELECT
            string_agg(format('    CONSTRAINT %s %s', con_rec.conname, con_rec.condef), E',\n') AS lines,
            oid
        FROM
            con_rec
        WHERE
            contype <> 'f'
        GROUP BY
            oid
    ),
    frnkey AS (
        SELECT
            string_agg(format('ALTER TABLE %I.%I ADD CONSTRAINT %s %s', nspname, relname, conname, condef), E';\n') AS lines,
            oid
        FROM
            con_rec
        WHERE
            contype = 'f'
        GROUP BY
            oid
    )
    SELECT
        concat(glue.top, cols.lines, E',\n', constrnt.lines, glue.bottom, frnkey.lines, ';')
    FROM
        glue
        JOIN cols ON cols.oid = glue.oid
        LEFT JOIN constrnt ON constrnt.oid = glue.oid
        LEFT JOIN frnkey ON frnkey.oid = glue.oid;
END;
$BODY$
LANGUAGE plpgsql;

Python assigning multiple variables to same value? list behavior

in your first example a = b = c = [1, 2, 3] you are really saying:

 'a' is the same as 'b', is the same as 'c' and they are all [1, 2, 3]

If you want to set 'a' equal to 1, 'b' equal to '2' and 'c' equal to 3, try this:

a, b, c = [1, 2, 3]

print(a)
--> 1
print(b)
--> 2
print(c)
--> 3

Hope this helps!

jQuery add text to span within a div

Careful - append() will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>').

Use text() to replace element content with text, or append(document.createTextNode(x)) to append a text node.

Verify a certificate chain using openssl verify

If you only want to verify that issuer of UserCert.pem is actually Intermediate.pem do the following (example uses: OpenSSL 1.1.1):

openssl verify -no-CAfile -no-CApath -partial_chain -trusted Intermediate.pem UserCert.pem

and you will get:

UserCert.pem: OK

or

UserCert.pem: verification failed

How to access model hasMany Relation with where condition?

I think this is what you're looking for (Laravel 4, see http://laravel.com/docs/eloquent#querying-relations)

$games = Game::whereHas('video', function($q)
{
    $q->where('available','=', 1);

})->get();

How to get current SIM card number in Android?

You can use the TelephonyManager to do this:

TelephonyManager t = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
String number = t.getLine1Number();

Have you used

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

Good tool for testing socket connections?

I also found a tool called TCP/IP Test Server [Edit: no longer available from the original developer, but still available via Brothersoft] which seems to do what I need too. But I didn't try it because it is not listed on big freeware-sites (like CNET...) and no source code is published so that it won't reassure a paranoid sysadmin.

How do I search a Perl array for a matching string?

I guess

@foo = ("aAa", "bbb");
@bar = grep(/^aaa/i, @foo);
print join ",",@bar;

would do the trick.

notifyDataSetChanged example

You can use the runOnUiThread() method as follows. If you're not using a ListActivity, just adapt the code to get a reference to your ArrayAdapter.

final ArrayAdapter adapter = ((ArrayAdapter)getListAdapter());
runOnUiThread(new Runnable() {
    public void run() {
        adapter.notifyDataSetChanged();
    }
});

Saving an Excel sheet in a current directory with VBA

VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.

MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"

This assumes that the sheet you want to save has never been saved and you want to define the file name in code.

Return the characters after Nth character in a string

Alternately, you could do a Text to Columns with space as the delimiter.

what is reverse() in Django

The reverse() is used to adhere the django DRY principle i.e if you change the url in future then you can reference that url using reverse(urlname).

How do I get the different parts of a Flask request's url?

another example:

request:

curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y

then:

request.method:              GET
request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.url_charset:         utf-8
request.url_root:            http://127.0.0.1:5000/
str(request.url_rule):       /alert/dingding/test
request.host_url:            http://127.0.0.1:5000/
request.host:                127.0.0.1:5000
request.script_root:
request.path:                /alert/dingding/test
request.full_path:           /alert/dingding/test?x=y

request.args:                ImmutableMultiDict([('x', 'y')])
request.args.get('x'):       y

.attr("disabled", "disabled") issue

Thank you all for your contribution! I found the problem:

ITS A FIREBUG BUG !!!

My code works. I have asked the PHP Dev to change the input types hidden in to input type text. The disabled feature works. But the firebug console does not update this status!

you can test out this firebug bug by your self here http://jsbin.com/uneti3/3#. Thx to aSeptik for the example page.

update: 2. June 2012: Firebug in FF11 still has this bug.

Deactivate or remove the scrollbar on HTML

In HTML

<div style="overflow: hidden;">

in CSS

overflow: hidden;

you can also end scrolling for x or y separately

overflow-y: hidden; /* Hide vertical scrollbar */
  overflow-x: hidden; /* Hide horizontal scrollbar */

How can I get the class name from a C++ object?

Just write simple template:

template<typename T>
const char* getClassName(T) {
  return typeid(T).name();
}

struct A {} a;

void main() {
   std::cout << getClassName(a);
}

How to implement LIMIT with SQL Server?

If i remember correctly (it's been a while since i dabbed with SQL Server) you may be able to use something like this: (2005 and up)

SELECT
    *
   ,ROW_NUMBER() OVER(ORDER BY SomeFields) AS [RowNum]
FROM SomeTable
WHERE RowNum BETWEEN 10 AND 20

Using set_facts and with_items together in Ansible

Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.

- name: Set fact 4
  set_fact:
    foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"

I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.

- name: build foo_string
  set_fact:
    foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"

- name: set fact foo
  set_fact:
    foo: "{{ foo_string.split(',') }}"

How to decompile to java files intellij idea

To use the IntelliJ Java decompiler from the command line for a jar package follow the instructions provided here: https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler/engine

Determine file creation date in Java

in java1.7+ You can use this code to get file`s create time !

private static LocalDateTime getCreateTime(File file) throws IOException {
        Path path = Paths.get(file.getPath());
        BasicFileAttributeView basicfile = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        BasicFileAttributes attr = basicfile.readAttributes();
        long date = attr.creationTime().toMillis();
        Instant instant = Instant.ofEpochMilli(date);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

python pandas convert index to datetime

You could explicitly create a DatetimeIndex when initializing the dataframe. Assuming your data is in string format

data = [
    ('2015-09-25 00:46', '71.925000'),
    ('2015-09-25 00:47', '71.625000'),
    ('2015-09-25 00:48', '71.333333'),
    ('2015-09-25 00:49', '64.571429'),
    ('2015-09-25 00:50', '72.285714'),
]

index, values = zip(*data)

frame = pd.DataFrame({
    'values': values
}, index=pd.DatetimeIndex(index))

print(frame.index.minute)

Ping all addresses in network, windows

Provided the windows box is in the same subnet:

for /L %a in (1,1,254) do start ping 192.168.0.%a

This will complete in less than 15 seconds and

arp -a 

will return any alive host.

Fastest native way I know of in Windows.

Read url to string in few lines of java code

Or just use Apache Commons IOUtils.toString(URL url), or the variant that also accepts an encoding parameter.

Can a constructor in Java be private?

Can a constructor be private? How is a private constructor useful?

Yes it can. I consider this another example of it being useful:

//... ErrorType.java
public enum ErrorType {
    X,
    Y,
    Z
}

//... ErrorTypeException.java
import java.util.*;
import java.lang.*;
import java.io.*;

//Translates ErrorTypes only
abstract public class ErrorTypeException extends Exception {
    private ErrorTypeException(){}

    //I don't want to expose thse
    static private class Xx extends ErrorTypeException {}
    static private class Yx extends ErrorTypeException {}
    static private class Zx extends ErrorTypeException {}

    // Want translation without exposing underlying type
    public static Exception from(ErrorType errorType) {
        switch (errorType) {
            case X:
                return new Xx();    
            case Y:
                return new Yx();
            default:
                return new Zx();
        }
    }

    // Want to get hold of class without exposing underlying type
    public static Class<? extends ErrorTypeException> toExceptionClass(ErrorType errorType) {
        switch (errorType) {
            case X:
                return Xx.class;    
            case Y:
                return Yx.class;
            default:
                return Zx.class;
        }
    }
}

In the case here above, it prevents the abstract class from being instantiated by any derived class other than it's static inner classes. Abstract classes cannot be final, but in this case the private constructor makes it effectively final to all classes that aren't inner classes

error: ORA-65096: invalid common user or role name in oracle

Create user dependency upon the database connect tools

sql plus
SQL> connect as sysdba;
Enter user-name: sysdba
Enter password:
Connected.
SQL> ALTER USER hr account unlock identified by hr;
User altered
 then create user on sql plus and sql developer

Create two blank lines in Markdown

Basically, if the library you are using is CommonMark-compliant, you can add multiple hard line breaks (<br />) easily. Here's a quotation from CommonMark's latest specifications (0.28):

A line break (not in a code span or HTML tag) that is preceded by two or more spaces and does not occur at the end of a block is parsed as a hard line break (rendered in HTML as a
tag)

and then...

For a more visible alternative, a backslash before the line ending may be used instead of two spaces

The specification is quite clear. However, the library I have been using MarkDig, doesn't quite work with the two spaces technique (must be a bug), but it works flawlessly with a backlash.

That said, this input...

Line one\
\
\
\
Line two

will produce four hard line breaks after "Line one". You can see it here (using backlash)...

https://babelmark.github.io/?text=Line+one%5C%0A%5C%0A%5C%0A%5C%0ALine+two%0A

Notice how all CommonMark-compliant implementations will get it right.

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Note: if you upgrade from spring boot 1 to spring boot 2 there is a ResponseStatusException which has a Http error code and a description.

So, you can effectively use generics they way it is intended.

The only case which is a bit challenging for me, is the response type for a status 204 (ok with no body). I tend to mark those methods as ResponseEntity<?>, because ResponseEntity<Void> is less predictive.

ng-change get new value and original value

You can use something like ng-change=someMethod({{user.id}}). By keeping your value in side {{expression}} it will evaluate expression in-line and gives you current value(value before ng-change method is called).

<select ng-model="selectedValue" ng-change="change(selectedValue, '{{selectedValue}}')">

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

dataGridView1.Columns is probably of a length less than 5. Accessing dataGridView1.Columns[4] then will be outside the list.

How do you convert a DataTable into a generic list?

You could use

List<DataRow> list = new List<DataRow>(dt.Select());

dt.Select() will return all rows in your table, as an array of datarows, and the List constructor accepts that array of objects as an argument to initially fill your list with.

rsync: how can I configure it to create target directory on server?

The -R, --relative option will do this.

For example: if you want to backup /var/named/chroot and create the same directory structure on the remote server then -R will do just that.

Object Required Error in excel VBA

In order to set the value of integer variable we simply assign the value to it. eg g1val = 0 where as set keyword is used to assign value to object.

Sub test()

Dim g1val, g2val As Integer

  g1val = 0
  g2val = 0

    For i = 3 To 18

     If g1val > Cells(33, i).Value Then
        g1val = g1val
    Else
       g1val = Cells(33, i).Value
     End If

    Next i

    For j = 32 To 57
        If g2val > Cells(31, j).Value Then
           g2val = g2val
        Else
          g2val = Cells(31, j).Value
        End If
    Next j

End Sub

Fixing the order of facets in ggplot

Make your size a factor in your dataframe by:

temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))

Then change the facet_grid(.~size) to facet_grid(.~size_f)

Then plot: enter image description here

The graphs are now in the correct order.

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

How can I override Bootstrap CSS styles?

See https://bootstrap.themes.guide/how-to-customize-bootstrap.html

  1. For simple CSS Overrides, you can add a custom.css below the bootstrap.css

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    
  2. For more extensive changes, SASS is the recommended method.

    • create your own custom.scss
    • import Bootstrap after the changes in custom.scss
    • For example, let’s change the body background-color to light-gray #eeeeee, and change the blue primary contextual color to Bootstrap's $purple variable...

      /* custom.scss */    
      
      /* import the necessary Bootstrap files */
      @import "bootstrap/functions";
      @import "bootstrap/variables";
      
      /* -------begin customization-------- */   
      
      /* simply assign the value */ 
      $body-bg: #eeeeee;
      
      /* or, use an existing variable */
      $theme-colors: (
        primary: $purple
      );
      /* -------end customization-------- */  
      
      /* finally, import Bootstrap to set the changes! */
      @import "bootstrap";
      

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

Not knowing the actual details, my guess is that it makes an attempt to join like you might join relative URIs. For example:

urljoin('/some/abs/path', '../other') = '/some/abs/other'

This means that when you join a path with a preceding slash, you are actually joining one base to another, in which case the second gets precedence.

How to control the line spacing in UILabel

Here is a class that subclass UILabel to have line-height property : https://github.com/LemonCake/MSLabel

Angular2 Material Dialog css, dialog size

On smaller screen's like laptop the dialog will shrink. To auto-fix, try the following option

http://answersicouldntfindanywhereelse.blogspot.com/2018/05/angular-material-full-size-dialog-on.html

Additional Reading https://material.angular.io/cdk/layout/overview

Thanks to the solution in answersicouldntfindanywhereelse (2nd para). it worked for me.

Following is needed

import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout'

how to set the background color of the whole page in css

I've checked your source code and find to change to yellow you need to adds the yellow background color to : #left-padding, #right-padding, html, #hd, #main and #yui-main.

Hope it's what you wanted. See ya

enter image description here

GridView sorting: SortDirection always Ascending

It can be done without the use of View State or Session. Current order can be determined based on value in first and last row in the column we sort by:

        protected void gvItems_Sorting(object sender, GridViewSortEventArgs e)
    {
        GridView grid = sender as GridView; // get reference to grid
        SortDirection currentSortDirection = SortDirection.Ascending; // default order

        // get column index by SortExpression
        int columnIndex = grid.Columns.IndexOf(grid.Columns.OfType<DataControlField>()
                                      .First(x => x.SortExpression == e.SortExpression));

        // sort only if grid has more than 1 row
        if (grid.Rows.Count > 1)
        {
            // get cells
            TableCell firstCell = grid.Rows[0].Cells[columnIndex];
            TableCell lastCell = grid.Rows[grid.Rows.Count - 1].Cells[columnIndex];

            // if field type of the cell is 'TemplateField' Text property is always empty.
            // Below assumes that value is binded to Label control in 'TemplateField'.
            string firstCellValue = firstCell.Controls.Count == 0 ? firstCell.Text : ((Label)firstCell.Controls[1]).Text;
            string lastCellValue = lastCell.Controls.Count == 0 ? lastCell.Text : ((Label)lastCell.Controls[1]).Text;

            DateTime tmpDate;
            decimal tmpDecimal;

            // try to determinate cell type to ensure correct ordering
            // by date or number
            if (DateTime.TryParse(firstCellValue, out tmpDate)) // sort as DateTime
            {
                currentSortDirection = 
                    DateTime.Compare(Convert.ToDateTime(firstCellValue), 
                                     Convert.ToDateTime(lastCellValue)) < 0 ? 
                                            SortDirection.Ascending : SortDirection.Descending;
            }
            else if (Decimal.TryParse(firstCellValue, out tmpDecimal)) // sort as any numeric type
            {
                currentSortDirection = Decimal.Compare(Convert.ToDecimal(firstCellValue), 
                                                       Convert.ToDecimal(lastCellValue)) < 0 ? 
                                                       SortDirection.Ascending : SortDirection.Descending;
            }
            else // sort as string
            {
                currentSortDirection = string.CompareOrdinal(firstCellValue, lastCellValue) < 0 ? 
                                                             SortDirection.Ascending : SortDirection.Descending;
            }
        }

        // then bind GridView using correct sorting direction (in this example I use Linq)
        if (currentSortDirection == SortDirection.Descending)
        {
            grid.DataSource = myItems.OrderBy(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));
        }
        else
        {
            grid.DataSource = myItems.OrderByDescending(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));
        }

        grid.DataBind();
    }

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

Same problem. List contained numbers of type numpy.int64 which throws a TypeError. Quick workaround for me was to

mylist = eval(str(mylist_of_integers))
json.dumps({'mylist': mylist})

which converts list to str() and eval() function evaluates the String like a Python expression and returns the result as a list of integers in my case.

How can I close a login form and show the main form without my application closing?

I would do this the other way round.

In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.

EDIT Code sample(s)

private void MainForm_Load(object sender, EventArgs e)
{
    this.Hide();

    LogonForm logon = new LogonForm();

    if (logon.ShowDialog() != DialogResult.OK)
    {
        //Handle authentication failures as necessary, for example:
        Application.Exit();
    }
    else
    {
        this.Show();
    }
}

Another solution would be to show the LogonForm from the Main method in program.cs, something like this:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    LogonForm logon = new LogonForm();

    Application.Run(logon);

    if (logon.LogonSuccessful)
    {
        Application.Run(new MainForm());
    }
}

In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials

Extracting jar to specified directory

In case you don't want to change your current working directory, it might be easier to run extract command in a subshell like this.

mkdir -p "/path/to/target-dir"
(cd "/path/to/target-dir" && exec jar -xf "/path/to/your/war-file.war")

You can then execute this script from any working directory.

[ Thanks to David Schmitt for the subshell trick ]

outline on only one border

Try with Shadow( Like border ) + Border

border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;

How do you refresh the MySQL configuration file without restarting?

Try:

sudo /etc/init.d/mysql reload

or

sudo /etc/init.d/mysql force-reload

That should initiate a reload of the configuration. Make sureyour init.d script supports it though, I don't know what version of MySQL/OS you are using?

My MySQL script contains the following:

'reload'|'force-reload')
        log_daemon_msg "Reloading MySQL database server" "mysqld"
        $MYADMIN reload
        log_end_msg 0
        ;;

Best way to use multiple SSH private keys on one client

Now, with the recent version of Git, we can specify sshCommand in the repository-specific Git configuration file:

  [core]
      repositoryformatversion = 0
      filemode = true
      bare = false
      logallrefupdates = true
      sshCommand = ssh -i ~/.ssh/id_rsa_user
   [remote "origin"]
      url = [email protected]:user/repo.git
      fetch = +refs/heads/*:refs/remotes/origin/*

Is it possible to specify proxy credentials in your web.config?

Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision

Converting String To Float in C#

You can use parsing with double instead of float to get more precision value.

VBA Subscript out of range - error 9

Option Explicit

Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook


TitleId = 4
Resultid = 0

Dim FileName1, FileName2 As String
Dim Difference As Long



'TestPassCount = 0
'TestFailCount = 0

'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count

If (TestDataRowCount <= 2) Then
  MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
  For RecordId = 3 To TestDataRowCount
    RefreshResultSheet

    'Source File row count
    SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
    Set sourcewb = Workbooks.Open(SrceFile)
    With sourcewb.Worksheets(1)
      SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      sourcewb.Close
    End With

    'Target File row count
    TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
    Set targetwb = Workbooks.Open(TrgtFile)
    With targetwb.Worksheets(1)
      TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      targetwb.Close
    End With

    ' Set Row Count Result Test data value
    TitleId = TitleId + 3
    Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value

    'Compare Source and Target Row count
    Resultid = TitleId + 1
    Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
    If (SourceRowCount = TargetRowCount) Then
       Worksheets("Result").Range("B" & Resultid).Value = "Passed"
       Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
       TestPassCount = TestPassCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Failed"
      Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
      TestFailCount = TestFailCount + 1
    End If


    'For comparison of two files

    FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
    FileName2 = Worksheets("TestData").Range("E" & RecordId).Value

    Set myWorkbook1 = Workbooks.Open(FileName1)
    Set myWorkbook2 = Workbooks.Open(FileName2)

    Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
    myWorkbook1.Close
    myWorkbook2.Close


    'MsgBox Difference

    'Set Result of data validation in result sheet
    Resultid = Resultid + 1

    Worksheets("Result").Activate
    Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"

    If Difference > 0 Then
        Worksheets("Result").Range("B" & Resultid).Value = "Failed"
        Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
        TestFailCount = TestFailCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Passed"
      Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
      TestPassCount = TestPassCount + 1
    End If


  Next RecordId
End If

UpdateTestExecData TestPassCount, TestFailCount
End Sub

Sub RefreshResultSheet()
  Worksheets("Result").Activate
  Worksheets("Result").Range("B1:B4").Select
  Selection.ClearContents
  Worksheets("Result").Range("D1:D4").Select
  Selection.ClearContents
  Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
  Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
  Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
  Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub

Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
  Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
  Worksheets("Result").Range("D2").Value = TestPassCount
  Worksheets("Result").Range("D3").Value = TestFailCount
  Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub

Clear git local cache

To remove cached .idea/ directory. e.g. git rm -r --cached .idea

Difference between SurfaceView and View?

updated 05/09/2014

OK. We have official document now. It talked all I have mentioned, in a better way.


Read more detailed here.

Yes, the main difference is surfaceView can be updated on the background thread. However, there are more you might care.

  • surfaceView has dedicate surface buffer while all the view shares one surface buffer that is allocated by ViewRoot. In another word, surfaceView cost more resources.

  • surfaceView cannot be hardware accelerated (as of JB4.2) while 95% operations on normal View are HW accelerated using openGL ES.

  • More work should be done to create your customized surfaceView. You need to listener to the surfaceCreated/Destroy Event, create an render thread, more importantly, synchronized the render thread and main thread. However, to customize the View, all you need to do is override onDraw method.

  • The timing to update is different. Normal view update mechanism is constraint or controlled by the framework:You call view.invalidate in the UI thread or view.postInvalid in other thread to indicate to the framework that the view should be updated. However, the view won't be updated immediately but wait until next VSYNC event arrived. The easy approach to understand VSYNC is to consider it is as a timer that fire up every 16ms for a 60fps screen. In Android, all the normal view update (and display actually but I won't talk it today), is synchronized with VSYNC to achieve better smoothness. Now,back to the surfaceView, you can render it anytime as you wish. However, I can hardly tell if it is an advantage, since the display is also synchronized with VSYNC, as stated previously.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Editing the date formatting of x-axis tick labels in matplotlib

In short:

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

Many examples on the matplotlib website. The one I most commonly use is here

How can I upgrade NumPy?

This works for me:

pip install numpy --upgrade

How to check if a std::thread is still running?

Create a mutex that the running thread and the calling thread both have access to. When the running thread starts it locks the mutex, and when it ends it unlocks the mutex. To check if the thread is still running, the calling thread calls mutex.try_lock(). The return value of that is the status of the thread. (Just make sure to unlock the mutex if the try_lock worked)

One small problem with this, mutex.try_lock() will return false between the time the thread is created, and when it locks the mutex, but this can be avoided using a slightly more complex method.

Unable to install pyodbc on Linux

I used this:

yum install unixODBC.x86_64

Depending on the version of centos could change the package, you can search like this:

yum search unixodbc

Multipart File upload Spring Boot

You can simply use a controller method like this:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
    @RequestParam("file") MultipartFile file) {

  try {
    // Handle the received file here
    // ...
  }
  catch (Exception e) {
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  }

  return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile

Without any additional configurations for Spring Boot.

Using the following html form client side:

<html>
<body>
  <form action="/uploadFile" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload"> 
  </form>
</body>
</html>

If you want to set limits on files size you can do it in the application.properties:

# File size limit
multipart.maxFileSize = 3Mb

# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb

Moreover to send the file with Ajax take a look here: http://blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/

jQuery - disable selected options

This seems to work:

$("#theSelect").change(function(){          
    var value = $("#theSelect option:selected").val();
    var theDiv = $(".is" + value);

    theDiv.slideDown().removeClass("hidden");
    //Add this...
    $("#theSelect option:selected").attr('disabled', 'disabled');
});


$("div a.remove").click(function () {     
    $(this).parent().slideUp(function() { $(this).addClass("hidden"); });
    //...and this.
    $("#theSelect option:disabled").removeAttr('disabled');
});

How to exclude a directory in find . command

The following commands works:

find . -path ./.git -prune -o -print

If You have a problem with find, use the -D tree option to view the expression analysis information.

find -D tree . -path ./.git -prune -o -print

Or the -D all, to see all the execution information.

find -D all . -path ./.git -prune -o -print

How do I select an element that has a certain class?

The element.class selector is for styling situations such as this:

<span class="large"> </span>
<p class="large"> </p>

.large {
    font-size:150%; font-weight:bold;
}

p.large {
    color:blue;
}

Both your span and p will be assigned the font-size and font-weight from .large, but the color blue will only be assigned to p.

As others have pointed out, what you're working with is descendant selectors.

Get the position of a div/span tag

I realize this is an old thread, but @alex 's answer needs to be marked as the correct answer

element.getBoundingClientRect() is an exact match to jQuery's $(element).offset()

And it's compatible with IE4+ ... https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect

Set equal width of columns in table layout in Android

Change android:stretchColumns value to *.

Value 0 means stretch the first column. Value 1 means stretch the second column and so on.

Value * means stretch all the columns.

Assign keyboard shortcut to run procedure

You can add some ALT+Letter shortcuts to the VBA editor environment. I added ALT+C to Comment selected text lines and A+X to Uncomment selected text lines:

  1. In the VBE, right-click on a toolbar and select Customize
  2. Optionally create a new toolbar
  3. Select the Command Tab and 'Edit' in the Categories listbox. Find 'Comment Block' in the Commands listbox. Click and drag it to the target toolbar. Left-click on it to open the context popup menu and select 'Image and Text'. Replace the name with &C.
  4. Repeat step 3 for the Uncomment Block command and replace the name with &X.
  5. Close the Customize popup window.

There are built-in Alt+Letter commands that cannot be used for new shortcuts using letters: A,D,E,D,H,I,O,Q,R,T,V,W.

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

Git refusing to merge unrelated histories on rebase

I ran this command and issue got resolved.

git pull origin branchName --allow-unrelated-histories

Check out this page for more info.

How to get all count of mongoose model?

The collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead.

userModel.countDocuments(query).exec((err, count) => {
    if (err) {
        res.send(err);
        return;
    }

    res.json({ count: count });
});

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

what's the default value of char?

I think it is '\u00000' or just '' rather than '\u0000' (The 1st one has 5 zeros while the last one has four zeroes.)

C# Linq Where Date Between 2 Dates

_x000D_
_x000D_
 public List<tbltask> gettaskssdata(int? c, int? userid, string a, string StartDate, string EndDate, int? ProjectID, int? statusid)_x000D_
        {_x000D_
            List<tbltask> tbtask = new List<tbltask>();_x000D_
            DateTime sdate = (StartDate != "") ? Convert.ToDateTime(StartDate).Date : new DateTime();_x000D_
            DateTime edate = (EndDate != "") ? Convert.ToDateTime(EndDate).Date : new DateTime();_x000D_
            tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser)._x000D_
                Where(x => x.tblproject.company_id == c_x000D_
                    && (ProjectID == 0 || ProjectID == x.tblproject.ProjectId)_x000D_
                    && (statusid == 0 || statusid == x.tblstatu.StatusId)_x000D_
                    && (a == "" || (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)))_x000D_
                    && ((StartDate == "" && EndDate == "") || ((x.StartDate >= sdate && x.EndDate <= edate)))).ToList();_x000D_
_x000D_
_x000D_
_x000D_
            return tbtask;_x000D_
_x000D_
_x000D_
        }
_x000D_
_x000D_
_x000D_

this my query for search records based on searchdata and between start to end date

Removing single-quote from a string in php

You can substitute in HTML entitiy:

$FileName = preg_replace("/'/", "\&#39;", $UserInput);

Understanding the difference between Object.create() and new SomeFunction()

The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.

Yes, Object.create builds an object that inherits directly from the one passed as its first argument.

With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:

var o = new SomeConstructor();

In the above example, o inherits directly from SomeConstructor.prototype.

There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.

You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.

Well, you can create closures, e.g. using property descriptors argument:

var o = Object.create({inherited: 1}, {
  foo: {
    get: (function () { // a closure
      var closured = 'foo';
      return function () {
        return closured+'bar';
      };
    })()
  }
});

o.foo; // "foobar"

Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.

The method is starting to be natively implemented on latest browsers, check this compatibility table.

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

Focusable EditText inside ListView

I just found another solution. I believe it's more a hack than a solution but it works on android 2.3.7 and android 4.3 (I've even tested that good old D-pad)

init your webview as usual and add this: (thanks Michael Bierman)

listView.setItemsCanFocus(true);

During the getView call:

editText.setOnFocusChangeListener(
    new OnFocusChangeListener(View view,boolean hasFocus){
        view.post(new Runnable() {
            @Override
            public void run() {
                view.requestFocus();
                view.requestFocusFromTouch();
            }
     });

Android: Share plain text using intent (to all messaging apps)

Images or binary data:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpg");
Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

or HTML:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));

Can I pass an array as arguments to a method with variable arguments in Java?

I was having same issue.

String[] arr= new String[] { "A", "B", "C" };
Object obj = arr;

And then passed the obj as varargs argument. It worked.

Twig: in_array or similar possible within if statement?

It should help you.

{% for user in users if user.active and user.id not 1 %}
   {{ user.name }}
{% endfor %}

More info: http://twig.sensiolabs.org/doc/tags/for.html

Copy files to network computers on windows command line

Why for? What do you want to iterate? Try this.

call :cpy pc-name-1
call :cpy pc-name-2
...

:cpy
net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF

Observable Finally on Subscribe

The only thing which worked for me is this

fetchData()
  .subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //Called when operation is complete (both success and error)
  });

Search for all occurrences of a string in a mysql database

You can do this by using HeidiSQL without generating Db dumps

Steps:

1) Select the database you need to search in from the left panel of GUI.

2) Export > Export Database as SQL

3) In Table Tools window select "FIND TEXT" tab.

4) Provide your string to search and click "FIND".

5) It will list all the tables contains our string.

6) Select the row with higher relevance %.

7) Click "SEE RESULTS"

enter image description here

Draw horizontal rule in React Native

import { View, Dimensions } from 'react-native'

var { width, height } = Dimensions.get('window')

// Create Component

<View style={{
   borderBottomColor: 'black', 
   borderBottomWidth: 0.5, 
   width: width - 20,}}>
</View>

Creating an R dataframe row-by-row

If you have vectors destined to become rows, concatenate them using c(), pass them to a matrix row-by-row, and convert that matrix to a dataframe.

For example, rows

dummydata1=c(2002,10,1,12.00,101,426340.0,4411238.0,3598.0,0.92,57.77,4.80,238.29,-9.9)
dummydata2=c(2002,10,2,12.00,101,426340.0,4411238.0,3598.0,-3.02,78.77,-9999.00,-99.0,-9.9)
dummydata3=c(2002,10,8,12.00,101,426340.0,4411238.0,3598.0,-5.02,88.77,-9999.00,-99.0,-9.9)

can be converted to a data frame thus:

dummyset=c(dummydata1,dummydata2,dummydata3)
col.len=length(dummydata1)
dummytable=data.frame(matrix(data=dummyset,ncol=col.len,byrow=TRUE))

Admittedly, I see 2 major limitations: (1) this only works with single-mode data, and (2) you must know your final # columns for this to work (i.e., I'm assuming that you're not working with a ragged array whose greatest row length is unknown a priori).

This solution seems simple, but from my experience with type conversions in R, I'm sure it creates new challenges down-the-line. Can anyone comment on this?

ActiveRecord find and only return selected columns

In Rails 2

l = Location.find(:id => id, :select => "name, website, city", :limit => 1)

...or...

l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])

This reference doc gives you the entire list of options you can use with .find, including how to limit by number, id, or any other arbitrary column/constraint.

In Rails 3 w/ActiveRecord Query Interface

l = Location.where(["id = ?", id]).select("name, website, city").first

Ref: Active Record Query Interface

You can also swap the order of these chained calls, doing .select(...).where(...).first - all these calls do is construct the SQL query and then send it off.

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

I know this is an old question, but still unanswered. It took me a day of research, but I found the simplest solution, at least in my case (Oracle 11.2 on Windows 2008 R2) and wanted to share.

The error, if looked at directly, indicates that the listener does not recognize the service name. But where does it keep service names? In %ORACLE_HOME%\NETWORK\ADMIN\listener.ora

The "SID_LIST" is just that, a list of SIDs and service names paired up in a format you can copy or lookup.

I added the problem Service Name, then in Windows "Services" control panel, I did a "Restart" on the Oracle listener service. Now all is well.


For example, your listener.ora file might initially look like:

# listener.ora Network Configuration File: C:\app\oracle_user\product\12.1.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\oracle_user\product\12.1.0\dbhome_1\bin\oraclr12.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

... And to make it recognize a service name of orcl, you might change it to:

# listener.ora Network Configuration File: C:\app\oracle_user\product\12.1.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\oracle_user\product\12.1.0\dbhome_1\bin\oraclr12.dll")
    )
    (SID_DESC = 
        (GLOBAL_DBNAME = orcl)
        (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
        (SID_NAME = orcl)
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

How can I style the border and title bar of a window in WPF?

If someone says you can't because only Windows can control the non-client area, they're wrong!

That's just a half-truth because Windows lets you specify the dimensions of the non-client area. The fact is, this is possible only throughout the Windows' kernel methods, and you're in .NET, not C/C++. Anyway, don't worry! P/Invoke was meant just for such things! Indeed, the whole of the Windows Form UI and Console application Std-I/O methods are offered using system calls. Hence, you'd have only to perform the right system calls to set the non-client area up, as documented in MSDN.

However, this is a really hard solution I came up with a lot of time ago. Luckily, as of .NET 4.5, you can use the WindowChrome class to adjust the non-client area like you want. Here you can get to start with.

In order to make things simpler and cleaner, I'll redirect you here, a guide to change the window border dimensions to whatever you want. By setting it to 0, you'll be able to implement your custom window border in place of the system's one.

I'm sorry for not posting a clear example, but later I will for sure.

Use Awk to extract substring

Or just use cut:

echo aaa0.bbb.ccc | cut -d'.' -f1

Querying data by joining two tables in two database on different servers

You'll need to use sp_addlinkedserver to create a server link. See the reference documentation for usage. Once the server link is established, you'll construct the query as normal, just prefixing the database name with the other server. I.E:

-- FROM DB1
SELECT *
FROM [MyDatabaseOnDB1].[dbo].[MyTable] tab1
    INNER JOIN [DB2].[MyDatabaseOnDB2].[dbo].[MyOtherTable] tab2
        ON tab1.ID = tab2.ID

Once the link is established, you can also use OPENQUERY to execute a SQL statement on the remote server and transfer only the data back to you. This can be a bit faster, and it will let the remote server optimize your query. If you cache the data in a temporary (or in-memory) table on DB1 in the example above, then you'll be able to query it just like joining a standard table. For example:

-- Fetch data from the other database server
SELECT *
INTO #myTempTable
FROM OPENQUERY([DB2], 'SELECT * FROM [MyDatabaseOnDB2].[dbo].[MyOtherTable]')

-- Now I can join my temp table to see the data
SELECT * FROM [MyDatabaseOnDB1].[dbo].[MyTable] tab1
    INNER JOIN #myTempTable tab2 ON tab1.ID = tab2.ID

Check out the documentation for OPENQUERY to see some more examples. The example above is pretty contrived. I would definitely use the first method in this specific example, but the second option using OPENQUERY can save some time and performance if you use the query to filter out some data.

How to find out line-endings in a text file?

Ubuntu 14.04:

simple cat -e <filename> works just fine.

This displays Unix line endings (\n or LF) as $ and Windows line endings (\r\n or CRLF) as ^M$.

The difference between sys.stdout.write and print?

My question is whether or not there are situations in which sys.stdout.write() is preferable to print

After finishing developing a script the other day, I uploaded it to a unix server. All my debug messages used print statements, and these do not appear on a server log.

This is a case where you may need sys.stdout.write instead.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

I had a different issue that brought me to this question, which will probably be more common than the overrelease issue in the accepted answer.

Root cause was our completion block being called twice due to bad if/else fallthrough in the network handler, leading to two calls of dispatch_group_leave for every one call to dispatch_group_enter.

Completion block called multiple times:

dispatch_group_enter(group);
[self badMethodThatCallsMULTIPLECompletions:^(NSString *completion) {

    // this block is called multiple times
    // one `enter` but multiple `leave`

    dispatch_group_leave(group);
}];

Debug via the dispatch_group's count

Upon the EXC_BAD_INSTRUCTION, you should still have access to your dispatch_group in the debugger. DispatchGroup: check how many "entered"

Print out the dispatch_group and you'll see:

<OS_dispatch_group: group[0x60800008bf40] = { xrefcnt = 0x2, refcnt = 0x1, port = 0x0, count = -1, waiters = 0 }>

When you see count = -1 it indicates that you've over-left the dispatch_group. Be sure to dispatch_enter and dispatch_leave the group in matched pairs.

Get exit code for command in bash/ksh

There are several things wrong with your script.

Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).

It's good practice to surround your variable references with curly braces, too. Your code might look like:

#!/bin/sh
command="/bin/date -u"          #...Example Only

safeRunCommand() {
   cmnd="$@"                    #...insure whitespace passed and preserved
   $cmnd
   ERROR_CODE=$?                #...so we have it for the command we want
   if [ ${ERROR_CODE} != 0 ]; then
      printf "Error when executing command: '${command}'\n"
      exit ${ERROR_CODE}        #...consider 'return()' here
   fi
}

safeRunCommand $command
command="cp"
safeRunCommand $command

how to rotate a bitmap 90 degrees

By default the rotation point is the Canvas's (0,0) point, and my guess is that you may want to rotate it around the center. I did that:

protected void renderImage(Canvas canvas)
{
    Rect dest,drawRect ;

    drawRect = new Rect(0,0, mImage.getWidth(), mImage.getHeight());
    dest = new Rect((int) (canvas.getWidth() / 2 - mImage.getWidth() * mImageResize / 2), // left
                    (int) (canvas.getHeight()/ 2 - mImage.getHeight()* mImageResize / 2), // top
                    (int) (canvas.getWidth() / 2 + mImage.getWidth() * mImageResize / 2), //right
                    (int) (canvas.getWidth() / 2 + mImage.getHeight()* mImageResize / 2));// bottom

    if(!mRotate) {
        canvas.drawBitmap(mImage, drawRect, dest, null);
    } else {
        canvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
        canvas.rotate(90,canvas.getWidth() / 2, canvas.getHeight()/ 2);
        canvas.drawBitmap(mImage, drawRect, dest, null);
        canvas.restore();
    }
}

How do I find a list of Homebrew's installable packages?

From the man page:

search, -S text|/text/
Perform a substring search of formula names for text. If text is surrounded with slashes,
then it is interpreted as a regular expression. If no search term is given,
all available formula are displayed.

For your purposes, brew search will suffice.

UIView Hide/Show with animation

Tried some of the exited answers, some only work for one situation, some of them need to add two functions.

Option 1

Nothing to do with view.isHidden.

extension UIView {
    func animate(fadeIn: Bool, withDuration: TimeInterval = 1.0) {
        UIView.animate(withDuration: withDuration, delay: 0.0, options: .curveEaseInOut, animations: {
            self.alpha = fadeIn ? 1.0 : 0.0
        })
    }
}

Then pass isFadeIn (true or false)

view.animate(fadeIn: isFadeIn) 

Option 2

Don't pass any parameter. It fades in or out according to isUserInteractionEnabled. This also suits the situation animate back and forth very well.

func animateFadeInOut(withDuration: TimeInterval = 1.0) {
    self.isUserInteractionEnabled = !self.isUserInteractionEnabled
    UIView.animate(withDuration: withDuration, delay: 0.0, options: .curveEaseInOut, animations: {
        self.alpha = self.isUserInteractionEnabled ? 1.0 : 0.0
    })
}

Then you call

yourView.animateFadeInOut()

Why self.isUserInteractionEnabled ?

Tried to replace self.isUserInteractionEnabled by self.isHidden, no luck at all.

That's it. Cost me sometime, hope it helps someone.

Dart SDK is not configured

Run this command:

$ echo "$(dirname $(which flutter))/cache/dart-sdk"

You'll get something like:

/home/lex/opt/flutter/bin/cache/dart-sdk

Enter that value as your Dart SDK path.

Can CSS detect the number of children an element has?

Clarification:

Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.


Original answer:

Incredibly, this is now possible purely in CSS3.

/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
    width: 100%;
}

/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
    width: 50%;
}

/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}

/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
    width: 25%;
}

The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.

Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).

Don't you just love CSS3?

CodePen Example:

Sources:

How to get the containing form of an input?

function doSomething(element) {
  var form = element.form;
}

and in the html, you need to find that element, and add the attribut "form" to connect to that form, please refer to http://www.w3schools.com/tags/att_input_form.asp but this form attr doesn't support IE, for ie, you need to pass form id directly.

Invoking modal window in AngularJS Bootstrap UI using JavaScript

To make angular ui $modal work with bootstrap 3 you need to overwrite the styles

.modal {
    display: block;
}
.modal-body:before,
.modal-body:after {
    display: table;
    content: " ";
}
.modal-header:before,
.modal-header:after {
    display: table;
    content: " ";
}

(The last ones are necessary if you use custom directives) and encapsulate the html with

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      <h4 class="modal-title">Modal title</h4>
    </div>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
  </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

Error 'tunneling socket' while executing npm install

npm config set registry http://registry.npmjs.org/

above code solved my issue :)

How to use log4net in Asp.net core 2.0

Following on Irfan's answer, I have the following XML configuration on OSX with .NET Core 2.1.300 which correctly logs and appends to a ./log folder and also to the console. Note the log4net.config must exist in the solution root (whereas in my case, my app root is a subfolder).

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %-5level %logger - %message%newline" />
      </layout>
  </appender>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="logs/" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingLogFileAppender"/>
      <appender-ref ref="ConsoleAppender"/>
    </root>
</log4net>

Another note, the traditional way of setting the XML up within app.config did not work:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net> ...

For some reason, the log4net node was not found when accessing the XMLDocument via log4netConfig["log4net"].

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you have multiples docker containers launched, use this

$ docker rm $(docker ps -aq)

It will remove all the current dockers listed in the "ps -aq" command.

Source : aaam on https://github.com/docker/docker/issues/12487

proper way to logout from a session in PHP

Session_unset(); only destroys the session variables. To end the session there is another function called session_destroy(); which also destroys the session .

update :

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that

PadLeft function in T-SQL

I needed this in a function on SQL server and adjusted Patrick's answer a bit.

declare @dossierId int = 123
declare @padded_id varchar(7)


set @padded_id = REPLACE(
              SPACE(7 - LEN(@dossierId)) + convert(varchar(7), @dossierId), 
              SPACE(1),  
              '0') 

SELECT @dossierId as '@dossierId'
      ,SPACE(LEN(@dossierId)) + convert(varchar(7)
      ,@dossierId) as withSpaces
      ,@padded_id as '@padded_id'

Flutter: how to make a TextField with HintText but no Underline?

            Container(
         height: 50,
          // margin: EdgeInsets.only(top: 20),
          decoration: BoxDecoration(
              color: Colors.tealAccent,
              borderRadius: BorderRadius.circular(32)),
          child: TextFormField(
            cursorColor: Colors.black,
            // keyboardType: TextInputType.,
            decoration: InputDecoration(
              hintStyle: TextStyle(fontSize: 17),
              hintText: 'Search your trips',
              suffixIcon: Icon(Icons.search),
              border: InputBorder.none,
              contentPadding: EdgeInsets.all(18),
            ),
          ),
        ),

Loading DLLs at runtime in C#

You need to create an instance of the type that expose the Output method:

static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var class1Type = DLL.GetType("DLL.Class1");

        //Now you can use reflection or dynamic to call the method. I will show you the dynamic way

        dynamic c = Activator.CreateInstance(class1Type);
        c.Output(@"Hello");

        Console.ReadLine();
     }

What is the equivalent of the C# 'var' keyword in Java?

There is none. Alas, you have to type out the full type name.

Edit: 7 years after being posted, type inference for local variables (with var) was added in Java 10.

Edit: 6 years after being posted, to collect some of the comments from below:

  • The reason C# has the var keyword is because it's possible to have Types that have no name in .NET. Eg:

    var myData = new { a = 1, b = "2" };
    

    In this case, it would be impossible to give a proper type to myData. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.

  • var is not the same as dynamic. variables are still 100% statically typed. This will not compile:

    var myString = "foo";
    myString = 3;
    
  • var is also useful when the type is obvious from context. For example:

    var currentUser = User.GetCurrent();
    

    I can say that in any code that I am responsible for, currentUser has a User or derived class in it. Obviously, if your implementation of User.GetCurrent return an int, then maybe this is a detriment to you.

  • This has nothing to do with var, but if you have weird inheritance hierarchies where you shadow methods with other methods (eg new public void DoAThing()), don't forget that non-virtual methods are affected by the Type they are cast as.

    I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:

    class Foo {
        public void Non() {}
        public virtual void Virt() {}
    }
    
    class Bar : Foo {
        public new void Non() {}
        public override void Virt() {}
    }
    
    class Baz {
        public static Foo GetFoo() {
            return new Bar();
        }
    }
    
    var foo = Baz.GetFoo();
    foo.Non();  // <- Foo.Non, not Bar.Non
    foo.Virt(); // <- Bar.Virt
    
    var bar = (Bar)foo;
    bar.Non();  // <- Bar.Non, not Foo.Non
    bar.Virt(); // <- Still Bar.Virt
    

    As indicated, virtual methods are not affected by this.

  • No, there is no non-clumsy way to initialize a var without an actual variable.

    var foo1 = "bar";        //good
    var foo2;                //bad, what type?
    var foo3 = null;         //bad, null doesn't have a type
    var foo4 = default(var); //what?
    var foo5 = (object)null; //legal, but go home, you're drunk
    

    In this case, just do it the old fashioned way:

    object foo6;
    

MySQL JOIN the most recent row only?

It's a good idea that logging actual data into "customer_data" table. With this data you can select all data from "customer_data" table as you wish.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

jQuery event handlers always execute in order they were bound - any way around this?

Here's a solution for jQuery 1.4.x (unfortunately, the accepted answer didn't work for jquery 1.4.1)

$.fn.bindFirst = function(name, fn) {
    // bind as you normally would
    // don't want to miss out on any jQuery magic
    this.bind(name, fn);

    // Thanks to a comment by @Martin, adding support for
    // namespaced events too.
    var handlers = this.data('events')[name.split('.')[0]];
    // take out the handler we just inserted from the end
    var copy = {1: null};

    var last = 0, lastValue = null;
    $.each(handlers, function(name, value) {
        //console.log(name + ": " + value);
        var isNumber = !isNaN(name);
        if(isNumber) {last = name; lastValue = value;};

        var key = isNumber ? (parseInt(name) + 1) : name;
        copy[key] = value;
    });
    copy[1] = lastValue;
    this.data('events')[name.split('.')[0]] = copy;
};

Does static constexpr variable inside a function make sense?

The short answer is that not only is static useful, it is pretty well always going to be desired.

First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

Every variable declared constexpr is implicitly const but const and static are almost orthogonal (except for the interaction with static const integers.)

The C++ object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if principle provided it can prove that no other such object can be observed.

That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr) array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.

On the other hand, a local static const object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.

So you should definitely use static constexpr in your example.

However, there is one case where you wouldn't want to use static constexpr. Unless a constexpr declared object is either ODR-used or declared static, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static, since static is likely to force the object to exist at runtime.

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

My case is related to Greg B's -- Visual Studio creates two sites when SSL is enabled -- one for secure, and one for normal http requests. However Visual Studio chooses two ports at random, and depending on how you start the debugger you might be pointing towards the wrong page for the request type. Especially if you edit the URL but don't change the port number.

Seeing these posts jogged my memory.

I know this isn't APACHE related, but it is definitely a page that people with that error will find..

Sprintf equivalent in Java

Since Java 13 you have formatted 1 method on String, which was added along with text blocks as a preview feature 2. You can use it instead of String.format()

Assertions.assertEquals(
   "%s %d %.3f".formatted("foo", 123, 7.89),
   "foo 123 7.890"
);

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

http://localhost/ not working on Windows 7. What's the problem?

Try adding the following tags in the wwwroot folder web.config file. These tags should be added as a child of the configuration tags as below.

-configuration-
--system.webServer--
---validation validateIntegratedModeConfiguration="false" ---
--/system.webServer--
-/configuration-

how to sort an ArrayList in ascending order using Collections and Comparator

Here a complete example :

Suppose we have a Person class like :

public class Person
{
    protected String fname;
    protected String lname;

    public Person()
    {

    }

    public Person(String fname, String lname)
    {
        this.fname = fname;
        this.lname = lname;
    }

    public boolean equals(Object objet)
    {
        if(objet instanceof Person)
        {
            Person p = (Person) objet;
            return (p.getFname().equals(this.fname)) && p.getLname().equals(this.lname));
        }
        else return super.equals(objet);
    }

    @Override
    public String toString()
    {
        return "Person(fname : " + getFname + ", lname : " + getLname + ")";
    }

    /** Getters and Setters **/
}

Now we create a comparator :

import java.util.Comparator;

public class ComparePerson implements Comparator<Person>
{
    @Override
    public int compare(Person p1, Person p2)
    {
        if(p1.getFname().equalsIgnoreCase(p2.getFname()))
        {
            return p1.getLname().compareTo(p2.getLname());
        }
        return p1.getFname().compareTo(p2.getFname());
    }
}

Finally suppose we have a group of persons :

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Group
{
    protected List<Person> listPersons;

    public Group()
    {
        this.listPersons = new ArrayList<Person>();
    }

    public Group(List<Person> listPersons)
    {
        this.listPersons = listPersons;
    }

    public void order(boolean asc)
    {
        Comparator<Person> comp = asc ? new ComparePerson() : Collections.reverseOrder(new ComparePerson());
        Collections.sort(this.listPersons, comp);
    }

    public void display()
    {
        for(Person p : this.listPersons)
        {
            System.out.println(p);
        }
    }

    /** Getters and Setters **/
}

Now we try this :

import java.util.ArrayList;
import java.util.List;

public class App
{
    public static void main(String[] args)
    {
        Group g = new Group();
        List listPersons = new ArrayList<Person>();
        g.setListPersons(listPersons);

        Person p;

        p = new Person("A", "B");
        listPersons.add(p);

        p = new Person("C", "D");
        listPersons.add(p);

        /** you can add Person as many as you want **/

        g.display();

        g.order(true);
        g.display();

        g.order(false);
        g.display();
    }
}

What Vim command(s) can be used to quote/unquote words?

I wrote a script that does this:

function! WrapSelect (front)
    "puts characters around the selected text.
    let l:front = a:front
    if (a:front == '[')
        let l:back = ']'
    elseif (a:front == '(')
        let l:back = ')'
    elseif (a:front == '{')
        let l:back = '}'
    elseif (a:front == '<')
        let l:back = '>'
    elseif (a:front =~ " ")
        let l:split = split(a:front)
        let l:back = l:split[1]
        let l:front = l:split[0]
    else
        let l:back = a:front
    endif
    "execute: concat all these strings. '.' means "concat without spaces"
    "norm means "run in normal mode and also be able to use \<C-x> characters"
    "gv means "get the previous visual selection back up"
    "c means "cut visual selection and go to insert mode"
    "\<C-R> means "insert the contents of a register. in this case, the
    "default register"
    execute 'norm! gvc' . l:front. "\<C-R>\""  . l:back
endfunction
vnoremap <C-l> :<C-u>call WrapSelect(input('Wrapping? Give both (space separated) or just the first one: '))<cr>

To use, just highlight something, hit control l, and then type a character. If it's one of the characters the function knows about, it'll provide the correct terminating character. If it's not, it'll use the same character to insert on both sides.

Surround.vim can do more than just this, but this was sufficient for my needs.

Using Composer's Autoload

The composer documentation states that:

After adding the autoload field, you have to re-run install to re-generate the vendor/autoload.php file.

Assuming your "src" dir resides at the same level as "vendor" dir:

  • src
    • AppName
  • vendor
  • composer.json

the following config is absolutely correct:

{
    "autoload": {
        "psr-0": {"AppName": "src/"}
    }
}

but you must re-update/install dependencies to make it work for you, i.e. run:

php composer.phar update

This command will get the latest versions of the dependencies and update the file "vendor/composer/autoload_namespaces.php" to match your configuration.

Also as noted by @Dom, you can use composer dump-autoload to update the autoloader without having to go through an update.

How do I set a value in CKEditor with Javascript?

I have used the below code and it is working fine as describing->

CKEDITOR.instances.mail_msg.insertText(obj["template"]);

Here-> CKEDITOR ->Your editor Name, mail_msg -> Id of your textarea(to which u bind the ckeditor), obj["template"]->is the value that u want to bind

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

Let me solve it for ya.

  • Get into the sql.
  • Enter the following thing.
SET GLOBAL validate_password.length = 4;
SET GLOBAL validate_password.mixed_case_count = 0;
SET GLOBAL validate_password.number_count = 0;
SET GLOBAL validate_password.policy = LOW;
SET GLOBAL validate_password.special_char_count = 0;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'test';

Only for testing purposes.

How to use "/" (directory separator) in both Linux and Windows in Python?

Use:

import os
print os.sep

to see how separator looks on a current OS.
In your code you can use:

import os
path = os.path.join('folder_name', 'file_name')

How to clear exisiting dropdownlist items when its content changes?

just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:

Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) //ddl2.Items.Clear()

ddl2.DataSource=New List(Of String)()
ddl2.DataSource = sql2
ddl2.DataBind() End Sub

and it worked just fine

How do I wait until Task is finished in C#?

Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below

private static string Send(int id)
{
    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
    string result = string.Empty;
    Task continuation = responseTask.ContinueWith(x => result = Print(x));
    continuation.Wait();
    return result;
}

private static string Print(Task<HttpResponseMessage> httpTask)
{
    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
    string result = string.Empty;
    Task continuation = task.ContinueWith(t =>
    {
        Console.WriteLine("Result: " + t.Result);
        result = t.Result;
    });
    continuation.Wait();  
    return result;
}

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

No, POST/GET values are never null. The best they can be is an empty string, which you can convert to null/'NULL'.

if ($_POST['value'] === '') {
    $_POST['value'] = null; // or 'NULL' for SQL
}

How can I make a ComboBox non-editable in .NET?

To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this:

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

Link to the documentation for the ComboBox DropDownStyle property on MSDN.

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

Sending arrays with Intent.putExtra

final static String EXTRA_MESSAGE = "edit.list.message";

Context context;
public void onClick (View view)
{   
    Intent intent = new Intent(this,display.class);
    RelativeLayout relativeLayout = (RelativeLayout) view.getParent();

    TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
    String message = textView.getText().toString();

    intent.putExtra(EXTRA_MESSAGE,message);
    startActivity(intent);
}

Inserting created_at data with Laravel

You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:

protected $fillable = ['name', 'created_at']; 

Getting value of selected item in list box as string

Elaborating on previous answer by Pir Fahim, he's right but i'm using selectedItem.Text (only way to make it work to me)

Use the SelectedIndexChanged() event to store the data somewhere. In my case, i usually fill a custom class, something like:

class myItem {
    string name {get; set;}
    string price {get; set;}
    string desc {get; set;}
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     myItem selected_item = new myItem();
     selected_item.name  = listBox1.SelectedItem.Text;
     Retrieve (selected_item.name);
}

And then you can retrieve the rest of data from a List of "myItems"..

myItem Retrieve (string wanted_item) {
    foreach (myItem item in my_items_list) {
        if (item.name == wanted_item) {
               // This is the selected item
               return item; 
        }
    }
    return null;
}

SQL Current month/ year question

In SQL Server you can use YEAR, MONTH and DAY instead of DATEPART.
(at least in SQL Server 2005/2008, I'm not sure about SQL Server 2000 and older)

I prefer using these "short forms" because to me, YEAR(getdate()) is shorter to type and better to read than DATEPART(yyyy, getdate()).

So you could also query your table like this:

select *
from your_table
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())

JavaScript check if value is only undefined, null or false

Well, you can always "give up" :)

function b(val){
    return (val==null || val===false);
}

How to align footer (div) to the bottom of the page?

UPDATE

My original answer is from a long time ago, and the links are broken; updating it so that it continues to be useful.

I'm including updated solutions inline, as well as a working examples on JSFiddle. Note: I'm relying on a CSS reset, though I'm not including those styles inline. Refer to normalize.css

Solution 1 - margin offset

https://jsfiddle.net/UnsungHero97/ur20fndv/2/

HTML

<div id="wrapper">
  <div id="content">
    <h1>Hello, World!</h1>
  </div>
</div>
<footer id="footer">
  <div id="footer-content">Sticky Footer</div>
</footer>

CSS

html, body {
  margin: 0px;
  padding: 0px;
  min-height: 100%;
  height: 100%;
}

#wrapper {
  background-color: #e3f2fd;
  min-height: 100%;
  height: auto !important;
  margin-bottom: -50px; /* the bottom margin is the negative value of the footer's total height */
}

#wrapper:after {
  content: "";
  display: block;
  height: 50px; /* the footer's total height */
}

#content {
  height: 100%;
}

#footer {
  height: 50px; /* the footer's total height */
}

#footer-content {
  background-color: #f3e5f5;
  border: 1px solid #ab47bc;
  height: 32px; /* height + top/bottom paddding + top/bottom border must add up to footer height */
  padding: 8px;
}

Solution 2 - flexbox

https://jsfiddle.net/UnsungHero97/oqom5e5m/3/

HTML

<div id="content">
  <h1>Hello, World!</h1>
</div>
<footer id="footer">Sticky Footer</footer>

CSS

html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  min-height: 100%;
}

#content {
  background-color: #e3f2fd;
  flex: 1;
  padding: 20px;
}

#footer {
  background-color: #f3e5f5;
  padding: 20px;
}

Here's some links with more detailed explanations and different approaches:


ORIGINAL ANSWER

Is this what you mean?

http://ryanfait.com/sticky-footer/

This method uses only 15 lines of CSS and hardly any HTML markup. Even better, it's completely valid CSS, and it works in all major browsers. Internet Explorer 5 and up, Firefox, Safari, Opera and more.

This footer will stay at the bottom of the page permanently. This means that if the content is more than the height of the browser window, you will need to scroll down to see the footer... but if the content is less than the height of the browser window, the footer will stick to the bottom of the browser window instead of floating up in the middle of the page.

Let me know if you need help with the implementation. I hope this helps.

SQL Server Pivot Table with multiple column aggregates

I would do this slightly different by applying both the UNPIVOT and the PIVOT functions to get the final result. The unpivot takes the values from both the totalcount and totalamount columns and places them into one column with multiple rows. You can then pivot on those results.:

select chardate,
  Australia_totalcount as [Australia # of Transactions], 
  Australia_totalamount as [Australia Total $ Amount],
  Austria_totalcount as [Austria # of Transactions], 
  Austria_totalamount as [Austria Total $ Amount]
from
(
  select 
    numericmonth, 
    chardate,
    country +'_'+col col, 
    value
  from
  (
    select numericmonth, 
      country, 
      chardate,
      cast(totalcount as numeric(10, 2)) totalcount,
      cast(totalamount as numeric(10, 2)) totalamount
    from mytransactions
  ) src
  unpivot
  (
    value
    for col in (totalcount, totalamount)
  ) unpiv
) s
pivot
(
  sum(value)
  for col in (Australia_totalcount, Australia_totalamount,
              Austria_totalcount, Austria_totalamount)
) piv
order by numericmonth

See SQL Fiddle with Demo.

If you have an unknown number of country names, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @colsName AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(country +'_'+c.col) 
                      from mytransactions
                      cross apply 
                      (
                        select 'TotalCount' col
                        union all
                        select 'TotalAmount'
                      ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsName 
    = STUFF((SELECT distinct ', ' + QUOTENAME(country +'_'+c.col) 
               +' as ['
               + country + case when c.col = 'TotalCount' then ' # of Transactions]' else 'Total $ Amount]' end
             from mytransactions
             cross apply 
             (
                select 'TotalCount' col
                union all
                select 'TotalAmount'
             ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query 
  = 'SELECT chardate, ' + @colsName + ' 
     from 
     (
      select 
        numericmonth, 
        chardate,
        country +''_''+col col, 
        value
      from
      (
        select numericmonth, 
          country, 
          chardate,
          cast(totalcount as numeric(10, 2)) totalcount,
          cast(totalamount as numeric(10, 2)) totalamount
        from mytransactions
      ) src
      unpivot
      (
        value
        for col in (totalcount, totalamount)
      ) unpiv
     ) s
     pivot 
     (
       sum(value)
       for col in (' + @cols + ')
     ) p 
     order by numericmonth'

execute(@query)

See SQL Fiddle with Demo

Both give the result:

|             CHARDATE | AUSTRALIA # OF TRANSACTIONS | AUSTRALIA TOTAL $ AMOUNT | AUSTRIA # OF TRANSACTIONS | AUSTRIA TOTAL $ AMOUNT |
--------------------------------------------------------------------------------------------------------------------------------------
| Jul-12               |                          36 |                   699.96 |                        11 |                 257.82 |
| Aug-12               |                          44 |                  1368.71 |                         5 |                 126.55 |
| Sep-12               |                          52 |                  1161.33 |                         7 |                  92.11 |
| Oct-12               |                          50 |                  1099.84 |                        12 |                 103.56 |
| Nov-12               |                          38 |                  1078.94 |                        21 |                 377.68 |
| Dec-12               |                          63 |                  1668.23 |                         3 |                  14.35 |

How do I accomplish an if/else in mustache.js?

This is something you solve in the "controller", which is the point of logicless templating.

// some function that retreived data through ajax
function( view ){

   if ( !view.avatar ) {
      // DEFAULTS can be a global settings object you define elsewhere
      // so that you don't have to maintain these values all over the place
      // in your code.
      view.avatar = DEFAULTS.AVATAR;
   }

   // do template stuff here

}

This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)

Another option is to do the following:

// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;

And in the template:

{{#hasAvatar}}
    SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
    SHOW DEFAULT
{{/noAvatar}}

But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)

How to generate a number of most distinctive colors in R?

You can use colorRampPalette from base or RColorBrewer package:

With colorRampPalette, you can specify colours as follows:

colorRampPalette(c("red", "green"))(5)
# [1] "#FF0000" "#BF3F00" "#7F7F00" "#3FBF00" "#00FF00"

You can alternatively provide hex codes as well:

colorRampPalette(c("#3794bf", "#FFFFFF", "#df8640"))(5)
# [1] "#3794BF" "#9BC9DF" "#FFFFFF" "#EFC29F" "#DF8640"
# Note that the mid color is the mid value...

With RColorBrewer you could use colors from pre-existing palettes:

require(RColorBrewer)
brewer.pal(9, "Set1")
# [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628" "#F781BF"
# [9] "#999999"

Look at RColorBrewer package for other available palettes. Hope this helps.

How can you undo the last git add?

At date git prompts:

  1. use "git rm --cached <file>..." to unstage if files were not in the repo. It unstages the files keeping them there.
  2. use "git reset HEAD <file>..." to unstage if the files were in the repo, and you are adding them as modified. It keeps the files as they are, and unstages them.

At my knowledge you cannot undo the git add -- but you can unstage a list of files as mentioned above.

How to use PHP OPCache?

Installation

OpCache is compiled by default on PHP5.5+. However it is disabled by default. In order to start using OpCache in PHP5.5+ you will first have to enable it. To do this you would have to do the following.

Add the following line to your php.ini:

zend_extension=/full/path/to/opcache.so (nix)
zend_extension=C:\path\to\php_opcache.dll (win)

Note that when the path contains spaces you should wrap it in quotes:

zend_extension="C:\Program Files\PHP5.5\ext\php_opcache.dll"

Also note that you will have to use the zend_extension directive instead of the "normal" extension directive because it affects the actual Zend engine (i.e. the thing that runs PHP).

Usage

Currently there are four functions which you can use:

opcache_get_configuration():

Returns an array containing the currently used configuration OpCache uses. This includes all ini settings as well as version information and blacklisted files.

var_dump(opcache_get_configuration());

opcache_get_status():

This will return an array with information about the current status of the cache. This information will include things like: the state the cache is in (enabled, restarting, full etc), the memory usage, hits, misses and some more useful information. It will also contain the cached scripts.

var_dump(opcache_get_status());

opcache_reset():

Resets the entire cache. Meaning all possible cached scripts will be parsed again on the next visit.

opcache_reset();

opcache_invalidate():

Invalidates a specific cached script. Meaning the script will be parsed again on the next visit.

opcache_invalidate('/path/to/script/to/invalidate.php', true);

Maintenance and reports

There are some GUI's created to help maintain OpCache and generate useful reports. These tools leverage the above functions.

OpCacheGUI

Disclaimer I am the author of this project

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • OpCache reset
  • Cached scripts overview
  • Cached scripts invalidation
  • Multilingual
  • Mobile device support
  • Shiny graphs

Screenshots:

status

cached-scripts

graphs

mobilr

URL: https://github.com/PeeHaa/OpCacheGUI

opcache-status

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • Cached scripts overview
  • Single file

Screenshot:

status

URL: https://github.com/rlerdorf/opcache-status

opcache-gui

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • OpCache reset
  • Cached scripts overview
  • Cached scripts invalidation
  • Automatic refresh

Screenshot:

opcache-gui-overview

URL: https://github.com/amnuts/opcache-gui

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

parseDouble() method is used to initialise a STRING (which should contains some numerical value)....the value it returns is of primitive data type, like int, float, etc.

But valueOf() creates an object of Wrapper class. You have to unwrap it in order to get the double value. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.

Observe the following conversion.

int k = 100; Integer it1 = new Integer(k);

The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.

The following code can be used to unwrap (getting back int from Integer object) the object it1.

int m = it1.intValue();

System.out.println(m*m); // prints 10000

//intValue() is a method of Integer class that returns an int data type.

How to display a date as iso 8601 format with PHP

Using the DateTime class available in PHP version 5.2 it would be done like this:

$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');

See it in action

As of PHP 5.4 you can do this as a one-liner:

echo (new DateTime('17 Oct 2008'))->format('c');

What exactly is Python's file.flush() doing?

Because the operating system may not do so. The flush operation forces the file data into the file cache in RAM, and from there it's the OS's job to actually send it to the disk.

Select all text inside EditText when it gets focus

EditText dummy = ... 

// android.view.View.OnFocusChangeListener
dummy.setOnFocusChangeListener(new OnFocusChangeListener(){
    public void onFocusChange(View v, boolean hasFocus){
        if (hasFocus) && (isDummyText())
            ((EditText)v).selectAll();
    }
});

super() in Java

For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:

public class DeveloperSteps extends ScenarioSteps {

public DeveloperSteps(Pages pages) {
    super(pages);
}........

Get Selected value from Multi-Value Select Boxes by jquery-select2?

I know its late but I think you can try like this

$("#multipledpdwn").on("select2:select select2:unselect", function (e) {

    //this returns all the selected item
    var items= $(this).val();       

    //Gets the last selected item
    var lastSelectedItem = e.params.data.id;

})

Hope it may help some one in future.

C# get and set properties for a List Collection

Or

public class Section
{
  public String Head { get; set; }
  private readonly List<string> _subHead = new List<string>();
  private readonly List<string> _content = new List<string>();

  public IEnumerable<string> SubHead { get { return _subHead; } }
  public IEnumerable<string> Content { get { return _content; } }

  public void AddContent(String argValue)
  {
    _content.Add(argValue);
  }

  public void AddSubHeader(String argValue)
  {
    _subHead.Add(argValue);
  }
}

All depends on how much of the implementaton of content and subhead you want to hide.

Split string with delimiters in C

I think the following solution is ideal:

  • Doesn't destroy the source string
  • Re-entrant - i.e., you can safely call it from anywhere in one or more threads
  • Portable
  • Handles multiple separators correctly
  • Fast and efficient

Explanation of the code:

  1. Define a structure token to store the address and lengths of the tokens
  2. Allocate enough memory for these in the worst case, which is when str is made up entirely of separators so there are strlen(str) + 1 tokens, all of them empty strings
  3. Scan str recording the address and length of every token
  4. Use this to allocate the output array of the correct size, including an extra space for a NULL sentinel value
  5. Allocate, copy, and add the tokens using the start and length information - use memcpy as it's faster than strcpy and we know the lengths
  6. Free the token address and length array
  7. Return the array of tokens
typedef struct {
    const char *start;
    size_t len;
} token;

char **split(const char *str, char sep)
{
    char **array;
    unsigned int start = 0, stop, toks = 0, t;
    token *tokens = malloc((strlen(str) + 1) * sizeof(token));
    for (stop = 0; str[stop]; stop++) {
        if (str[stop] == sep) {
            tokens[toks].start = str + start;
            tokens[toks].len = stop - start;
            toks++;
            start = stop + 1;
        }
    }
    /* Mop up the last token */
    tokens[toks].start = str + start;
    tokens[toks].len = stop - start;
    toks++;
    array = malloc((toks + 1) * sizeof(char*));
    for (t = 0; t < toks; t++) {
        /* Calloc makes it nul-terminated */
        char *token = calloc(tokens[t].len + 1, 1);
        memcpy(token, tokens[t].start, tokens[t].len);
        array[t] = token;
    }
    /* Add a sentinel */
    array[t] = NULL; 
    free(tokens);
    return array;
}

Note malloc checking omitted for brevity.

In general, I wouldn't return an array of char * pointers from a split function like this as it places a lot of responsibility on the caller to free them correctly. An interface I prefer is to allow the caller to pass a callback function and call this for every token, as I have described here: Split a String in C.

Get file name from URL

I have the same problem, with yours. I solved it by this:

var URL = window.location.pathname; // Gets page name
var page = URL.substring(URL.lastIndexOf('/') + 1); 
console.info(page)

Javascript reduce on array of objects

You can use reduce method as bellow; If you change the 0(zero) to 1 or other numbers, it will add it to total number. For example, this example gives the total number as 31 however if we change 0 to 1, total number will be 32.

const batteryBatches = [4, 5, 3, 4, 4, 6, 5];

let totalBatteries= batteryBatches.reduce((acc,val) => acc + val ,0)