Programs & Examples On #End of line

The end of a physical line

Remove end of line characters from Java string

Hey we can also use this regex solution.

String chomp = StringUtils.normalizeSpace(sentence.replaceAll("[\\r\\n]"," "));

How to convert Windows end of line in Unix end of line (CR/LF to LF)

sed cannot match \n because the trailing newline is removed before the line is put into the pattern space but can match \r, so you can convert \r\n (dos) to \n (unix) by removing \r

sed -i 's/\r//g' file

Warning: this will change the original file

However, you cannot change from unix EOL to dos or old mac (\r) by this. More readings here:

How can I replace a newline (\n) using sed?

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

Not able to change TextField Border Color

We have tried custom search box with the pasted snippet. This code will useful for all kind of TextFiled decoration in Flutter. Hope this snippet will helpful for others.

Container(
        margin: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
        child:  new Theme(
          data: new ThemeData(
           hintColor: Colors.white,
            primaryColor: Colors.white,
            primaryColorDark: Colors.white,
          ),
          child:Padding(
          padding: EdgeInsets.all(10.0),
          child: TextField(
            style: TextStyle(color: Colors.white),
            onChanged: (value) {
              filterSearchResults(value);
            },
            controller: editingController,
            decoration: InputDecoration(
                labelText: "Search",
                hintText: "Search",
                prefixIcon: Icon(Icons.search,color: Colors.white,),
                enabled: true,
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.white),
                    borderRadius: BorderRadius.all(Radius.circular(25.0))),
                border: OutlineInputBorder(
                    borderSide: const BorderSide(color: Colors.white, width: 0.0),
                    borderRadius: BorderRadius.all(Radius.circular(25.0)))),
          ),
        ),
        ),
      ),

Insert/Update/Delete with function in SQL Server

Yes, you can.

However, it requires SQL CLR with EXTERNAL_ACCESS or UNSAFE permission and specifying a connection string. This is obviously not recommended.

For example, using Eval SQL.NET (a SQL CLR which allow to add C# syntax in SQL)

CREATE FUNCTION [dbo].[fn_modify_table_state]
    (
      @conn VARCHAR(8000) ,
      @sql VARCHAR(8000)
    )
RETURNS INT
AS
    BEGIN
        RETURN SQLNET::New('
using(var connection = new SqlConnection(conn))
{
    connection.Open();

    using(var command = new SqlCommand(sql, connection))
    {
        return command.ExecuteNonQuery();
    }
}
').ValueString('conn', @conn).ValueString('sql', @sql).EvalReadAccessInt()

    END

    GO

DECLARE @conn VARCHAR(8000) = 'Data Source=XPS8700;Initial Catalog=SqlServerEval_Debug;Integrated Security=True'
DECLARE @sql VARCHAR(8000) = 'UPDATE [Table_1] SET Value = -1 WHERE Name = ''zzz'''

DECLARE @rowAffecteds INT =  dbo.fn_modify_table_state(@conn, @sql)

Documentation: Modify table state within a SQL Function

Disclaimer: I'm the owner of the project Eval SQL.NET

Iterating Through a Dictionary in Swift

You can also use values.makeIterator() to iterate over dict values, like this:

for sb in sbItems.values.makeIterator(){
  // do something with your sb item..
  print(sb)
}

You can also do the iteration like this, in a more swifty style:

sbItems.values.makeIterator().forEach{
  // $0 is your dict value..
  print($0) 
}

sbItems is dict of type [String : NSManagedObject]

Where can I find a list of escape characters required for my JSON ajax return type?

As explained in the section 9 of the official ECMA specification (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) in JSON, the following chars have to be escaped:

  • U+0022 (", the quotation mark)
  • U+005C (\, the backslash or reverse solidus)
  • U+0000 to U+001F (the ASCII control characters)

In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:

  • U+002F (/)
  • U+0027 (')
  • U+003C (<)
  • U+003E (>)
  • U+0026 (&)
  • U+0085 (Next Line)
  • U+2028 (Line Separator)
  • U+2029 (Paragraph Separator)

Some of the above characters can be escaped with the following short escape sequences defined in the standard:

  • \" represents the quotation mark character (U+0022).
  • \\ represents the reverse solidus character (U+005C).
  • \/ represents the solidus character (U+002F).
  • \b represents the backspace character (U+0008).
  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).
  • \r represents the carriage return character (U+000D).
  • \t represents the character tabulation character (U+0009).

The other characters which need to be escaped will use the \uXXXX notation, that is \u followed by the four hexadecimal digits that encode the code point.

The \uXXXX can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).

Illegal character in path at index 16

I got this error today and unlike all the above answers my error was due to a new reason.

In my Japanese translation strings.xml file, I had removed a required string.

Some how android mixed up all the other string and this caused an error.

The solution was to include all the strings from my normal, English strings.xml

Including those strings which weren't translated to Japanese.

Converting Go struct to JSON

You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    name string
}

func (u *User) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        Name     string `json:"name"`
    }{
        Name:     "customized" + u.name,
    })
}

func main() {
    user := &User{name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Lists in ConfigParser

json.loads & ast.literal_eval seems to be working but simple list within config is treating each character as byte so returning even square bracket....

meaning if config has fieldvalue = [1,2,3,4,5]

then config.read(*.cfg) config['fieldValue'][0] returning [ in place of 1

Java Look and Feel (L&F)

You can try L&F which i am developing - WebLaF
It combines three parts required for successful UI development:

  • Cross-platform re-stylable L&F for Swing applications
  • Large set of extended Swing components
  • Various utilities and managers

Binaries: https://github.com/mgarin/weblaf/releases
Source: https://github.com/mgarin/weblaf
Licenses: GPLv3 and Commercial

A few examples showing how some of WebLaF components look like: Some of WebLaF components

Main reason why i have started with a totally new L&F is that most of existing L&F lack flexibility - you cannot re-style them in most cases (you can only change a few colors and turn on/off some UI elements in best case) and/or there are only inconvenient ways to do that. Its even worse when it comes to custom/3rd party components styling - they doesn't look similar to other components styled by some specific L&F or even totally different - that makes your application look unprofessional and unpleasant.

My goal is to provide a fully customizable L&F with a pack of additional widely-known and useful components (for example: date chooser, tree table, dockable and document panes and lots of other) and additional helpful managers and utilities, which will reduce the amount of code required to quickly integrate WebLaF into your application and help creating awesome UIs using Swing.

How to export a mysql database using Command Prompt?

Go to command prompt at this path,

C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin>

Then give this command to export your database (no space after -p)

mysqldump -u[username] -p[userpassword] yourdatabase > [filepath]wantedsqlfile.sql

Trying to get property of non-object MySQLi result

Just thought I would expand on this a bit.

If you perform a MYSQLI SELECT query that returns 0 results, it returns FALSE.

However, if you get this error and you have written your own MYSQLI Query function, then you can also get this error if the query you are running is not a select but an update. An update query will return either TRUE or FALSE. So if you just assume that any non false result will have records returned, then you will trip up when you run an update or anything other than select.

The easiest solution, once you have checked that its not false, is to first check that the result of the query is an object.

    $sqlResult = $connection->query($sql);
    if (!$sqlResult)
    {
     ... 
    }
    else if (is_object($sqlResult))
    {
        $sqlRowCount = $sqlResult->num_rows;
    }
    else
    {
        $sqlRowCount = 0;
    }

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

This answer may have to be modified depending on what you were trying to achieve with position: fixed;. If all you want is two columns side by side then do the following:

http://jsfiddle.net/8weSA/1/

I floated both columns to the left.

Note: I added min-height to each column for illustrative purposes and I simplified your CSS.

_x000D_
_x000D_
body {_x000D_
  background-color: #444;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
  width: 1005px;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
#leftcolumn,_x000D_
#rightcolumn {_x000D_
  border: 1px solid white;_x000D_
  float: left;_x000D_
  min-height: 450px;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
#leftcolumn {_x000D_
  width: 250px;_x000D_
  background-color: #111;_x000D_
}_x000D_
_x000D_
#rightcolumn {_x000D_
  width: 750px;_x000D_
  background-color: #777;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="leftcolumn">_x000D_
    Left_x000D_
  </div>_x000D_
  <div id="rightcolumn">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you would like the left column to stay in place as you scroll do the following:

http://jsfiddle.net/8weSA/2/

Here we float the right column to the right while adding position: relative; to #wrapper and position: fixed; to #leftcolumn.

Note: I again used min-height for illustrative purposes and can be removed for your needs.

_x000D_
_x000D_
body {_x000D_
  background-color: #444;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
  width: 1005px;_x000D_
  margin: 0 auto;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
#leftcolumn,_x000D_
#rightcolumn {_x000D_
  border: 1px solid white;_x000D_
  min-height: 750px;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
#leftcolumn {_x000D_
  width: 250px;_x000D_
  background-color: #111;_x000D_
  min-height: 100px;_x000D_
  position: fixed;_x000D_
}_x000D_
_x000D_
#rightcolumn {_x000D_
  width: 750px;_x000D_
  background-color: #777;_x000D_
  float: right;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="leftcolumn">_x000D_
    Left_x000D_
  </div>_x000D_
  <div id="rightcolumn">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to remove special characters from a string?

That depends on what you define as special characters, but try replaceAll(...):

String result = yourString.replaceAll("[-+.^:,]","");

Note that the ^ character must not be the first one in the list, since you'd then either have to escape it or it would mean "any but these characters".

Another note: the - character needs to be the first or last one on the list, otherwise you'd have to escape it or it would define a range ( e.g. :-, would mean "all characters in the range : to ,).

So, in order to keep consistency and not depend on character positioning, you might want to escape all those characters that have a special meaning in regular expressions (the following list is not complete, so be aware of other characters like (, {, $ etc.):

String result = yourString.replaceAll("[\\-\\+\\.\\^:,]","");


If you want to get rid of all punctuation and symbols, try this regex: \p{P}\p{S} (keep in mind that in Java strings you'd have to escape back slashes: "\\p{P}\\p{S}").

A third way could be something like this, if you can exactly define what should be left in your string:

String  result = yourString.replaceAll("[^\\w\\s]","");

This means: replace everything that is not a word character (a-z in any case, 0-9 or _) or whitespace.

Edit: please note that there are a couple of other patterns that might prove helpful. However, I can't explain them all, so have a look at the reference section of regular-expressions.info.

Here's less restrictive alternative to the "define allowed characters" approach, as suggested by Ray:

String  result = yourString.replaceAll("[^\\p{L}\\p{Z}]","");

The regex matches everything that is not a letter in any language and not a separator (whitespace, linebreak etc.). Note that you can't use [\P{L}\P{Z}] (upper case P means not having that property), since that would mean "everything that is not a letter or not whitespace", which almost matches everything, since letters are not whitespace and vice versa.

Additional information on Unicode

Some unicode characters seem to cause problems due to different possible ways to encode them (as a single code point or a combination of code points). Please refer to regular-expressions.info for more information.

How to execute a shell script on a remote server using Ansible?

You can use template module to copy if script exists on local machine to remote machine and execute it.

 - name: Copy script from local to remote machine
   hosts: remote_machine
   tasks:
    - name: Copy  script to remote_machine
      template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
    - name: Execute script on remote_machine
      script: sh <remote_machine path>/script.sh

How to tell when UITableView has completed ReloadData?

Try this:

tableView.backgroundColor = .black

tableView.reloadData()

DispatchQueue.main.async(execute: {

    tableView.backgroundColor = .green

})

The tableView color will changed from black to green only after the reloadData() function completes.

mongo - couldn't connect to server 127.0.0.1:27017

I face same issue after searching a lot I solve this by following :

sudo service mongodb stop 

sudo rm /var/lib/mongodb/mongod.lock 

sudo mongod --repair --dbpath /var/lib/mongodb 

sudo mongod --fork --logpath /var/lib/mongodb/mongodb.log --dbpath /var/lib/mongodb 

sudo service mongodb start

Auto reloading python Flask app upon code changes

If you are talking about test/dev environments, then just use the debug option. It will auto-reload the flask app when a code change happens.

app.run(debug=True)

Or, from the shell:

$ export FLASK_DEBUG=1
$ flask run

http://flask.pocoo.org/docs/quickstart/#debug-mode

What is Hash and Range Primary Key?

As the whole thing is mixing up let's look at it function and code to simulate what it means consicely

The only way to get a row is via primary key

getRow(pk: PrimaryKey): Row

Primary key data structure can be this:

// If you decide your primary key is just the partition key.
class PrimaryKey(partitionKey: String)

// and in thids case
getRow(somePartitionKey): Row

However you can decide your primary key is partition key + sort key in this case:

// if you decide your primary key is partition key + sort key
class PrimaryKey(partitionKey: String, sortKey: String)

getRow(partitionKey, sortKey): Row
getMultipleRows(partitionKey): Row[]

So the bottom line:

  1. Decided that your primary key is partition key only? get single row by partition key.

  2. Decided that your primary key is partition key + sort key? 2.1 Get single row by (partition key, sort key) or get range of rows by (partition key)

In either way you get a single row by primary key the only question is if you defined that primary key to be partition key only or partition key + sort key

Building blocks are:

  1. Table
  2. Item
  3. KV Attribute.

Think of Item as a row and of KV Attribute as cells in that row.

  1. You can get an item (a row) by primary key.
  2. You can get multiple items (multiple rows) by specifying (HashKey, RangeKeyQuery)

You can do (2) only if you decided that your PK is composed of (HashKey, SortKey).

More visually as its complex, the way I see it:

+----------------------------------------------------------------------------------+
|Table                                                                             |
|+------------------------------------------------------------------------------+  |
||Item                                                                          |  |
||+-----------+ +-----------+ +-----------+ +-----------+                       |  |
|||primaryKey | |kv attr    | |kv attr ...| |kv attr ...|                       |  |
||+-----------+ +-----------+ +-----------+ +-----------+                       |  |
|+------------------------------------------------------------------------------+  |
|+------------------------------------------------------------------------------+  |
||Item                                                                          |  |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+         |  |
|||primaryKey | |kv attr    | |kv attr ...| |kv attr ...| |kv attr ...|         |  |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+         |  |
|+------------------------------------------------------------------------------+  |
|                                                                                  |
+----------------------------------------------------------------------------------+

+----------------------------------------------------------------------------------+
|1. Always get item by PrimaryKey                                                  |
|2. PK is (Hash,RangeKey), great get MULTIPLE Items by Hash, filter/sort by range     |
|3. PK is HashKey: just get a SINGLE ITEM by hashKey                               |
|                                                      +--------------------------+|
|                                 +---------------+    |getByPK => getBy(1        ||
|                 +-----------+ +>|(HashKey,Range)|--->|hashKey, > < or startWith ||
|              +->|Composite  |-+ +---------------+    |of rangeKeys)             ||
|              |  +-----------+                        +--------------------------+|
|+-----------+ |                                                                   |
||PrimaryKey |-+                                                                   |
|+-----------+ |                                       +--------------------------+|
|              |  +-----------+   +---------------+    |getByPK => get by specific||
|              +->|HashType   |-->|get one item   |--->|hashKey                   ||
|                 +-----------+   +---------------+    |                          ||
|                                                      +--------------------------+|
+----------------------------------------------------------------------------------+

So what is happening above. Notice the following observations. As we said our data belongs to (Table, Item, KVAttribute). Then Every Item has a primary key. Now the way you compose that primary key is meaningful into how you can access the data.

If you decide that your PrimaryKey is simply a hash key then great you can get a single item out of it. If you decide however that your primary key is hashKey + SortKey then you could also do a range query on your primary key because you will get your items by (HashKey + SomeRangeFunction(on range key)). So you can get multiple items with your primary key query.

Note: I did not refer to secondary indexes.

Is it possible to return empty in react render function?

Some answers are slightly incorrect and point to the wrong part of the docs:

If you want a component to render nothing, just return null, as per doc:

In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.

If you try to return undefined for example, you'll get the following error:

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

As pointed out by other answers, null, true, false and undefined are valid children which is useful for conditional rendering inside your jsx, but it you want your component to hide / render nothing, just return null.

What is the parameter "next" used for in Express?

Before understanding next, you need to have a little idea of Request-Response cycle in node though not much in detail. It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World’);

let’s have a look at a very simple example.

app.get('/hello', function (req, res, next) {
  res.send('USER')
})

Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.

Now let’s take a look at another example.

app.get('/hello', function (req, res, next) {
  res.send("Hello World !!!!");
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.

But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let’s modify the above code and see what happens.

app.get('/hello', function (req, res, next) {
  if(some condition){
    next();
    return;
  }
  res.send("Hello World !!!!");  
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

What’s the next doing here. And yes you might have gusses. It’s gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!" response.

So, next pass the control to the next function in the middleware stack.

What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.

Something like below:-

app.get('/hello', function (req, res, next) {
  // Your piece of logic
  next();
});

app.get('/hello', function (req, res, next) {
  res.send("Hello !!!!");
});

In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();

What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.

call javascript function on hyperlink click

Use the onclick HTML attribute.

The onclick event handler captures a click event from the users’ mouse button on the element to which the onclick attribute is applied. This action usually results in a call to a script method such as a JavaScript function [...]

Constructor in an Interface?

Dependencies that are not referenced in an interfaces methods should be regarded as implementation details, not something that the interface enforces. Of course there can be exceptions, but as a rule, you should define your interface as what the behavior is expected to be. Internal state of a given implementation shouldn't be a design concern of the interface.

Using the "animated circle" in an ImageView while loading stuff

If you would like to not inflate another view just to indicate progress then do the following:

  1. Create ProgressBar in the same XML layout of the list view.
  2. Make it centered
  3. Give it an id
  4. Attach it to your listview instance variable by calling setEmptyView

Android will take care the progress bar's visibility.

For example, in activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.fcchyd.linkletandroid.MainActivity">

    <ListView
        android:id="@+id/list_view_xml"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@color/colorDivider"
        android:dividerHeight="1dp" />

   <ProgressBar
        android:id="@+id/loading_progress_xml"
        style="?android:attr/progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

And in MainActivity.java:

package com.fcchyd.linkletandroid;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

final String debugLogHeader = "Linklet Debug Message";
Call<Links> call;
List<Link> arraylistLink;
ListView linksListV;

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

    linksListV = (ListView) findViewById(R.id.list_view_xml);
    linksListV.setEmptyView(findViewById(R.id.loading_progress_xml));
    arraylistLink = new ArrayList<>();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.links.linklet.ml")
            .addConverterFactory(GsonConverterFactory
                    .create())
            .build();

    HttpsInterface HttpsInterface = retrofit
            .create(HttpsInterface.class);

    call = HttpsInterface.httpGETpageNumber(1);

    call.enqueue(new Callback<Links>() {
        @Override
        public void onResponse(Call<Links> call, Response<Links> response) {
            try {
                arraylistLink = response.body().getLinks();

                String[] simpletTitlesArray = new String[arraylistLink.size()];
                for (int i = 0; i < simpletTitlesArray.length; i++) {
                    simpletTitlesArray[i] = arraylistLink.get(i).getTitle();
                }
                ArrayAdapter<String> simpleAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, simpletTitlesArray);
                linksListV.setAdapter(simpleAdapter);
            } catch (Exception e) {
                Log.e("erro", "" + e);
            }
        }

        @Override
        public void onFailure(Call<Links> call, Throwable t) {

        }
    });


}

}

Excel CSV - Number cell format

When opening a CSV, you get the text import wizard. At the last step of the wizard, you should be able to import the specific column as text, thereby retaining the '00' prefix. After that you can then format the cell any way that you want.

I tried with with Excel 2007 and it appeared to work.

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

One I was just working on involves picking two random points, and if they are in the wrong order, reversing the entire subrange between them. I found the algorithm on http://richardhartersworld.com/cri_d/cri/2001/badsort.html, which says that the average case is is probably somewhere around O(n^3) or O(n^2 log n) (he's not really sure).

I think it might be possible to do it more efficiently, because I think it might be possible to do the reversal operation in O(1) time.

Actually, I just realized that doing that would make the whole thing I say maybe because I just realized that the data structure I had in mind would put accessing the random elements at O(log n) and determining if it needs reversing at O(n).

Set HTML dropdown selected option using JSTL

Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

UPDATE (next question)

You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.

Because of the limitations of the expression language, I think the best way to deal with this is to use a map:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

And then in the JSP:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>

Open Google Chrome from VBA/Excel

You can use the following vba code and input them into standard module in excel. A list of websites can be entered and should be entered like this on cell A1 in Excel - www.stackoverflow.com

ActiveSheet.Cells(1,2).Value merely takes the number of website links that you have on cell B1 in Excel and will loop the code again and again based on number of website links you have placed on the sheet. Therefore Chrome will open up a new tab for each website link.

I hope this helps with the dynamic website you have got.

Sub multiplechrome()

    Dim WebUrl As String
    Dim i As Integer

    For i = 1 To ActiveSheet.Cells(1, 2).Value
        WebUrl = "http://" & Cells(i, 1).Value & """"
        Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)

    Next
End Sub

How do I load an url in iframe with Jquery

$("#frame").click(function () { 
    this.src="http://www.google.com/";
});

Sometimes plain JavaScript is even cooler and faster than jQuery ;-)

WPF binding to Listbox selectedItem

For me, I usually use DataContext together in order to bind two-depth property such as this question.

<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />

Or, I prefer to use ElementName because it achieves bindings only with view controls.

<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />

Permanently hide Navigation Bar in an activity

AFAIK, this is not possible without root access. It would be a security issue to be able to have an app that cannot be exited with system buttons.

Edit, see here: Hide System Bar in Tablets

How to programmatically set style attribute in a view

If you are using the Support library, you could simply use

TextViewCompat.setTextAppearance(textView, R.style.AppTheme_TextStyle_ButtonDefault_Whatever);

for TextViews and Buttons. There are similar classes for the rest of Views :-)

What is the meaning of the term "thread-safe"?

As others have pointed out, thread safety means that a piece of code will work without errors if it's used by more than one thread at once.

It's worth being aware that this sometimes comes at a cost, of computer time and more complex coding, so it isn't always desirable. If a class can be safely used on only one thread, it may be better to do so.

For example, Java has two classes that are almost equivalent, StringBuffer and StringBuilder. The difference is that StringBuffer is thread-safe, so a single instance of a StringBuffer may be used by multiple threads at once. StringBuilder is not thread-safe, and is designed as a higher-performance replacement for those cases (the vast majority) when the String is built by only one thread.

How do I pass JavaScript variables to PHP?

There are several ways of passing variables from JavaScript to PHP (not the current page, of course).

You could:

  1. Send the information in a form as stated here (will result in a page refresh)
  2. Pass it in Ajax (several posts are on here about that) (without a page refresh)
  3. Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:

 if (window.XMLHttpRequest){
     xmlhttp = new XMLHttpRequest();
 }

else{
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }

 var PageToSendTo = "nowitworks.php?";
 var MyVariable = "variableData";
 var VariablePlaceholder = "variableName=";
 var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;

 xmlhttp.open("GET", UrlToSend, false);
 xmlhttp.send();

I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.

How do I convert an interval into a number of hours with postgres?

         select date 'now()' - date '1955-12-15';

Here is the simple query which calculates total no of days.

missing FROM-clause entry for table

SELECT 
   AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit, 
   BillLimit, Mode, PNotes, gtab82.memno 
FROM
   VCustomer AS v1
INNER JOIN   
   gtab82 ON gtab82.memacid = v1.AcId 
WHERE (AcGrCode = '204' OR CreDebt = 'True') 
AND Masked = 'false'
ORDER BY AcName

You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer but only use it in the ON clause for uncertain reasons. You may want to review that aspect of your code.

For loop in Oracle SQL

You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.

With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.

http://www.dba-oracle.com/t_with_clause.htm

http://www.orafaq.com/node/55

It requires some effort though. Don't be afraid to post a concrete example.

Using simple pseudo table DUAL helps too.

Batch Script to Run as Administrator

@echo off

 call :isAdmin

 if %errorlevel% == 0 (
    goto :run
 ) else (
    echo Requesting administrative privileges...
    goto :UACPrompt
 )

 exit /b

 :isAdmin
    fsutil dirty query %systemdrive% >nul
 exit /b

 :run
  <YOUR BATCH SCRIPT HERE>
 exit /b

 :UACPrompt
   echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
   echo UAC.ShellExecute "cmd.exe", "/c %~s0 %~1", "", "runas", 1 >> "%temp%\getadmin.vbs"

   "%temp%\getadmin.vbs"
   del "%temp%\getadmin.vbs"
  exit /B`

Check if value is zero or not null in python

Zero and None both treated as same for if block, below code should work fine.

if number or number==0:
    return True

How can I convert a DOM element to a jQuery element?

So far best solution that I've made:

function convertHtmlToJQueryObject(html){
    var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
    return $(htmlDOMObject.documentElement);
}

How to test if parameters exist in rails

Simple as pie:

if !params[:one].nil? and !params[:two].nil?
  #do something...
elsif !params[:one].nil?
  #do something else...
elsif !params[:two].nil?
  #do something extraordinary...
end

MySQL root password change

This is the updated answer for WAMP v3.0.6 and up

> UPDATE mysql.user 
> SET authentication_string=PASSWORD('MyNewPass') 
> WHERE user='root';

> FLUSH PRIVILEGES;

In MySQL version 5.7.x there is no more password field in the mysql table. It was replaced with authentication_string. (This is for the terminal/CLI)

UPDATE mysql.user SET authentication_string=PASSWORD('MyNewPass') WHERE user='root';

FLUSH PRIVILEGES;

(This if for PHPMyAdmin or any Mysql GUI)

ASP.NET MVC on IIS 7.5

Yet another reason this can happen - your RouteConfig.cs or WebApiConfig.cs are invalid.

In my case, I had a route defined as such (note the parenthesis instead of curly brace):

...
routeTemplate: "api/(something}"
...

BigDecimal equals() versus compareTo()

I believe that the correct answer would be to make the two numbers (BigDecimals), have the same scale, then we can decide about their equality. For example, are these two numbers equal?

1.00001 and 1.00002

Well, it depends on the scale. On the scale 5 (5 decimal points), no they are not the same. but on smaller decimal precisions (scale 4 and lower) they are considered equal. So I suggest make the scale of the two numbers equal and then compare them.

AngularJS : Custom filters and ng-repeat

If you want to run some custom filter logic you can create a function which takes the array element as an argument and returns true or false based on whether it should be in the search results. Then pass it to the filter instruction just like you do with the search object, for example:

JS:

$scope.filterFn = function(car)
{
    // Do some tests

    if(car.carDetails.doors > 2)
    {
        return true; // this will be listed in the results
    }

    return false; // otherwise it won't be within the results
};

HTML:

...
<article data-ng-repeat="result in results | filter:search | filter:filterFn" class="result">
...

As you can see you can chain many filters together, so adding your custom filter function doesn't force you to remove the previous filter using the search object (they will work together seamlessly).

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

  1. Find file:

    [XAMPP Installation Directory]\php\php.ini
    
  2. open php.ini.
  3. Find max_execution_time and increase the value of it as you required
  4. Restart XAMPP control panel

How to query GROUP BY Month in a Year

I would be inclined to include the year in the output. One way:

select to_char(DATE_CREATED, 'YYYY-MM'), sum(Num_of_Pictures)
from pictures_table
group by to_char(DATE_CREATED, 'YYYY-MM')
order by 1

Another way (more standard SQL):

select extract(year from date_created) as yr, extract(month from date_created) as mon,
       sum(Num_of_Pictures)
from pictures_table
group by extract(year from date_created), extract(month from date_created)
order by yr, mon;

Remember the order by, since you presumably want these in order, and there is no guarantee about the order that rows are returned in after a group by.

Where can I download an offline installer of Cygwin?

may this post can solve your problem

see Full Installation Answer on that: What is the current full install size of Cygwin?

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

How to install latest version of Node using Brew

After installation/upgrading node via brew I ran into this issue exactly: the node command worked but not the npm command.

I used these commands to fix it.

brew uninstall node
brew update
brew upgrade
brew cleanup
brew install node
sudo chown -R $(whoami) /usr/local
brew link --overwrite node
brew postinstall node

I pieced together this solution after trial and error using...

XMLHttpRequest (Ajax) Error

So there might be a few things wrong here.

First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:

var oXHR = new XMLHttpRequest();

oXHR.open("GET", "http://www.mozilla.org/", true);

oXHR.onreadystatechange = function (oEvent) {
    if (oXHR.readyState === 4) {
        if (oXHR.status === 200) {
          console.log(oXHR.responseText)
        } else {
           console.log("Error", oXHR.statusText);
        }
    }
};

oXHR.send(null);

Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml file.

You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:

var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false); 
request.send(null);

if (request.status == 0)
    console.log(request.responseText);

Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.

Jquery checking success of ajax post

using jQuery 1.8 and above, should use the following:

var request = $.ajax({
    type: 'POST',
    url: 'mmm.php',
    data: { abc: "abcdefghijklmnopqrstuvwxyz" } })
    .done(function(data) { alert("success"+data.slice(0, 100)); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });

check out the docs as @hitautodestruct stated.

How do I get rid of an element's offset using CSS?

That offset is basically the x,y position that the browser has calculated for the element based on it's position css attribute. So if you put a <br> before it or any other element, it would change the offset. For example, you could set it to 0 by:

#inputBox{position:absolute;top:0px;left:0px;}

or

#inputBox{position:relative;top:-12px;left:-2px;}

Therefore, whatever positioning issue you have, is not necessarily an issue with offset, though you could always fix it by playing with the top,left,right and bottom attributes.

Is your problem browser incompatibility?

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

Eclipse for PHP Developers Package

Looking for the Eclipse for PHP Developers Package?

Due to lack of a package maintainer for the Indigo release there will be no PHP (PDT) package. If you would like to install PDT into your Eclipse installtion you can do so by using the Install New Software feature from the Help Menu and installing the PHP Development Tools (PDT) SDK Feature from the Eclipse Indigo Repo >> http://download.eclipse.org/releases/indigo

Text grabbed from page: http://www.eclipse.org/downloads/php_package.php

How can I zoom an HTML element in Firefox and Opera?

Try this code, this’ll work:

-moz-transform: scale(2);

You can refer to this.

How to display UTF-8 characters in phpMyAdmin?

Add:

mysql_query("SET NAMES UTF8");

below:

mysql_select_db(/*your_database_name*/);

Static array vs. dynamic array in C++

Local arrays are created on the stack, and have automatic storage duration -- you don't need to manually manage memory, but they get destroyed when the function they're in ends. They necessarily have a fixed size:

int foo[10];

Arrays created with operator new[] have dynamic storage duration and are stored on the heap (technically the "free store"). They can have any size, but you need to allocate and free them yourself since they're not part of the stack frame:

int* foo = new int[10];
delete[] foo;

Convert RGB to Black & White in OpenCV

AFAIK, you have to convert it to grayscale and then threshold it to binary.

1. Read the image as a grayscale image If you're reading the RGB image from disk, then you can directly read it as a grayscale image, like this:

// C
IplImage* im_gray = cvLoadImage("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

// C++ (OpenCV 2.0)
Mat im_gray = imread("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

2. Convert an RGB image im_rgb into a grayscale image: Otherwise, you'll have to convert the previously obtained RGB image into a grayscale image

// C
IplImage *im_rgb  = cvLoadImage("image.jpg");
IplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);
cvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);

// C++
Mat im_rgb  = imread("image.jpg");
Mat im_gray;
cvtColor(im_rgb,im_gray,CV_RGB2GRAY);

3. Convert to binary You can use adaptive thresholding or fixed-level thresholding to convert your grayscale image to a binary image.

E.g. in C you can do the following (you can also do the same in C++ with Mat and the corresponding functions):

// C
IplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);
cvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

// C++
Mat img_bw = im_gray > 128;

In the above example, 128 is the threshold.

4. Save to disk

// C
cvSaveImage("image_bw.jpg",img_bw);

// C++
imwrite("image_bw.jpg", img_bw);

equivalent to push() or pop() for arrays?

For those who don't have time to refactor the code to replace arrays with Collections (for example ArrayList), there is an alternative. Unlike Collections, the length of an array cannot be changed, but the array can be replaced, like this:

array = push(array, item);

The drawbacks are that

  • the whole array has to be copied each time you push, and
  • the original array Object is not changed, so you have to update the variable(s) as appropriate.

Here is the push method for String:
(You can create multiple push methods, one for String, one for int, etc)

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    for (int i = 0; i < array.length; i++)
        longer[i] = array[i];
    longer[array.length] = push;
    return longer;
}

This alternative is more efficient, shorter & harder to read:

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    System.arraycopy(array, 0, longer, 0, array.length);
    longer[array.length] = push;
    return longer;
}

Where is git.exe located?

If you can use the git command it should be in your path? thus this should work asuming linux or linux like os

which git

else also asuming linux like os

cd /
find . -name "*git*"

if on windows tell me what version you are using and I'll help you. The default path on windows is C:\Program Files (x86)\Git.

The name of the executable is not git.exeon all systems.

Error Code: 1406. Data too long for column - MySQL

Go to your Models and check, because you might have truncated a number of words for that particular column eg. max_length="150".

How to make rounded percentages add up to 100%

I think the following will achieve what you are after

function func( orig, target ) {

    var i = orig.length, j = 0, total = 0, change, newVals = [], next, factor1, factor2, len = orig.length, marginOfErrors = [];

    // map original values to new array
    while( i-- ) {
        total += newVals[i] = Math.round( orig[i] );
    }

    change = total < target ? 1 : -1;

    while( total !== target ) {

        // Iterate through values and select the one that once changed will introduce
        // the least margin of error in terms of itself. e.g. Incrementing 10 by 1
        // would mean an error of 10% in relation to the value itself.
        for( i = 0; i < len; i++ ) {

            next = i === len - 1 ? 0 : i + 1;

            factor2 = errorFactor( orig[next], newVals[next] + change );
            factor1 = errorFactor( orig[i], newVals[i] + change );

            if(  factor1 > factor2 ) {
                j = next; 
            }
        }

        newVals[j] += change;
        total += change;
    }


    for( i = 0; i < len; i++ ) { marginOfErrors[i] = newVals[i] && Math.abs( orig[i] - newVals[i] ) / orig[i]; }

    // Math.round() causes some problems as it is difficult to know at the beginning
    // whether numbers should have been rounded up or down to reduce total margin of error. 
    // This section of code increments and decrements values by 1 to find the number
    // combination with least margin of error.
    for( i = 0; i < len; i++ ) {
        for( j = 0; j < len; j++ ) {
            if( j === i ) continue;

            var roundUpFactor = errorFactor( orig[i], newVals[i] + 1)  + errorFactor( orig[j], newVals[j] - 1 );
            var roundDownFactor = errorFactor( orig[i], newVals[i] - 1) + errorFactor( orig[j], newVals[j] + 1 );
            var sumMargin = marginOfErrors[i] + marginOfErrors[j];

            if( roundUpFactor < sumMargin) { 
                newVals[i] = newVals[i] + 1;
                newVals[j] = newVals[j] - 1;
                marginOfErrors[i] = newVals[i] && Math.abs( orig[i] - newVals[i] ) / orig[i];
                marginOfErrors[j] = newVals[j] && Math.abs( orig[j] - newVals[j] ) / orig[j];
            }

            if( roundDownFactor < sumMargin ) { 
                newVals[i] = newVals[i] - 1;
                newVals[j] = newVals[j] + 1;
                marginOfErrors[i] = newVals[i] && Math.abs( orig[i] - newVals[i] ) / orig[i];
                marginOfErrors[j] = newVals[j] && Math.abs( orig[j] - newVals[j] ) / orig[j];
            }

        }
    }

    function errorFactor( oldNum, newNum ) {
        return Math.abs( oldNum - newNum ) / oldNum;
    }

    return newVals;
}


func([16.666, 16.666, 16.666, 16.666, 16.666, 16.666], 100); // => [16, 16, 17, 17, 17, 17]
func([33.333, 33.333, 33.333], 100); // => [34, 33, 33]
func([33.3, 33.3, 33.3, 0.1], 100); // => [34, 33, 33, 0] 
func([13.25, 47.25, 11.25, 28.25], 100 ); // => [13, 48, 11, 28]
func( [25.5, 25.5, 25.5, 23.5], 100 ); // => [25, 25, 26, 24]

One last thing, I ran the function using the numbers originally given in the question to compare to the desired output

func([13.626332, 47.989636, 9.596008, 28.788024], 100); // => [48, 29, 13, 10]

This was different to what the question wanted => [ 48, 29, 14, 9]. I couldn't understand this until I looked at the total margin of error

-------------------------------------------------
| original  | question | % diff | mine | % diff |
-------------------------------------------------
| 13.626332 | 14       | 2.74%  | 13   | 4.5%   |
| 47.989636 | 48       | 0.02%  | 48   | 0.02%  |
| 9.596008  | 9        | 6.2%   | 10   | 4.2%   |
| 28.788024 | 29       | 0.7%   | 29   | 0.7%   |
-------------------------------------------------
| Totals    | 100      | 9.66%  | 100  | 9.43%  |
-------------------------------------------------

Essentially, the result from my function actually introduces the least amount of error.

Fiddle here

Using CRON jobs to visit url?

U can try this :-


    wget -q -O - http://www.example.com/ >/dev/null 2>&1

Constantly print Subprocess output while process is running

For anyone trying the answers to this question to get the stdout from a Python script note that Python buffers its stdout, and therefore it may take a while to see the stdout.

This can be rectified by adding the following after each stdout write in the target script:

sys.stdout.flush()

Converting from longitude\latitude to Cartesian coordinates

Here's the answer I found:

Just to make the definition complete, in the Cartesian coordinate system:

  • the x-axis goes through long,lat (0,0), so longitude 0 meets the equator;
  • the y-axis goes through (0,90);
  • and the z-axis goes through the poles.

The conversion is:

x = R * cos(lat) * cos(lon)

y = R * cos(lat) * sin(lon)

z = R *sin(lat)

Where R is the approximate radius of earth (e.g. 6371 km).

If your trigonometric functions expect radians (which they probably do), you will need to convert your longitude and latitude to radians first. You obviously need a decimal representation, not degrees\minutes\seconds (see e.g. here about conversion).

The formula for back conversion:

   lat = asin(z / R)
   lon = atan2(y, x)

asin is of course arc sine. read about atan2 in wikipedia. Don’t forget to convert back from radians to degrees.

This page gives c# code for this (note that it is very different from the formulas), and also some explanation and nice diagram of why this is correct,

Division in Python 2.7. and 3.3

"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:

float(20)/15 #1.33333333

Adding an item to an associative array

before for loop :

$data = array();

then in your loop:

$data[] = array($catagory => $question);

How to select last two characters of a string

Shortest:

str.slice(-2)

Example:

_x000D_
_x000D_
const str = "test";
const last2 = str.slice(-2);

console.log(last2);
_x000D_
_x000D_
_x000D_

PHP Error: Cannot use object of type stdClass as array (array and object issues)

If you're iterating over an object instead of an array, you'll need to access the properties using:

$id = $blog->id;
$title = $blog->title;
$content = $blog->content;

That, or change your object to an array.

Can't import org.apache.http.HttpResponse in Android Studio

Main build.gradle - /build.gradle

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1' 
        // Versions: http://jcenter.bintray.com/com/android/tools/build/gradle/
    }
    ...
}

Module specific build.gradle - /app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

ZIP Code (US Postal Code) validation

If you're doing for Canada remember that not all letters are valid

These letters are invalid: D, F, I, O, Q, or U And the letters W and Z are not used as the first letter. Also some people use an optional space after the 3rd character.

Here is a regular expression for Canadian postal code:

new RegExp(/^[abceghjklmnprstvxy][0-9][abceghjklmnprstvwxyz]\s?[0-9][abceghjklmnprstvwxyz][0-9]$/i)

The last i makes it case insensitive.

Remove Server Response Header IIS7

Scott Mitchell provides in a blog post solutions for removing unnecessary headers.

As already said here in other answers, for the Server header, there is the http module solution, or a web.config solution for IIS 10+, or you can use URLRewrite instead for blanking it.

The most practical solution for an up-to-date (IIS 10 +) setup is using removeServerHeader in the web.config:

<system.webServer>
  ...
  <security>
    <requestFiltering removeServerHeader="true" />
  </security>
  ...
</system.webServer>

For X-AspNet-Version and X-AspNetMvc-Version, he provides a better way than removing them on each response: simply not generating them at all.

Use enableVersionHeader for disabling X-AspNet-Version, in web.config

<system.web>
  ...
  <httpRuntime enableVersionHeader="false" />
  ...
</system.web>

Use MvcHandler.DisableMvcResponseHeader in .Net Application_Start event for disabling X-AspNetMvc-Version

MvcHandler.DisableMvcResponseHeader = true;

And finally, remove in IIS configuration the X-Powered-By custom header in web.config.

<system.webServer>
  ...
  <httpProtocol>
    <customHeaders>
      <remove name="X-Powered-By" />
    </customHeaders>
  </httpProtocol>
  ...
</system.webServer>

Beware, if you have ARR (Application Request Routing), it will also add its own X-Powered-By, which will not be removed by custom headers settings. This one has to be removed through the IIS Manager, Editor configuration on the IIS root (not on a site): go to system.webServer/proxy node and set arrResponseHeader to false. After an IISReset, it is taken into account.
(I have found this one here, excepted this post is about old IIS 6.0 way of configuring things.)

Do not forget that solution by application code does not apply by default to header generated on static content (you may activate the runAllManagedModulesForAllRequests for changing that, but it causes all requests to run .Net pipeline). It is not an issue for X-AspNetMvc-Version since it is not added on static content (at least if static request are not run in .Net pipeline).

Side note: when the aim is to cloak used technology, you should also change standard .Net cookie names (.ASPXAUTH if forms auth activated (use name attribute on forms tag in web.config), ASP.NET_SessionId (use <sessionState cookieName="yourName" /> in web.config under system.web tag), __RequestVerificationToken (change it by code with AntiForgeryConfig.CookieName, but unfortunately does not apply to the hidden input this system generates in the html)).

Resource from src/main/resources not found after building with maven

FileReader reads from files on the file system.

Perhaps you intended to use something like this to load a file from the class path

// this will look in src/main/resources before building and myjar.jar! after building.
InputStream is = MyClass.class.getClassloader()
                     .getResourceAsStream("config.txt");

Or you could extract the file from the jar before reading it.

how to convert 2d list to 2d numpy array?

just use following code

c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

Then it will give you

you can check shape and dimension of matrix by using following code

c.shape

c.ndim

How do we check if a pointer is NULL pointer?

Apparently the thread you refer is about C++.

In C your snippet will always work. I like the simpler if (p) { /* ... */ }.

How to add element in List while iterating in java?

Iterate through a copy of the list and add new elements to the original list.

for (String s : new ArrayList<String>(list))     
{
    list.add("u");
}

See How to make a copy of ArrayList object which is type of List?

How can I find where Python is installed on Windows?

Go to C:\Users\USER\AppData\Local\Programs\Python\Python36 if it is not there then open console by windows+^R Then type cmd and hit enter type python if installed in your local file it will show you its version from there type the following import os import sys os.path.dirname(sys.executable)

Get textarea text with javascript or Jquery

As @Darin Dimitrov said, if it is not an iframe on the same domain it is not posible, if it is, check that $("#frame1").contents() returns all it should, and then check if the textbox is found:

$("#frame1").contents().find("#area1").length should be 1.

Edit

If when your textarea is "empty" an empty string is returned and when it has some text entered that text is returned, then it is working perfect!! When the textarea is empty, an empty string is returned!

Edit 2 Ok. Here there is one way, it is not very pretty but it works:

Outside the iframe you will access the textarea like this:

window.textAreaInIframe

And inside the iframe (which I assume has jQuery) in the document ready put this code:

$("#area1").change(function() {
    window.parent.textAreaInIframe = $(this).val();
}).trigger("change");

Quoting backslashes in Python string literals

You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)

>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

Incidentally, there's another string form which might be a bit clearer:

>>> print(r'baz "\"')
baz "\"

Get current directory name (without full path) in a Bash script

I strongly prefer using gbasename, which is part of GNU coreutils.

Python: find position of element in array

As Aaron states, you can use .index(value), but because that will throw an exception if value is not present, you should handle that case, even if you're sure it will never happen. A couple options are by checking its presence first, such as:

if value in my_list:
    value_index = my_list.index(value)

or by catching the exception as in:

try:
    value_index = my_list.index(value)
except:
    value_index = -1

You can never go wrong with proper error handling.

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

RE error: illegal byte sequence on Mac OS X

You simply have to pipe an iconv command before the sed command. Ex with file.txt input :

iconv -f ISO-8859-1 -t UTF8-MAC file.txt | sed 's/something/àéèêçùû/g' | .....

-f option is the 'from' codeset and -t option is the 'to' codeset conversion.

Take care of case, web pages usually show lowercase like that < charset=iso-8859-1"/> and iconv uses uppercase. You have list of iconv supported codesets in you system with command iconv -l

UTF8-MAC is modern OS Mac codeset for conversion.

JavaScript DOM: Find Element Index In Container

An example of making an array from HTMLCollection

<ul id="myList">
    <li>0</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

<script>
var tagList = [];

var ulList = document.getElementById("myList");

var tags   = ulList.getElementsByTagName("li");

//Dump elements into Array
while( tagList.length != tags.length){
    tagList.push(tags[tagList.length])
};

tagList.forEach(function(item){
        item.addEventListener("click", function (event){ 
            console.log(tagList.indexOf( event.target || event.srcElement));
        });
}); 
</script>

Multiple arguments to function called by pthread_create()?

The args of print_the_arguments is arguments, so you should use:

struct arg_struct *args = (struct arg_struct *)arguments. 

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

It's worth noting that even when On Error Resume Next is in effect, the Err object is still populated when an error occurs, so you can still do C-style error handling.

On Error Resume Next

DangerousOperationThatCouldCauseErrors

If Err Then
    WScript.StdErr.WriteLine "error " & Err.Number
    WScript.Quit 1
End If

On Error GoTo 0

HTTP Request in Swift with POST method

All the answers here use JSON objects. This gave us problems with the $this->input->post() methods of our Codeigniter controllers. The CI_Controller cannot read JSON directly. We used this method to do it WITHOUT JSON

func postRequest() {
    // Create url object
    guard let url = URL(string: yourURL) else {return}

    // Create the session object
    let session = URLSession.shared

    // Create the URLRequest object using the url object
    var request = URLRequest(url: url)

    // Set the request method. Important Do not set any other headers, like Content-Type
    request.httpMethod = "POST" //set http method as POST

    // Set parameters here. Replace with your own.
    let postData = "param1_id=param1_value&param2_id=param2_value".data(using: .utf8)
    request.httpBody = postData

    // Create a task using the session object, to run and return completion handler
    let webTask = session.dataTask(with: request, completionHandler: {data, response, error in
    guard error == nil else {
        print(error?.localizedDescription ?? "Response Error")
        return
    }
    guard let serverData = data else {
        print("server data error")
        return
    }
    do {
        if let requestJson = try JSONSerialization.jsonObject(with: serverData, options: .mutableContainers) as? [String: Any]{
            print("Response: \(requestJson)")
        }
    } catch let responseError {
        print("Serialisation in error in creating response body: \(responseError.localizedDescription)")
        let message = String(bytes: serverData, encoding: .ascii)
        print(message as Any)
    }

    // Run the task
    webTask.resume()
}

Now your CI_Controller will be able to get param1 and param2 using $this->input->post('param1') and $this->input->post('param2')

String replacement in batch file

You can use !, but you must have the ENABLEDELAYEDEXPANSION switch set.

setlocal ENABLEDELAYEDEXPANSION
set word=table
set str="jump over the chair"
set str=%str:chair=!word!%

C free(): invalid pointer

You can't call free on the pointers returned from strsep. Those are not individually allocated strings, but just pointers into the string s that you've already allocated. When you're done with s altogether, you should free it, but you do not have to do that with the return values of strsep.

Sending string via socket (python)

This piece of code is incorrect.

while 1:
    (clientsocket, address) = serversocket.accept()
    print ("connection found!")
    data = clientsocket.recv(1024).decode()
    print (data)
    r='REceieve'
    clientsocket.send(r.encode())

The call on accept() on the serversocket blocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.

That's the reason the recv works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.

Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.

jQuery DatePicker with today as maxDate

If you're using bootstrap 3 date time picker, try this:

$('.selector').datetimepicker({ maxDate: $.now() });

How to restart a single container with docker-compose

Since some of the other answers include info on rebuilding, and my use case also required a rebuild, I had a better solution (compared to those).

There's still a way to easily target just the one single worker container that both rebuilds + restarts it in a single line, albeit it's not actually a single command. The best solution for me was simply rebuild and restart:

docker-compose build worker && docker-compose restart worker

This accomplishes both major goals at once for me:

  1. Targets the single worker container
  2. Rebuilds and restarts it in a single line

Hope this helps anyone else getting here.

Android Studio: Where is the Compiler Error Output Window?

Are you on Windows? Launch cmd, find your project folder and run "gradlew build". This should already give you more output than the IDE, you can also use --info, --stacktrace and --debug there.

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

WebAPI 2 now has a package for CORS which can be installed using : Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebServic

Once this is installed, follow this for the code :http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.

\begin{description} 
     <YOUR TEXT HERE> 
\end{description}
  • This only worked on windows latex compiler

How to get base url with jquery or javascript?

You can easily get it with:

var currentUrl = window.location.href;

or, if you want the original URL, use:

var originalUrl = window.location.origin;

Under which circumstances textAlign property works in Flutter?

For maximum flexibility, I usually prefer working with SizedBox like this:

Row(
                                children: <Widget>[
                                  SizedBox(
                                      width: 235,
                                      child: Text('Hey, ')),
                                  SizedBox(
                                      width: 110,
                                      child: Text('how are'),
                                  SizedBox(
                                      width: 10,
                                      child: Text('you?'))
                                ],
                              )

I've experienced problems with text alignment when using alignment in the past, whereas sizedbox always does the work.

Java optional parameters

There is optional parameters with Java 5.0. Just declare your function like this:

public void doSomething(boolean... optionalFlag) {
    //default to "false"
    //boolean flag = (optionalFlag.length >= 1) ? optionalFlag[0] : false;
}

you could call with doSomething(); or doSomething(true); now.

How to use Jackson to deserialise an array of objects

For Generic Implementation:

public static <T> List<T> parseJsonArray(String json,
                                         Class<T> classOnWhichArrayIsDefined) 
                                         throws IOException, ClassNotFoundException {
   ObjectMapper mapper = new ObjectMapper();
   Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";");
   T[] objects = mapper.readValue(json, arrayClass);
   return Arrays.asList(objects);
}

Which SchemaType in Mongoose is Best for Timestamp?

Mongoose now supports the timestamps in schema.

const item = new Schema(
  {
    id: {
      type: String,
      required: true,
    },
  { timestamps: true },
);

This will add the createdAt and updatedAt fields on each record create.

Timestamp interface has fields

  interface SchemaTimestampsConfig {
    createdAt?: boolean | string;
    updatedAt?: boolean | string;
    currentTime?: () => (Date | number);
  }

This would help us to choose which fields we want and overwrite the date format.

What is difference between png8 and png24

You have asked two questions, one in the title about the difference between PNG8 and PNG24, which has received a few answers, namely that PNG24 has 8-bit red, green, and blue channels, and PNG-8 has a single 8-bit index into a palette. Naturally, PNG24 usually has a larger filesize than PNG8. Furthermore, PNG8 usually means that it is opaque or has only binary transparency (like GIF); it's defined that way in ImageMagick/GraphicsMagick.

This is an answer to the other one, "I would like to know that if I use either type in my html page, will there be any error? Or is this only quality matter?"

You can put either type on an HTML page and no, this won't cause an error; the files should all be named with the ".png" extension and referred to that way in your HTML. Years ago, early versions of Internet Explorer would not handle PNG with an alpha channel (PNG32) or indexed-color PNG with translucent pixels properly, so it was useful to convert such images to PNG8 (indexed-color with binary transparency conveyed via a PNG tRNS chunk) -- but still use the .png extension, to be sure they would display properly on IE. I think PNG24 was always OK on Internet Explorer because PNG24 is either opaque or has GIF-like single-color transparency conveyed via a PNG tRNS chunk.

The names PNG8 and PNG24 aren't mentioned in the PNG specification, which simply calls them all "PNG". Other names, invented by others, include

  • PNG8 or PNG-8 (indexed-color with 8-bit samples, usually means opaque or with GIF-like, binary transparency, but sometimes includes translucency)
  • PNG24 or PNG-24 (RGB with 8-bit samples, may have GIF-like transparency via tRNS)
  • PNG32 (RGBA with 8-bit samples, opaque, transparent, or translucent)
  • PNG48 (Like PNG24 but with 16-bit R,G,B samples)
  • PNG64 (like PNG32 but with 16-bit R,G,B,A samples)

There are many more possible combinations including grayscale with 1, 2, 4, 8, or 16-bit samples and indexed PNG with 1, 2, or 4-bit samples (and any of those with transparent or translucent pixels), but those don't have special names.

Python data structure sort list alphabetically

[] denotes a list, () denotes a tuple and {} denotes a dictionary. You should take a look at the official Python tutorial as these are the very basics of programming in Python.

What you have is a list of strings. You can sort it like this:

In [1]: lst = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']

In [2]: sorted(lst)
Out[2]: ['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']

As you can see, words that start with an uppercase letter get preference over those starting with a lowercase letter. If you want to sort them independently, do this:

In [4]: sorted(lst, key=str.lower)
Out[4]: ['constitute', 'Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim']

You can also sort the list in reverse order by doing this:

In [12]: sorted(lst, reverse=True)
Out[12]: ['constitute', 'Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux']

In [13]: sorted(lst, key=str.lower, reverse=True)
Out[13]: ['Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux', 'constitute']

Please note: If you work with Python 3, then str is the correct data type for every string that contains human-readable text. However, if you still need to work with Python 2, then you might deal with unicode strings which have the data type unicode in Python 2, and not str. In such a case, if you have a list of unicode strings, you must write key=unicode.lower instead of key=str.lower.

ffprobe or avprobe not found. Please install one

This is so simple if on windows...

In the folder where you have youtube-dl.exe

goto https://www.gyan.dev/ffmpeg/builds/

download the ffmpeg-git-full.7z file the download link is https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z

Open that zip file and move the ffmpeg.exe file to the same folder where youtube-dl.exe is

Example "blahblah.7z / whatevertherootfolderis / bin / ffmpeg.exe"

youtube-dl.exe -x --audio-format mp3 -o %(title)s.%(ext)s https://www.youtube.com/watch?v=wyPKRcBTsFQ

How can I add new item to the String array?

Simple answer: You can't. An array is fixed size in Java. You'll want to use a List<String>.

Alternatively, you could create an array of fixed size and put things in it:

String[] array = new String[2];
array[0] = "Hello";
array[1] = "World!";

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

Numpy AttributeError: 'float' object has no attribute 'exp'

You convert type np.dot(X, T) to float32 like this:

z=np.array(np.dot(X, T),dtype=np.float32)

def sigmoid(X, T):
    return (1.0 / (1.0 + np.exp(-z)))

Hopefully it will finally work!

Performance of Java matrix math libraries?

Linalg code that relies heavily on Pentiums and later processors' vector computing capabilities (starting with the MMX extensions, like LAPACK and now Atlas BLAS) is not "fantastically optimized", but simply industry-standard. To replicate that perfomance in Java you are going to need native libraries. I have had the same performance problem as you describe (mainly, to be able to compute Choleski decompositions) and have found nothing really efficient: Jama is pure Java, since it is supposed to be just a template and reference kit for implementers to follow... which never happened. You know Apache math commons... As for COLT, I have still to test it but it seems to rely heavily on Ninja improvements, most of which were reached by building an ad-hoc Java compiler, so I doubt it's going to help. At that point, I think we "just" need a collective effort to build a native Jama implementation...

How do I make a matrix from a list of vectors in R?

t(sapply(a, '[', 1:max(sapply(a, length))))

where 'a' is a list. Would work for unequal row size

jQuery location href

There's no need of jQuery.

window.location.href = 'http://example.com';

CSS Box Shadow - Top and Bottom Only

I've played around with it and I think I have a solution. The following example shows how to set Box-Shadow so that it will only show a shadow for the inset top and bottom of an element.

Legend: insetOption leftPosition topPosition blurStrength spreadStrength color

Description
The key to accomplishing this is to set the blur value to <= the negative of the spread value (ex. inset 0px 5px -?px 5px #000; the blur value should be -5 and lower) and to also keep the blur value > 0 when subtracted from the primary positioning value (ex. using the example from above, the blur value should be -9 and up, thus giving us an optimal value for the the blur to be between -5 and -9).

Solution

.styleName {   
/* for IE 8 and lower */
background-color:#888; filter: progid:DXImageTransform.Microsoft.dropShadow(color=#FFFFCC, offX=0, offY=0, positive=true);  

/* for IE 9 */ 
box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for webkit browsers */ 
-webkit-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for firefox 3.6+ */
-moz-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7);   
}

Where should my npm modules be installed on Mac OS X?

Second Thomas David Kehoe, with the following caveat --

If you are using node version manager (nvm), your global node modules will be stored under whatever version of node you are using at the time you saved the module.

So ~/.nvm/versions/node/{version}/lib/node_modules/.

Convert PDF to image with high resolution

In ImageMagick, you can do "supersampling". You specify a large density and then resize down as much as desired for the final output size. For example with your image:

convert -density 600 test.pdf -background white -flatten -resize 25% test.png


enter image description here

Download the image to view at full resolution for comparison..

I do not recommend saving to JPG if you are expecting to do further processing.

If you want the output to be the same size as the input, then resize to the inverse of the ratio of your density to 72. For example, -density 288 and -resize 25%. 288=4*72 and 25%=1/4

The larger the density the better the resulting quality, but it will take longer to process.

How can I build XML in C#?

For simple things, I just use the XmlDocument/XmlNode/XmlAttribute classes and XmlDocument DOM found in System.XML.

It generates the XML for me, I just need to link a few items together.

However, on larger things, I use XML serialization.

Search for value in DataGridView in a column

Why you are using row.Cells[row.Index]. You need to specify index of column you want to search (Problem #2). For example, you need to change row.Cells[row.Index] to row.Cells[2] where 2 is index of your column:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;

    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        foreach (DataGridViewRow row in dgvProjects.Rows)
        {
            if (row.Cells[2].Value.ToString().Equals(searchValue))
            {
                row.Selected = true;
                break;
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

Reading a JSP variable from JavaScript

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

    <title>JSP Page</title>
    <script>
       $(document).ready(function(){
          <% String name = "phuongmychi.github.io" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html

       });
    </script>
</head>
<body>
    <h1 id='id'>!</h1>
</body>

Python division

Specifying a float by placing a '.' after the number will also cause it to default to float.

>>> 1 / 2
0

>>> 1. / 2.
0.5

Clicking HTML 5 Video element to play, pause video, breaks play button

Following up on ios-lizard's idea:

I found out that the controls on the video are about 35 pixels. This is what I did:

$(this).on("click", function(event) {
    console.log("clicked");
    var offset = $(this).offset();
    var height = $(this).height();
    var y = (event.pageY - offset.top - height) * -1;
    if (y > 35) {
        this.paused ? this.play() : this.pause();
    }
});

Basically, it finds the position of the click relative to the element. I multiplied it by -1 to make it positive. If the value was greater than 35 (the height of the controls) that means that the user click somewhere else than the controls Therefore we pause or play the video.

Force IE10 to run in IE10 Compatibility View?

I had the exact same problem, this - "meta http-equiv="X-UA-Compatible" content="IE=7">" works great in IE8 and IE9, but not in IE10. There is a bug in the server browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.

My thanks to Scott Hanselman for this fix.

Here is the link -

http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx

This MS KP fix just adds missing files to the asp.net on your server. I installed it and rebooted my server and it now works perfectly. I would have thought that MS would have given this fix a wider distribution.

Rick

Making an svg image object clickable with onclick, avoiding absolute positioning

You could use following code:

<style>
    .svgwrapper {
        position: relative;
    }
    .svgwrapper {
        position: absolute;
        z-index: -1;
    }
</style>

<div class="svgwrapper" onClick="function();">
    <object src="blah" />
</div>

b3ng0 wrote similar code but it does not work. z-index of parent must be auto.

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Maybe this example listed here can help you out. Statement from the author

about 24 lines of code to encrypt, 23 to decrypt

Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)

  /*
  Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.*/
   
  #region Usings
  using System;
  using System.IO;
  using System.Security.Cryptography;
  using System.Text;
  #endregion
   
  namespace Utilities.Encryption
  {
      /// <summary>
      /// Utility class that handles encryption
      /// </summary>
      public static class AESEncryption
      {
          #region Static Functions
   
          /// <summary>
          /// Encrypts a string
          /// </summary>
          /// <param name="PlainText">Text to be encrypted</param>
          /// <param name="Password">Password to encrypt with</param>
          /// <param name="Salt">Salt to encrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>An encrypted string</returns>
          public static string Encrypt(string PlainText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(PlainText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] CipherTextBytes = null;
              using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream())
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                      {
                          CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                          CryptoStream.FlushFinalBlock();
                          CipherTextBytes = MemStream.ToArray();
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Convert.ToBase64String(CipherTextBytes);
          }
   
          /// <summary>
          /// Decrypts a string
          /// </summary>
          /// <param name="CipherText">Text to be decrypted</param>
          /// <param name="Password">Password to decrypt with</param>
          /// <param name="Salt">Salt to decrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>A decrypted string</returns>
          public static string Decrypt(string CipherText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(CipherText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
              int ByteCount = 0;
              using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                      {
   
                          ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
          }
   
          #endregion
      }
  }

Call a stored procedure with another in Oracle

Sure, you just call it from within the SP, there's no special syntax.

Ex:

   PROCEDURE some_sp
   AS
   BEGIN
      some_other_sp('parm1', 10, 20.42);
   END;

If the procedure is in a different schema than the one the executing procedure is in, you need to prefix it with schema name.

   PROCEDURE some_sp
   AS
   BEGIN
      other_schema.some_other_sp('parm1', 10, 20.42);
   END;

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

How can I fix "Design editor is unavailable until a successful build" error?

I have the latest Android Studio 3.6.1 and yet couldn't build a simple 'Hello World' app as documented here "https://codelabs.developers.google.com/codelabs/android-training-hello-world/index.html?index=..%2F..%2Fandroid-training#3". I applied various steps discussed above including the 2 most viable options which should have really solved this issue,

  1. 'File->Sync Project with Gradle Files' and
  2. 'File->Invalidate Caches/Restart' but to no avail.

Even though, I suspect standard answer should be one of these 2 options only for most, but for me the resolution came only after I went inside the 'File->Project Structure' and checked my SDK versions configured! Android Studio and Gradle were using different JDK versions and locations.

  • Android Studio: C:\Program Files\Java\jdk1.8.0_241
  • Gradle: C:\Program Files\Java\jdk-13.0.2

I had previously defined my JAVA_HOME environment variable by downloading latest JAVA SDK on my own from ORACLE website. Where Gradle was using the %JAVA_HOME% JAVA SDK version and Android Studio the built in SDK which came along with Android Studio.

Once I switched both to versions JDK 1.8.* (Any version as long as it is JDK 1.8. for that matter*) then simple 'File->Synch...' option worked perfectly fine for me!

Good luck the solution is in between one of these 2 options only if you are stuck, just ensure you validate JDK versions being referred to!

Change primary key column in SQL Server

Assuming that your current primary key constraint is called pk_history, you can replace the following lines:

ALTER TABLE history ADD PRIMARY KEY (id)

ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name

with these:

ALTER TABLE history DROP CONSTRAINT pk_history

ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)

If you don't know what the name of the PK is, you can find it with the following query:

SELECT * 
  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
 WHERE TABLE_NAME = 'history'

How to run function in AngularJS controller on document ready?

Angular has several timepoints to start executing functions. If you seek for something like jQuery's

$(document).ready();

You may find this analog in angular to be very useful:

$scope.$watch('$viewContentLoaded', function(){
    //do something
});

This one is helpful when you want to manipulate the DOM elements. It will start executing only after all te elements are loaded.

UPD: What is said above works when you want to change css properties. However, sometimes it doesn't work when you want to measure the element properties, such as width, height, etc. In this case you may want to try this:

$scope.$watch('$viewContentLoaded', 
    function() { 
        $timeout(function() {
            //do something
        },0);    
});

git - remote add origin vs remote set-url origin

You can not call remote set-url origin just after git init, Because the git remote set-url command will not create origin, but it changes an existing remote repository URL.

so the command git remote set-url will only work if you've either cloned the repository or manually added a remote called origin.

you can check remote with command git remote -v it will show remote url after name, or if this command gives error like fatal: Not a git repository (or any of the parent directories): .git then the repository not exists, so you have to add origin with command git remote add

1. git remote add

This command is used to add a new remote, you can use this command on the terminal, in the directory of your repository.

The git remote add command takes two arguments:

  1. A remote name, for example, origin
  2. A remote URL, for example, https://github.com/user/repo.git

For example:

git remote add origin https://github.com/user/repo.git

2.git remote set-url

The git remote set-url command changes an existing remote repository URL.

The git remote set-url command takes two arguments:

  1. An existing remote name. For example, origin or upstream are two common choices.
  2. A new URL for the remote

For example you can change your remote's URL from SSH to HTTPS with the git remote set-url command.

git remote set-url origin https://github.com/USERNAME/REPOSITORY.git

you can verify that the remote URL has changed, with command git remote -v.

note: "origin" is a convention not part of the command. "origin" is the local name of the remote repository. you can use any name instead of "origin".

For example:

git remote add myorigin [email protected]:user/repo.git
git remote set-url myorigin https://github.com/user/repo.git

References from github: remote add, remote set-url

Create HTTP post request and receive response using C# console application

HttpWebRequest request =(HttpWebRequest)WebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
doc.Save(request.GetRequestStream());
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;

Hope it helps

Extract first item of each sublist

lst = [['a','b','c'], [1,2,3], ['x','y','z']]
outputlist = []
for values in lst:
    outputlist.append(values[0])

print(outputlist) 

Output: ['a', 1, 'x']

Android Endless List

The key of this problem is to detect the load-more event, start an async request for data and then update the list. Also an adapter with loading indicator and other decorators is needed. In fact, the problem is very complicated in some corner cases. Just a OnScrollListener implementation is not enough, because sometimes the items do not fill the screen.

I have written a personal package which support endless list for RecyclerView, and also provide a async loader implementation AutoPagerFragment which makes it very easy to get data from a multi-page source. It can load any page you want into a RecyclerView on a custom event, not only the next page.

Here is the address: https://github.com/SphiaTower/AutoPagerRecyclerManager

MongoDB logging all queries

You can log all queries:

$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use myDb
switched to db myDb
> db.getProfilingLevel()
0
> db.setProfilingLevel(2)
{ "was" : 0, "slowms" : 1, "ok" : 1 }
> db.getProfilingLevel()
2
> db.system.profile.find().pretty()

Source: http://docs.mongodb.org/manual/reference/method/db.setProfilingLevel/

db.setProfilingLevel(2) means "log all operations".

Get type name without full namespace

After the C# 6.0 (including) you can use nameof expression:

using Stuff = Some.Cool.Functionality  
class C {  
    static int Method1 (string x, int y) {}  
    static int Method1 (string x, string y) {}  
    int Method2 (int z) {}  
    string f<T>() => nameof(T);  
}  

var c = new C()  

nameof(C) -> "C"  
nameof(C.Method1) -> "Method1"   
nameof(C.Method2) -> "Method2"  
nameof(c.Method1) -> "Method1"   
nameof(c.Method2) -> "Method2"  
nameof(z) -> "z" // inside of Method2 ok, inside Method1 is a compiler error  
nameof(Stuff) = "Stuff"  
nameof(T) -> "T" // works inside of method but not in attributes on the method  
nameof(f) -> “f”  
nameof(f<T>) -> syntax error  
nameof(f<>) -> syntax error  
nameof(Method2()) -> error “This expression does not have a name”  

Note! nameof not get the underlying object's runtime Type, it is just the compile-time argument. If a method accepts an IEnumerable then nameof simply returns "IEnumerable", whereas the actual object could be "List".

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

Droppping schema and recreating it with utf8mb4 character set solved my issue.

How to open an existing project in Eclipse?

Just do like below, it helped me after doing like this.

To load existing Eclipse projects in the IDE, you need to import them into the Eclipse workspace.

  1. Click File > Import > General
  2. Click Existing Projects into Workspace.
  3. You can edit the project directly in its original location or choose to create a copy of the project in the workspace.
  4. Select the directory that contains the projects you want to import.
  5. Click Finish. This imports the projects into the current workspace and loads them in the IDE.

Look at this below link for reference. https://www.microfocus.com/documentation/enterprise-developer/ed30/Eclipse/GUID-773A19C7-98B2-442D-9D36-240E20E3F2CE.html

@ variables in Ruby on Rails

A local variable is only accessible from within the block of it's initialization. Also a local variable begins with a lower case letter (a-z) or underscore (_).

And instance variable is an instance of self and begins with a @ Also an instance variable belongs to the object itself. Instance variables are the ones that you perform methods on i.e. .send etc

example:

@user = User.all

The @user is the instance variable

And Uninitialized instance variables have a value of Nil

Xcode 'CodeSign error: code signing is required'

  1. Populate "Code Signing" in both "Project" and "Targets" section
  2. Select valid entries in "Code Signing Identity" in both "Debug" and "Release"
  3. Under "Debug" select you Developer certificate
  4. Under "Release" select your Distributor certificate

Following these 4 steps always solves my issues.

jquery append div inside div with id and manipulate

You're overcomplicating things:

var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
e.attr('id', 'myid');
$('#box').append(e);

For example: http://jsfiddle.net/ambiguous/Dm5J2/

How can I control the width of a label tag?

You can either give class name to all label so that all can have same width :

 .class-name {  width:200px;}

Example

.labelname{  width:200px;}

or you can simple give rest of label

label {  width:200px;  display: inline-block;}

Count rows with not empty value

It works for me:

=SUMPRODUCT(NOT(ISBLANK(F2:F)))

Count of all non-empty cells from F2 to the end of the column

Notepad++ - How can I replace blank lines

By the way, in Notepad++ there's built-in plugin that can handle this: TextFX -> TextFX Edit -> Delete Blank Lines (first press CTRL+A to select all).

Change background color on mouseover and remove it after mouseout

This is my solution :

$(document).ready(function () {
  $( "td" ).on({
    "click": clicked,
    "mouseover": hovered,
    "mouseout": mouseout
});

var flag=0;

function hovered(){
  $(this).css("background", "#380606");
}

function mouseout(){
  if (flag == 0){
  $(this).css("background", "#ffffff");
} else {
  flag=0;
}
}

function clicked(){
  $(this).css("background","#000000");
  flag=1;
}
})

Parse XML using JavaScript

I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

If your XML is in a string variable called txt and looks like this:

<address>
  <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
</address>

Then you can parse the XML with Javascript DOM like this:

if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;

JSFiddle


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

_x000D_
_x000D_
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
  <s:street>Roble Ave</s:street>_x000D_
  <sn:streetNumber>649</sn:streetNumber>_x000D_
  <p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
    parser = new DOMParser();_x000D_
    xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
    xmlDoc.async = false;_x000D_
    xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
_x000D_
_x000D_

How to specify HTTP error code?

Express deprecated res.send(body, status).

Use res.status(status).send(body) instead

Javascript Print iframe contents only

If you are setting the contents of IFrame using javascript document.write() then you must close the document by newWin.document.close(); otherwise the following code will not work and print will print the contents of whole page instead of only the IFrame contents.

var frm = document.getElementById(id).contentWindow;
frm.focus();// focus on contentWindow is needed on some ie versions
frm.print();

Center Align on a Absolutely Positioned Div

To center it both vertically and horizontally do this:

div#thing {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

How to fire an event on class change using jQuery?

Use trigger to fire your own event. When ever you change class add trigger with name

JS Fiddle DEMO

$("#main").on('click', function () {
    $("#chld").addClass("bgcolorRed").trigger("cssFontSet");
});

$('#chld').on('cssFontSet', function () {

    alert("Red bg set ");
});

Learn jQuery: Simple and easy jQuery tutorials blog

Writing file to web server - ASP.NET

protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
    using (StreamWriter w = new StreamWriter(Server.MapPath("~/data.txt"), true))
    {
        w.WriteLine(TextBox1.Text); // Write the text
    }
}

Correlation heatmap

  1. Use the 'jet' colormap for a transition between blue and red.
  2. Use pcolor() with the vmin, vmax parameters.

It is detailed in this answer: https://stackoverflow.com/a/3376734/21974

How to I say Is Not Null in VBA

Use Not IsNull(Fields!W_O_Count.Value)

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

A quick fix for capistrano user is to put this line to Capfile

# Uncomment if you are using Rails' asset pipeline
load 'deploy/assets'

Laravel Eloquent get results grouped by days

I had same problem, I'm currently using Laravel 5.3.

I use DATE_FORMAT()

->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))

Hopefully this will help you.

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

Plugin that scrolls (with animation) only when required

I've written a jQuery plugin that does exactly what it says on the tin (and also exactly what you require). The good thing is that it will only scroll container when element is actually off. Otherwise no scrolling will be performed.

It works as easy as this:

$("table tr:last").scrollintoview();

It automatically finds closest scrollable ancestor that has excess content and is showing scrollbars. So if there's another ancestor with overflow:auto but is not scrollable will be skipped. This way you don't need to provide scrollable element because sometimes you don't even know which one is scrollable (I'm using this plugin in my Sharepoint site where content/master is developer independent so it's beyond my control - HTML may change when site is operational so can scrollable containers).

C# LINQ select from list

        var eventids = GetEventIdsByEventDate(DateTime.Now);
        var result = eventsdb.Where(e => eventids.Contains(e));

If you are returnning List<EventFeed> inside the method, you should change the method return type from IEnumerable<EventFeed> to List<EventFeed>.

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

C#: How would I get the current time into a string?

You can use format strings as well.

string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros

or some shortcuts if the format works for you

string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();

Either should work.

Can we pass parameters to a view in SQL?

no you can pass the parameter to the procedure in view

java.lang.OutOfMemoryError: Java heap space in Maven

I have solved this problem on my side by 2 ways:

  1. Adding this configuration in pom.xml

    <configuration><argLine>-Xmx1024m</argLine></configuration>
    
  2. Switch to used JDK 1.7 instead of 1.6

Perform Segue programmatically and pass parameters to the destination view

In case if you use new swift version.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ChannelMoreSegue" {

        }
}

Align HTML input fields by :

I know that this approach has been taken before, But I believe that using tables, the layout can be generated easily, Though this may not be the best practice.

JSFiddle

HTML

<table>

    <tr><td>Name:</td><td><input type="text"/></td></tr>

    <tr><td>Age:</td><td><input type="text"/></td></tr>

</table>

<!--You can add the fields as you want-->

CSS

td{
    text-align:right;
}

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

How to get the latest tag name in current branch in Git?

git log --tags --no-walk --pretty="format:%d" | sed 2q | sed 's/[()]//g' | sed s/,[^,]*$// | sed  's ......  '

IF YOU NEED MORE THAN ONE LAST TAG

(git describe --tags sometimes gives wrong hashes, i dont know why, but for me --max-count 2 doesnt work)

this is how you can get list with latest 2 tag names in reverse chronological order, works perfectly on git 1.8.4. For earlier versions of git(like 1.7.*), there is no "tag: " string in output - just delete last sed call

If you want more than 2 latest tags - change this "sed 2q" to "sed 5q" or whatever you need

Then you can easily parse every tag name to variable or so.

Moment.js get day name from date

code

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('dddd');
console.log(weekDayName);

mydate is the input date. The variable weekDayName get the name of the day. Here the output is

Output

Wednesday

_x000D_
_x000D_
var mydate = "2017-08-30T00:00:00";_x000D_
console.log(moment(mydate).format('dddd'));_x000D_
console.log(moment(mydate).format('ddd'));_x000D_
console.log('Day in number[0,1,2,3,4,5,6]: '+moment(mydate).format('d'));_x000D_
console.log(moment(mydate).format('MMM'));_x000D_
console.log(moment(mydate).format('MMMM'));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

Hashmap holding different data types as values for instance Integer, String and Object

Create an object holding following properties with an appropriate name.

  1. message
  2. timestamp
  3. count
  4. version

and use this as a value in your map.

Also consider overriding the equals() and hashCode() method accordingly if you do not want object equality to be used for comparison (e.g. when inserting values into your map).

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

public class LmsEmpWfhUtils {    
    private LmsEmpWfhUtils() 
    { 
    // prevents access default paramater-less constructor
    }
}

This prevents the default parameter-less constructor from being used elsewhere in your code.

Changing iframe src with Javascript

Here is my updated code. It works fine and it can help you.

<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  <title>Untitled 1</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
  <script type="text/javascript">
  function go(loc) {
    document.getElementById('calendar').src = loc;
  }
  </script>
</head>

<body>
  <iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>

  <form method="post">
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month
  </form>

</body>

</html>

Convert hex to binary

Another way:

import math

def hextobinary(hex_string):
    s = int(hex_string, 16) 
    num_digits = int(math.ceil(math.log(s) / math.log(2)))
    digit_lst = ['0'] * num_digits
    idx = num_digits
    while s > 0:
        idx -= 1
        if s % 2 == 1: digit_lst[idx] = '1'
        s = s / 2
    return ''.join(digit_lst)

print hextobinary('abc123efff')

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Getter and Setter declaration in .NET

Properties are used to encapsulate some data. You could use a plain field:

public string MyField

But this field can be accessed by all outside users of your class. People can insert illegal values or change the value in ways you didn't expect.

By using a property, you can encapsulate the way your data is accessed. C# has a nice syntax for turning a field into a property:

string MyProperty { get; set; }

This is called an auto-implemented property. When the need arises you can expand your property to:

string _myProperty;

public string MyProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

Now you can add code that validates the value in your setter:

set
{
    if (string.IsNullOrWhiteSpace(value))
        throw new ArgumentNullException();

    _myProperty = value;
}

Properties can also have different accessors for the getter and the setter:

public string MyProperty { get; private set; }

This way you create a property that can be read by everyone but can only be modified by the class itself.

You can also add a completely custom implementation for your getter:

public string MyProperty
{
    get
    {
        return DateTime.Now.Second.ToString();
    }
}

When C# compiles your auto-implemented property, it generates Intermediate Language (IL). In your IL you will see a get_MyProperty and set_MyProperty method. It also creates a backing field called <MyProperty>k_BackingField (normally this would be an illegal name in C# but in IL it's valid. This way you won't get any conflicts between generated types and your own code). However, you should use the official property syntax in C#. This creates a nicer experience in C# (for example with IntelliSense).

By convention, you shouldn't use properties for operations that take a long time.

How to get Android application id?

I am not sure what you need the app/installation ID for, but you can review the existing possibilities in a great article from Android developers:

To sum up:

  • UUID.randomUUID() for creating id on the first time an app runs after installation and simple retrieval afterwards
  • TelephonyManager.getDeviceId() for actual device identifier
  • Settings.Secure.ANDROID_ID on relatively modern devices

MySQL config file location - redhat linux server

From the header of '/etc/mysql/my.cnf':

MariaDB programs look for option files in a set of
locations which depend on the deployment platform.
[...] For information about these locations, do:
'my_print_defaults --help' and see what is printed under
"Default options are read from the following files in the given order:"
More information at: http://dev.mysql.com/doc/mysql/en/option-files.html

T-SQL split string based on delimiter

Try filtering out the rows that contain strings with the delimiter and work on those only like:

SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
       SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM   MyTable
WHERE CHARINDEX('/', myColumn) > 0

Or

SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
       SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM   MyTable
WHERE myColumn LIKE '%/%'

'tuple' object does not support item assignment

You probably want the next transformation for you pixels:

pixels = map(list, image.getdata())

Animate visibility modes, GONE and VISIBLE

To animate layout changes, you can add the following attribute to your LinearLayout

android:animateLayoutChanges="true"

and it will animate changes automatically for you.


For information, if android:animateLayoutChanges="true" is used, then custom animation via anim xml will not work.

A 'for' loop to iterate over an enum in Java

.values()

You can call the values() method on your enum.

for (Direction dir : Direction.values()) {
  // do what you want
}

This values() method is implicitly declared by the compiler. So it is not listed on Enum doc.

Why does C++ compilation take so long?

The trade off you are getting is that the program runs a wee bit faster. That may be a cold comfort to you during development, but it could matter a great deal once development is complete, and the program is just being run by users.

Foreign Key Django Model

I would advise, it is slightly better practise to use string model references for ForeignKey relationships if utilising an app based approach to seperation of logical concerns .

So, expanding on Martijn Pieters' answer:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        'app_label.Anniversary', on_delete=models.CASCADE)
    address = models.ForeignKey(
        'app_label.Address', on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

How to deserialize JS date using Jackson?

@JsonFormat only work for standard format supported by the jackson version that you are using.

Ex :- compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")) for jackson 2.8.6

How to increase the max connections in postgres?

Just increasing max_connections is bad idea. You need to increase shared_buffers and kernel.shmmax as well.


Considerations

max_connections determines the maximum number of concurrent connections to the database server. The default is typically 100 connections.

Before increasing your connection count you might need to scale up your deployment. But before that, you should consider whether you really need an increased connection limit.

Each PostgreSQL connection consumes RAM for managing the connection or the client using it. The more connections you have, the more RAM you will be using that could instead be used to run the database.

A well-written app typically doesn't need a large number of connections. If you have an app that does need a large number of connections then consider using a tool such as pg_bouncer which can pool connections for you. As each connection consumes RAM, you should be looking to minimize their use.


How to increase max connections

1. Increase max_connection and shared_buffers

in /var/lib/pgsql/{version_number}/data/postgresql.conf

change

max_connections = 100
shared_buffers = 24MB

to

max_connections = 300
shared_buffers = 80MB

The shared_buffers configuration parameter determines how much memory is dedicated to PostgreSQL to use for caching data.

  • If you have a system with 1GB or more of RAM, a reasonable starting value for shared_buffers is 1/4 of the memory in your system.
  • it's unlikely you'll find using more than 40% of RAM to work better than a smaller amount (like 25%)
  • Be aware that if your system or PostgreSQL build is 32-bit, it might not be practical to set shared_buffers above 2 ~ 2.5GB.
  • Note that on Windows, large values for shared_buffers aren't as effective, and you may find better results keeping it relatively low and using the OS cache more instead. On Windows the useful range is 64MB to 512MB.

2. Change kernel.shmmax

You would need to increase kernel max segment size to be slightly larger than the shared_buffers.

In file /etc/sysctl.conf set the parameter as shown below. It will take effect when postgresql reboots (The following line makes the kernel max to 96Mb)

kernel.shmmax=100663296

References

Postgres Max Connections And Shared Buffers

Tuning Your PostgreSQL Server

How to get name of the computer in VBA?

A shell method to read the environmental variable for this courtesy of devhut

Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")

Same source gives an API method:

Option Explicit

#If VBA7 And Win64 Then
    'x64 Declarations
    Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#Else
    'x32 Declaration
    Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If

Public Sub test()

    Debug.Print ComputerName
    
End Sub

Public Function ComputerName() As String
    Dim sBuff                 As String * 255
    Dim lBuffLen              As Long
    Dim lResult               As Long
 
    lBuffLen = 255
    lResult = GetComputerName(sBuff, lBuffLen)
    If lBuffLen > 0 Then
        ComputerName = Left(sBuff, lBuffLen)
    End If
End Function

internet explorer 10 - how to apply grayscale filter?

Inline SVG can be used in IE 10 and 11 and Edge 12.

I've created a project called gray which includes a polyfill for these browsers. The polyfill switches out <img> tags with inline SVG: https://github.com/karlhorky/gray

To implement, the short version is to download the jQuery plugin at the GitHub link above and add after jQuery at the end of your body:

<script src="/js/jquery.gray.min.js"></script>

Then every image with the class grayscale will appear as gray.

<img src="/img/color.jpg" class="grayscale">

You can see a demo too if you like.

Stripping everything but alphanumeric chars from a string in Python

Timing with random strings of ASCII printables:

from inspect import getsource
from random import sample
import re
from string import printable
from timeit import timeit

pattern_single = re.compile(r'[\W]')
pattern_repeat = re.compile(r'[\W]+')
translation_tb = str.maketrans('', '', ''.join(c for c in map(chr, range(256)) if not c.isalnum()))


def generate_test_string(length):
    return ''.join(sample(printable, length))


def main():
    for i in range(0, 60, 10):
        for test in [
            lambda: ''.join(c for c in generate_test_string(i) if c.isalnum()),
            lambda: ''.join(filter(str.isalnum, generate_test_string(i))),
            lambda: re.sub(r'[\W]', '', generate_test_string(i)),
            lambda: re.sub(r'[\W]+', '', generate_test_string(i)),
            lambda: pattern_single.sub('', generate_test_string(i)),
            lambda: pattern_repeat.sub('', generate_test_string(i)),
            lambda: generate_test_string(i).translate(translation_tb),

        ]:
            print(timeit(test), i, getsource(test).lstrip('            lambda: ').rstrip(',\n'), sep='\t')


if __name__ == '__main__':
    main()

Result (Python 3.7):

       Time       Length                           Code                           
6.3716264850008880  00  ''.join(c for c in generate_test_string(i) if c.isalnum())
5.7285426190064750  00  ''.join(filter(str.isalnum, generate_test_string(i)))
8.1875841680011940  00  re.sub(r'[\W]', '', generate_test_string(i))
8.0002205439959650  00  re.sub(r'[\W]+', '', generate_test_string(i))
5.5290945199958510  00  pattern_single.sub('', generate_test_string(i))
5.4417179649972240  00  pattern_repeat.sub('', generate_test_string(i))
4.6772285089973590  00  generate_test_string(i).translate(translation_tb)
23.574712151996210  10  ''.join(c for c in generate_test_string(i) if c.isalnum())
22.829975890002970  10  ''.join(filter(str.isalnum, generate_test_string(i)))
27.210196289997840  10  re.sub(r'[\W]', '', generate_test_string(i))
27.203713296003116  10  re.sub(r'[\W]+', '', generate_test_string(i))
24.008979928999906  10  pattern_single.sub('', generate_test_string(i))
23.945240008994006  10  pattern_repeat.sub('', generate_test_string(i))
21.830899796994345  10  generate_test_string(i).translate(translation_tb)
38.731336012999236  20  ''.join(c for c in generate_test_string(i) if c.isalnum())
37.942474347000825  20  ''.join(filter(str.isalnum, generate_test_string(i)))
42.169366310001350  20  re.sub(r'[\W]', '', generate_test_string(i))
41.933375883003464  20  re.sub(r'[\W]+', '', generate_test_string(i))
38.899814646996674  20  pattern_single.sub('', generate_test_string(i))
38.636144253003295  20  pattern_repeat.sub('', generate_test_string(i))
36.201238164998360  20  generate_test_string(i).translate(translation_tb)
49.377356811004574  30  ''.join(c for c in generate_test_string(i) if c.isalnum())
48.408927293996385  30  ''.join(filter(str.isalnum, generate_test_string(i)))
53.901889764994850  30  re.sub(r'[\W]', '', generate_test_string(i))
52.130339455994545  30  re.sub(r'[\W]+', '', generate_test_string(i))
50.061149017004940  30  pattern_single.sub('', generate_test_string(i))
49.366573111998150  30  pattern_repeat.sub('', generate_test_string(i))
46.649754120997386  30  generate_test_string(i).translate(translation_tb)
63.107938601999194  40  ''.join(c for c in generate_test_string(i) if c.isalnum())
65.116287978999030  40  ''.join(filter(str.isalnum, generate_test_string(i)))
71.477421126997800  40  re.sub(r'[\W]', '', generate_test_string(i))
66.027950693998720  40  re.sub(r'[\W]+', '', generate_test_string(i))
63.315361931003280  40  pattern_single.sub('', generate_test_string(i))
62.342320287003530  40  pattern_repeat.sub('', generate_test_string(i))
58.249303059004890  40  generate_test_string(i).translate(translation_tb)
73.810345625002810  50  ''.join(c for c in generate_test_string(i) if c.isalnum())
72.593953348005020  50  ''.join(filter(str.isalnum, generate_test_string(i)))
76.048324580995540  50  re.sub(r'[\W]', '', generate_test_string(i))
75.106637657001560  50  re.sub(r'[\W]+', '', generate_test_string(i))
74.681338128997600  50  pattern_single.sub('', generate_test_string(i))
72.430461594005460  50  pattern_repeat.sub('', generate_test_string(i))
69.394243567003290  50  generate_test_string(i).translate(translation_tb)

str.maketrans & str.translate is fastest, but includes all non-ASCII characters. re.compile & pattern.sub is slower, but is somehow faster than ''.join & filter.

Serializing enums with Jackson

Here is my solution. I want transform enum to {id: ..., name: ...} form.

With Jackson 1.x:

pom.xml:

<properties>
    <jackson.version>1.9.13</jackson.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>${jackson.version}</version>
    </dependency>
</dependencies>

Rule.java:

import org.codehaus.jackson.map.annotate.JsonSerialize;
import my.NamedEnumJsonSerializer;
import my.NamedEnum;

@Entity
@Table(name = "RULE")
public class Rule {
    @Column(name = "STATUS", nullable = false, updatable = true)
    @Enumerated(EnumType.STRING)
    @JsonSerialize(using = NamedEnumJsonSerializer.class)
    private Status status;
    public Status getStatus() { return status; }
    public void setStatus(Status status) { this.status = status; }

    public static enum Status implements NamedEnum {
        OPEN("open rule"),
        CLOSED("closed rule"),
        WORKING("rule in work");

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

NamedEnum.java:

package my;

public interface NamedEnum {
    String name();
    String getName();
}

NamedEnumJsonSerializer.java:

package my;

import my.NamedEnum;
import java.io.IOException;
import java.util.*;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

public class NamedEnumJsonSerializer extends JsonSerializer<NamedEnum> {
    @Override
    public void serialize(NamedEnum value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        Map<String, String> map = new HashMap<>();
        map.put("id", value.name());
        map.put("name", value.getName());
        jgen.writeObject(map);
    }
}

With Jackson 2.x:

pom.xml:

<properties>
    <jackson.version>2.3.3</jackson.version>
</properties>

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
</dependencies>

Rule.java:

import com.fasterxml.jackson.annotation.JsonFormat;

@Entity
@Table(name = "RULE")
public class Rule {
    @Column(name = "STATUS", nullable = false, updatable = true)
    @Enumerated(EnumType.STRING)
    private Status status;
    public Status getStatus() { return status; }
    public void setStatus(Status status) { this.status = status; }

    @JsonFormat(shape = JsonFormat.Shape.OBJECT)
    public static enum Status {
        OPEN("open rule"),
        CLOSED("closed rule"),
        WORKING("rule in work");

        private String name;
        Status(String name) { this.name = name; }
        public String getName() { return this.name; }
        public String getId() { return this.name(); }
    };
}

Rule.Status.CLOSED translated to {id: "CLOSED", name: "closed rule"}.

How to get a list of installed Jenkins plugins with name and version pair

I think these are not good enough answer(s)... many involve a couple of extra under-the-hood steps. Here's how I did it.

sudo apt-get install jq

...because the JSON output needs to be consumed after you call the API.

#!/bin/bash
server_addr = 'jenkins'
server_port = '8080'

curl -s -k "http://${server_addr}:${server_port}/pluginManager/api/json?depth=1" \
  | jq '.plugins[]|{shortName, version,longName,url}' -c | sort \
  > plugin-list

echo "dude, here's your list: "
cat plugin-list

how to select rows based on distinct values of A COLUMN only

Try this - you need a CTE (Common Table Expression) that partitions (groups) your data by distinct e-mail address, and sorts each group by ID - smallest first. Then you just select the first entry for each group - that should give you what you're looking for:

;WITH DistinctMails AS
(
    SELECT ID, MailID, EMailAddress, NAME,
        ROW_NUMBER() OVER(PARTITION BY EMailAddress ORDER BY ID) AS 'RowNum'
    FROM dbo.YourMailTable
)
SELECT *
FROM DistinctMails
WHERE RowNum = 1

This works on SQL Server 2005 and newer (you didn't mention what version you're using...)

Sublime Text 2 multiple line edit

Worked for me on OS X + Sublime build 3083:

OPTION (ALT) + select lines

Scatter plots in Pandas/Pyplot: How to plot by category

You can use scatter for this, but that requires having numerical values for your key1, and you won't have a legend, as you noticed.

It's better to just use plot for discrete categories like this. For example:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

groups = df.groupby('label')

# Plot
fig, ax = plt.subplots()
ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling
for name, group in groups:
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend()

plt.show()

enter image description here

If you'd like things to look like the default pandas style, then just update the rcParams with the pandas stylesheet and use its color generator. (I'm also tweaking the legend slightly):

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

groups = df.groupby('label')

# Plot
plt.rcParams.update(pd.tools.plotting.mpl_stylesheet)
colors = pd.tools.plotting._get_standard_colors(len(groups), color_type='random')

fig, ax = plt.subplots()
ax.set_color_cycle(colors)
ax.margins(0.05)
for name, group in groups:
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend(numpoints=1, loc='upper left')

plt.show()

enter image description here

MVC controller : get JSON object from HTTP body?

you can get the json string as a param of your ActionResult and afterwards serialize it using JSON.Net

HERE an example is being shown


in order to receive it in the serialized form as a param of the controller action you must either write a custom model binder or a Action filter (OnActionExecuting) so that the json string is serialized into the model of your liking and is available inside the controller body for use.


HERE is an implementation using the dynamic object

Deleting Row in SQLite in Android

if you are using SQLiteDatabase then there is a delete method

Definition of Delete

int delete (String table, String whereClause, String[] whereArgs)

Example Implementation

Now we can write a method called delete with argument as name

public void delete(String value) {
    db.delete(DATABASE_TABLE, KEY_NAME + "=?", new String[]{String.valueOf(value)});
}

if you want to delete all records then just pass null to the above method,

public void delete() {
    db.delete(DATABASE_TABLE, null, null);
}

Source Of Information

How to post data using HttpClient?

Use UploadStringAsync method:

WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
    if (e.Error != null)
    {
        //handle your error here
    }
    else
    {
        //post was successful, so do what you need to do here
    }
};

webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);     

Radio button checked event handling

Update in 2017: Hey. This is a terrible answer. Don't use it. Back in the old days this type of jQuery use was common. And it probably worked back then. Just read it, realize it's terrible, then move on (or downvote or, whatever) to one of the other answers that are better for today's jQuery.


$("input[type=radio]").change(function(){
    alert( $("input[type=radio][name="+ this.name + "]").val() );
});

How to convert an xml string to a dictionary?

This lightweight version, while not configurable, is pretty easy to tailor as needed, and works in old pythons. Also it is rigid - meaning the results are the same regardless of the existence of attributes.

import xml.etree.ElementTree as ET

from copy import copy

def dictify(r,root=True):
    if root:
        return {r.tag : dictify(r, False)}
    d=copy(r.attrib)
    if r.text:
        d["_text"]=r.text
    for x in r.findall("./*"):
        if x.tag not in d:
            d[x.tag]=[]
        d[x.tag].append(dictify(x,False))
    return d

So:

root = ET.fromstring("<erik><a x='1'>v</a><a y='2'>w</a></erik>")

dictify(root)

Results in:

{'erik': {'a': [{'x': '1', '_text': 'v'}, {'y': '2', '_text': 'w'}]}}

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

Jackson marshalling/unmarshalling requires following jar files of same version.

  1. jackson-core

  2. jackson-databind

  3. jackson-annotations

    Make sure that you have added all these with same version in your classpath. In your case jackson-annotations is missing in classpath.

Unzip files (7-zip) via cmd command

In Windows 10 I had to run the batch file as an administrator.

Create excel ranges using column numbers in vba?

Function fncToLetters(vintCol As Integer) As String

        Dim mstrDigits As String

    ' Convert a positive number n to its digit representation in base 26.
    mstrDigits = ""
    Do While vintCol > 0
        mstrDigits = Chr(((vintCol - 1) Mod 26) + 65) & mstrDigits
        vintCol = Int((vintCol - 1) / 26)
    Loop

    fncToLetters = mstrDigits

End Function

Simple way to calculate median with MySQL

create table med(id integer);
insert into med(id) values(1);
insert into med(id) values(2);
insert into med(id) values(3);
insert into med(id) values(4);
insert into med(id) values(5);
insert into med(id) values(6);

select (MIN(count)+MAX(count))/2 from 
(select case when (select count(*) from 
med A where A.id<B.id)=(select count(*)/2 from med) OR 
(select count(*) from med A where A.id>B.id)=(select count(*)/2 
from med) then cast(B.id as float)end as count from med B) C;

 ?column? 
----------
  3.5
(1 row)

OR

select cast(avg(id) as float) from 
(select t1.id from med t1 JOIN med t2 on t1.id!= t2.id 
group by t1.id having ABS(SUM(SIGN(t1.id-t2.id)))=1) A;

The type arguments for method cannot be inferred from the usage

As I mentioned in my comment, I think the reason why this doesn't work is because the compiler can't infer types based on generic constraints.

Below is an alternative implementation that will compile. I've revised the IAccess interface to only have the T generic type parameter.

interface ISignatur<T>
{
    Type Type { get; }
}

interface IAccess<T>
{
    ISignatur<T> Signature { get; }
    T Value { get; set; }
}

class Signatur : ISignatur<bool>
{
    public Type Type
    {
        get { return typeof(bool); }
    }
}

class ServiceGate
{
    public IAccess<T> Get<T>(ISignatur<T> sig)
    {
        throw new NotImplementedException();
    }
}

static class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        var access = service.Get(new Signatur());
    }
}

How to explain callbacks in plain english? How are they different from calling one function from another function?

A callback is a function that will be called by a second function. This second function doesn't know in advance what function it will call. So the identity of the callback function is stored somewhere, or passed to the second function as a parameter. This "identity," depending on the programming language, might be the address of the callback, or some other sort of pointer, or it might be the name of the function. The principal is the same, we store or pass some information that unambiguously identifies the function.

When the time comes, the second function can call the callback, supplying parameters depending on the circumstances at that moment. It might even choose the callback from a set of possible callbacks. The programming language must provide some kind of syntax to allow the second function to call the callback, knowing its "identity."

This mechanism has a great many possible uses. With callbacks, the designer of a function can let it be customized by having it call whatever callbacks are provided. For example, a sorting function might take a callback as a parameter, and this callback might be a function for comparing two elements to decide which one comes first.

By the way, depending on the programming language, the word "function" in the above discussion might be replaced by "block," "closure," "lambda," etc.

JavaScript variable assignments from tuples

As an update to The Minister's answer, you can now do this with es2015:

function Tuple(...args) {
  args.forEach((val, idx) => 
    Object.defineProperty(this, "item"+idx, { get: () => val })
  )
}


var t = new Tuple("a", 123)
console.log(t.item0) // "a"
t.item0 = "b"
console.log(t.item0) // "a"

https://jsbin.com/fubaluwimo/edit?js,console

java - path to trustStore - set property doesn't work?

Both

-Djavax.net.ssl.trustStore=path/to/trustStore.jks

and

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");

do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore in javax.net.ssl.trustStore.

Best way to check if column returns a null value (from database to .net application)

If we are using EF and reading the database element in while loop then,

   using( var idr = connection, SP.......)
   {
       while(idr.read())
       {
          if(String.IsNullOrEmpty(idr["ColumnNameFromDB"].ToString())
          //do something
       }
   }