Programs & Examples On #Android adapter

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view.

android - listview get item view by position

You can get only visible View from ListView because row views in ListView are reuseable. If you use mListView.getChildAt(0) you get first visible view. This view is associated with item from adapter at position mListView.getFirstVisiblePosition().

How to update/refresh specific item in RecyclerView

I think I have an Idea on how to deal with this. Updating is the same as deleting and replacing at the exact position. So I first remove the item from that position using the code below:

public void removeItem(int position){
    mData.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, mData.size());
}

and then I would add the item at that particular position as shown below:

public void addItem(int position, Landscape landscape){
    mData.add(position, landscape);
    notifyItemInserted(position);
    notifyItemRangeChanged(position, mData.size());
}

I'm trying to implement this now. I would give you a feedback when I'm through!

Best way to update data with a RecyclerView adapter

RecyclerView's Adapter doesn't come with many methods otherwise available in ListView's adapter. But your swap can be implemented quite simply as:

class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
   List<Data> data;
   ...

    public void swap(ArrayList<Data> datas)
    {
        data.clear();
        data.addAll(datas);
        notifyDataSetChanged();     
    }
}

Also there is a difference between

list.clear();
list.add(data);

and

list = newList;

The first is reusing the same list object. The other is dereferencing and referencing the list. The old list object which can no longer be reached will be garbage collected but not without first piling up heap memory. This would be the same as initializing new adapter everytime you want to swap data.

How to customize listview using baseadapter

Create your own BaseAdapter class and use it as following.

 public class NotificationScreen extends Activity
{

@Override
protected void onCreate_Impl(Bundle savedInstanceState)
{
    setContentView(R.layout.notification_screen);

    ListView notificationList = (ListView) findViewById(R.id.notification_list);
    NotiFicationListAdapter notiFicationListAdapter = new NotiFicationListAdapter();
    notificationList.setAdapter(notiFicationListAdapter);

    homeButton = (Button) findViewById(R.id.home_button);

}

}

Make your own BaseAdapter class and its separate xml file.

public class NotiFicationListAdapter  extends BaseAdapter
{
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;


public NotiFicationListAdapter(ArrayList data)
{
this.data=data;        
    inflater =(LayoutInflater)baseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}



public int getCount() 
{
 return data.size();
}



public Object getItem(int position) 
{
 return position;
}



public long getItemId(int position) 
{
    return position;
}



public View getView(int position, View convertView, ViewGroup parent) 
{
View vi=convertView;
    if(convertView==null)

    vi = inflater.inflate(R.layout.notification_list_item, null);

    ImageView compleatImageView=(ImageView)vi.findViewById(R.id.complet_image);
    TextView name = (TextView)vi.findViewById(R.id.game_name); // name
    TextView email_id = (TextView)vi.findViewById(R.id.e_mail_id); // email ID
    TextView notification_message = (TextView)vi.findViewById(R.id.notification_message); // notification message



    compleatImageView.setBackgroundResource(R.id.address_book);
    name.setText(data.getIndex(position));
    email_id.setText(data.getIndex(position));
    notification_message.setTextdata.getIndex(position));

    return vi;
}

  }

BaseAdapter xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/inner_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_weight="4"
android:background="@drawable/list_view_frame"
android:gravity="center_vertical"
android:padding="5dp" >

<TextView
    android:id="@+id/game_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Game name"
    android:textColor="#FFFFFF"
    android:textSize="15dip"
    android:textStyle="bold"
    android:typeface="sans" />

<TextView
    android:id="@+id/e_mail_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_marginTop="1dip"
    android:text="E-Mail Id"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />

<TextView
    android:id="@+id/notification_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_toRightOf="@id/e_mail_id"
    android:paddingLeft="5dp"
    android:text="Notification message"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />



<ImageView
    android:id="@+id/complet_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginBottom="30dp"
    android:layout_marginRight="10dp"
    android:src="@drawable/complete_tag"
    android:visibility="invisible" />

</RelativeLayout>

Change it accordingly and use.

Android: how to refresh ListView contents?

In my understanding, if you want to refresh ListView immediately when data has changed, you should call notifyDataSetChanged() in RunOnUiThread().

private void updateData() {
    List<Data> newData = getYourNewData();
    mAdapter.setList(yourNewList);

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
                mAdapter.notifyDataSetChanged();
        }
    });
}

How to execute INSERT statement using JdbcTemplate class from Spring Framework

If you are planning to use JdbcTemplate in multiple locations, it would be a good idea to create a Spring Bean for it.

Using Java Config it would be:

@Configuration
public class DBConfig {

   @Bean
   public DataSource dataSource() {
      //create a data source
   }

   @Bean
   public JdbcTemplate jdbcTemplate() {
      return new JdbcTemplate(dataSource());
   }

   @Bean
   public TransactionManager transactionManager() {
      return new DataSourceTransactionManager(dataSource());
   }

}

Then a repository that uses that JdbcTemplate could be:

@Repository
public class JdbcSomeRepository implements SomeRepository {

   private final JdbcTemplate jdbcTemplate ;

   @Autowired
   public JdbcSomeRepository(JdbcTemplate jdbcTemplate) {
      this.jdbcTemplate = jdbcTemplate;
   } 

   @Override
   @Transactional 
   public int someUpdate(SomeType someValue, SomeOtherType someOtherValue) {
      return jdbcTemplate.update("INSERT INTO SomeTable(column1, column2) VALUES(?,?)", someValue, someOtherValue)
   }
}

The update method from JdbcTemplate that I have used can be found here.

How to create a dynamic array of integers

int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

Don't forget to delete every array you allocate with new.

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

TL;DR. You can get around this by expressing your queries as MyModel::query()->find(10); instead of MyModel::find(10);.

To the best of my knowledge, starting PhpStorm 2017.2 code inspection fails for methods such as MyModel::where(), MyModel::find(), etc (check this thread). This could get quite annoying, when you try let's say to use PhpStorm's Git integration before committing your code, PhpStorm won't stop complaining about these static method call warnings.

One elegant way (IMOO) to get around this is to explicitly call ::query() wherever it makes sense to. This will let you benefit from a free auto-completion and a nice query formatting.

Examples

Snippet where inspection complains about static method calls

$myModel = MyModel::find(10); // static call complaint

// another poorly formatted query with code inspection complaints
$myFilteredModels = MyModel::where('is_beautiful', true)
    ->where('is_not_smart', false)
    ->get();

Well formatted code with no complaints

$myModel = MyModel::query()->find(10);

// a nicely formatted query with no complaints
$myFilteredModels = MyModel::query()
    ->where('is_beautiful', true)
    ->where('is_not_smart', false)
    ->get();

MySQL - ignore insert error: duplicate entry

Try creating a duplicate table, preferably a temporary table, without the unique constraint and do your bulk load into that table. Then select only the unique (DISTINCT) items from the temporary table and insert into the target table.

Convert a row of a data frame to vector

Here is a dplyr based option:

newV = df %>% slice(1) %>% unlist(use.names = FALSE)

# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()

ImportError: No module named 'Tkinter'

You might need to install for your specific version, I have known cases where this was needed when I was using many versions of python and one version in a virtualenv using for example python 3.7 was not importing tkinter I would have to install it for that version specifically.

For example

sudo apt-get install python3.7-tk 

No idea why - but this has occured.

Delete all files of specific type (extension) recursively down a directory using a batch file

If you are trying to delete certain .extensions in the C: drive use this cmd:

del /s c:\*.blaawbg

I had a customer that got a encryption virus and i needed to find all junk files and delete them.

How to SUM parts of a column which have same text value in different column in the same row

A PivotTable might suit, though I am not quite certain of the layout of your data:

SO19669814 example

The bold numbers (one of each pair of duplicates) need not be shown as the field does not have to be subtotalled eg:

SO19669814 second example

Docker - Cannot remove dead container

Most likely, an error occurred when the daemon attempted to cleanup the container, and he is now stuck in this "zombie" state.

I'm afraid your only option here is to manually clean it up:

$ sudo rm -rf /var/lib/docker/<storage_driver>/11667ef16239.../

Where <storage_driver> is the name of your driver (aufs, overlay, btrfs, or devicemapper).

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

I had the same issue, just copied the App Config file from the project that contained the DBContext to my test project

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

How to break lines at a specific character in Notepad++?

Let's assume ], is the character where we wanted to break at

  1. Open notePad++
  2. Open Find window Ctrl+F
  3. Switch to Replace Tab
  4. Choose Search Mode to Extended
  5. Type ], in Find What field
  6. Type \nin Replace with field
  7. Hit Replace All
  8. Boom

Accessing session from TWIG template

A simple trick is to define the $_SESSION array as a global variable. For that, edit the core.php file in the extension folder by adding this function :

public function getGlobals() {
    return array(
        'session'   => $_SESSION,
    ) ;
}

Then, you'll be able to acces any session variable as :

{{ session.username }}

if you want to access to

$_SESSION['username']

month name to month number and vice versa in python

def month_num2abbr(month):
    month = int(month)
    import calendar
    months_abbr = {month: index for index, month in enumerate(calendar.month_abbr) if month}
    for abbr, month_num in months_abbr.items():
        if month_num==month:
            return abbr
    return False

print(month_num2abbr(7))

Landscape printing from HTML

I tried Denis's answer and hit some problems (portrait pages didn't print properly after going after landscape pages), so here is my solution:

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  background: #CCCCCC;_x000D_
}_x000D_
_x000D_
div.page {_x000D_
  margin: 10px auto;_x000D_
  border: solid 1px black;_x000D_
  display: block;_x000D_
  page-break-after: always;_x000D_
  width: 209mm;_x000D_
  height: 296mm;_x000D_
  overflow: hidden;_x000D_
  background: white;_x000D_
}_x000D_
_x000D_
div.landscape-parent {_x000D_
  width: 296mm;_x000D_
  height: 209mm;_x000D_
}_x000D_
_x000D_
div.landscape {_x000D_
  width: 296mm;_x000D_
  height: 209mm;_x000D_
}_x000D_
_x000D_
div.content {_x000D_
  padding: 10mm;_x000D_
}_x000D_
_x000D_
body,_x000D_
div,_x000D_
td {_x000D_
  font-size: 13px;_x000D_
  font-family: Verdana;_x000D_
}_x000D_
_x000D_
@media print {_x000D_
  body {_x000D_
    background: none;_x000D_
  }_x000D_
  div.page {_x000D_
    width: 209mm;_x000D_
    height: 296mm;_x000D_
  }_x000D_
  div.landscape {_x000D_
    transform: rotate(270deg) translate(-296mm, 0);_x000D_
    transform-origin: 0 0;_x000D_
  }_x000D_
  div.portrait,_x000D_
  div.landscape,_x000D_
  div.page {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    border: none;_x000D_
    background: none;_x000D_
  }_x000D_
}
_x000D_
<div class="page">_x000D_
  <div class="content">_x000D_
    First page in Portrait mode_x000D_
  </div>_x000D_
</div>_x000D_
<div class="page landscape-parent">_x000D_
  <div class="landscape">_x000D_
    <div class="content">_x000D_
      Second page in Landscape mode (correctly shows horizontally in browser and prints rotated in printer)_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="page">_x000D_
  <div class="content">_x000D_
    Third page in Portrait mode_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Wait .5 seconds before continuing code VB.net

In web application a timer will be the best approach.

Just fyi, in desktop application I use this instead, inside an async method.

... 
Await Task.Run(Sub()
    System.Threading.Thread.Sleep(5000)
End Sub)
...

It work for me, importantly it doesn't freeze entire screen. But again this is on desktop, i try in web application it does freeze.

How to check if current thread is not main thread

you can verify it in android ddms logcat where process id will be same but thread id will be different.

How can I copy the output of a command directly into my clipboard?

Based on previous posts, I ended up with the following light-weigh alias solution that can be added to .bashrc:

if [ -n "$(type -P xclip)" ]
then
  alias xclip='xclip -selection clipboard'
  alias clipboard='if [ -p /dev/stdin ]; then xclip -in; fi; xclip -out'
fi

Examples:

# Copy
$ date | clipboard
Sat Dec 29 14:12:57 PST 2018

# Paste
$ date
Sat Dec 29 14:12:57 PST 2018

# Chain
$ date | clipboard | wc
   1       6      29

How to serialize SqlAlchemy result to JSON?

Even though it's a old post, Maybe I didn't answer the question above, but I want to talk about my serialization, at least it works for me.

I use FastAPI,SqlAlchemy and MySQL, but I don't use orm model;

# from sqlalchemy import create_engine
# from sqlalchemy.orm import sessionmaker
# engine = create_engine(config.SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
# SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Serialization code



import decimal
import datetime


def alchemy_encoder(obj):
    """JSON encoder function for SQLAlchemy special classes."""
    if isinstance(obj, datetime.date):
        return obj.strftime("%Y-%m-%d %H:%M:%S")
    elif isinstance(obj, decimal.Decimal):
        return float(obj)

import json
from sqlalchemy import text

# db is SessionLocal() object 

app_sql = 'SELECT * FROM app_info ORDER BY app_id LIMIT :page,:page_size'

# The next two are the parameters passed in
page = 1
page_size = 10

# execute sql and return a <class 'sqlalchemy.engine.result.ResultProxy'> object
app_list = db.execute(text(app_sql), {'page': page, 'page_size': page_size})

# serialize
res = json.loads(json.dumps([dict(r) for r in app_list], default=alchemy_encoder))

If it doesn't work, please ignore my answer. I refer to it here

https://codeandlife.com/2014/12/07/sqlalchemy-results-to-json-the-easy-way/

Adding gif image in an ImageView in android

This is what worked for me:

In your build.gradle (project) write mavenCentral() in the buildscript{} and allprojects {}. It should look like this:

buildscript {
    repositories {
        jcenter()
        **mavenCentral()**
    }
//more code ...
}
allprojects {
    repositories {
        jcenter()
        **mavenCentral()**
    }
}

Then, in build.gradle(module) add in dependencies{} this snippet:

compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.4'

it should look like this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'
    **compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.4'**
}

Put your .gif image in your drawable folder. Now go to app > res > layout > activity_main.xml and add this snipped for your .gif:

<pl.droidsonroids.gif.GifImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/YOUR_GIF_IMAGE"
    android:background="#000000" //for black background
    />

And you're done :)

Helpful links: https://github.com/koral--/android-gif-drawable

https://www.youtube.com/watch?v=EOFY0cwNjuk

Hope this helps.

How to create two columns on a web page?

The simple and best solution is to use tables for layouts. You're doing it right. There are a number of reasons tables are better.

  • They perform better than CSS
  • They work on all browsers without any fuss
  • You can debug them easily with the border=1 attribute

How to pass a variable to the SelectCommand of a SqlDataSource?

we had to do this so often that I made what I called a DelegateParameter class

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Reflection;

namespace MyControls
{
    public delegate object EvaluateParameterEventHandler(object sender, EventArgs e);

    public class DelegateParameter : Parameter
    {
        private System.Web.UI.Control _parent;
        public System.Web.UI.Control Parent
        {
            get { return _parent; }
            set { _parent = value; }
        }

        private event EvaluateParameterEventHandler _evaluateParameter;
        public event EvaluateParameterEventHandler EvaluateParameter
        {
            add { _evaluateParameter += value; }
            remove { _evaluateParameter -= value; }
        }

        protected override object Evaluate(System.Web.HttpContext context, System.Web.UI.Control control)
        {
            return _evaluateParameter(this, EventArgs.Empty);
        }
    }
}

put this class either in your app_code (remove the namespace if you put it there) or in your custom control assembly. After the control is registered in the web.config you should be able to do this

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:itematConnectionString %>"
    SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC">
    <SelectParameters>
    <asp:DelegateParameter Name="userId"  DbType="Guid" OnEvaluate="GetUserID" />
    </SelectParameters>
</asp:SqlDataSource>

then in the code behind you implement the GetUserID anyway you like.

protected object GetUserID(object sender, EventArgs e)
{
  return userId;
}

Python list sort in descending order

In one line, using a lambda:

timestamps.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)

Passing a function to list.sort:

def foo(x):
    return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]

timestamps.sort(key=foo, reverse=True)

How to get element-wise matrix multiplication (Hadamard product) in numpy?

import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])

x*y
Out: 
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit x*y
1000000 loops, best of 3: 421 ns per loop

np.multiply(x,y)
Out: 
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop

Both np.multiply and * would yield element wise multiplication known as the Hadamard Product

%timeit is ipython magic

Targeting only Firefox with CSS

Here is some browser hacks for targeting only the Firefox browser,

Using selector hacks.

_:-moz-tree-row(hover), .selector {}

JavaScript Hacks

var isFF = !!window.sidebar;

var isFF = 'MozAppearance' in document.documentElement.style;

var isFF = !!navigator.userAgent.match(/firefox/i);

Media Query Hacks

This is gonna work on, Firefox 3.6 and Later

@media screen and (-moz-images-in-menus:0) {}

If you need more information,Please visit browserhacks

Create Windows service from executable

Same as Sergii Pozharov's answer, but with a PowerShell cmdlet:

New-Service -Name "MyService" -BinaryPathName "C:\Path\to\myservice.exe"

See New-Service for more customization.

This will only work for executables that already implement the Windows Services API.

run a python script in terminal without the python command

You need to use a hashbang. Add it to the first line of your python script.

#! <full path of python interpreter>

Then change the file permissions, and add the executing permission.

chmod +x <filename>

And finally execute it using

./<filename>

If its in the current directory,

How can I get a favicon to show up in my django app?

The best solution is to override the Django base.html template. Make another base.html template under admin directory. Make an admin directory first if it does not exist. app/admin/base.html.

Add {% block extrahead %} to the overriding template.

{% extends 'admin/base.html' %}
{% load staticfiles %}
{% block javascripts %}
    {{ block.super }}
<script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>

{% endblock %}

{% block extrahead %}
    <link rel="shortcut icon" href="{% static 'app/img/favicon.ico'  %}" />
{% endblock %}
{% block stylesheets %}

    {{ block.super }}
{% endblock %}

Google maps API V3 - multiple markers on exact same spot

@Ignatius most excellent answer, updated to work with v2.0.7 of MarkerClustererPlus.

  1. Add a prototype click method in the MarkerClusterer class, like so - we will override this later in the map initialize() function:

    // BEGIN MODIFICATION (around line 715)
    MarkerClusterer.prototype.onClick = function() { 
        return true; 
    };
    // END MODIFICATION
    
  2. In the ClusterIcon class, add the following code AFTER the click/clusterclick trigger:

    // EXISTING CODE (around line 143)
    google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
    google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
    
    // BEGIN MODIFICATION
    var zoom = mc.getMap().getZoom();
    // Trying to pull this dynamically made the more zoomed in clusters not render
    // when then kind of made this useless. -NNC @ BNB
    // var maxZoom = mc.getMaxZoom();
    var maxZoom = 15;
    // if we have reached the maxZoom and there is more than 1 marker in this cluster
    // use our onClick method to popup a list of options
    if (zoom >= maxZoom && cClusterIcon.cluster_.markers_.length > 1) {
        return mc.onClick(cClusterIcon);
    }
    // END MODIFICATION
    
  3. Then, in your initialize() function where you initialize the map and declare your MarkerClusterer object:

    markerCluster = new MarkerClusterer(map, markers);
    // onClick OVERRIDE
    markerCluster.onClick = function(clickedClusterIcon) { 
      return multiChoice(clickedClusterIcon.cluster_); 
    }
    

    Where multiChoice() is YOUR (yet to be written) function to popup an InfoWindow with a list of options to select from. Note that the markerClusterer object is passed to your function, because you will need this to determine how many markers there are in that cluster. For example:

    function multiChoice(clickedCluster) {
      if (clickedCluster.getMarkers().length > 1)
      {
        // var markers = clickedCluster.getMarkers();
        // do something creative!
        return false;
      }
      return true;
    };
    

What is tempuri.org?

Probably to guarantee that public webservices will be unique.

It always makes me think of delicious deep fried treats...

How to get unique values in an array

If you want to leave the original array intact,

you need a second array to contain the uniqe elements of the first-

Most browsers have Array.prototype.filter:

var unique= array1.filter(function(itm, i){
    return array1.indexOf(itm)== i; 
    // returns true for only the first instance of itm
});


//if you need a 'shim':
Array.prototype.filter= Array.prototype.filter || function(fun, scope){
    var T= this, A= [], i= 0, itm, L= T.length;
    if(typeof fun== 'function'){
        while(i<L){
            if(i in T){
                itm= T[i];
                if(fun.call(scope, itm, i, T)) A[A.length]= itm;
            }
            ++i;
        }
    }
    return A;
}
 Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
        if(!i || typeof i!= 'number') i= 0;
        var L= this.length;
        while(i<L){
            if(this[i]=== what) return i;
            ++i;
        }
        return -1;
    }

Script to Change Row Color when a cell changes text

user2532030's answer is the correct and most simple answer.

I just want to add, that in the case, where the value of the determining cell is not suitable for a RegEx-match, I found the following syntax to work the same, only with numerical values, relations et.c.:

[Custom formula is]
=$B$2:$B = "Complete"
Range: A2:Z1000

If column 2 of any row (row 2 in script, but the leading $ means, this could be any row) textually equals "Complete", do X for the Range of the entire sheet (excluding header row (i.e. starting from A2 instead of A1)).

But obviously, this method allows also for numerical operations (even though this does not apply for op's question), like:

=$B$2:$B > $C$2:$C

So, do stuff, if the value of col B in any row is higher than col C value.

One last thing: Most likely, this applies only to me, but I was stupid enough to repeatedly forget to choose Custom formula is in the drop-down, leaving it at Text contains. Obviously, this won't float...

What's the fastest way to convert String to Number in JavaScript?

I find that num * 1 is simple, clear, and works for integers and floats...

mysql - move rows from one table to another

INSERT INTO Persons_Table (person_id, person_name,person_email)
      SELECT person_id, customer_name, customer_email
      FROM customer_table
      ORDER BY `person_id` DESC LIMIT 0, 15 
      WHERE "insert your where clause here";
DELETE FROM customer_table
      WHERE "repeat your where clause here";

You can also use ORDER BY, LIMIT and ASC/DESC to limit and select the specific column that you want to move.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

The page is not found cause the associated controller doesn't exit. Just create the specific Controller. If you try to show the home page, and use Visual Studio 2015, follow this steps:

  1. Right click on Controller folder, and then select Add > Controller;
  2. Select MVC 5 Controller - Empty;
  3. Click in Add;
  4. Put HomeController for the controller name;
  5. Build the project and after Run your project again

I hope this help

How to import csv file in PHP?

The simplest way I know ( str_getcsv ), it will import a CSV file into an array.

$csv = array_map('str_getcsv', file('data.csv'));

Calculating frames per second in a game

A much better system than using a large array of old framerates is to just do something like this:

new_fps = old_fps * 0.99 + new_fps * 0.01

This method uses far less memory, requires far less code, and places more importance upon recent framerates than old framerates while still smoothing the effects of sudden framerate changes.

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

It is very likely that the pickled file is empty.

It is surprisingly easy to overwrite a pickle file if you're copying and pasting code.

For example the following writes a pickle file:

pickle.dump(df,open('df.p','wb'))

And if you copied this code to reopen it, but forgot to change 'wb' to 'rb' then you would overwrite the file:

df=pickle.load(open('df.p','wb'))

The correct syntax is

df=pickle.load(open('df.p','rb'))

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

What is Domain Driven Design?

Domain Driven Design is a methodology and process prescription for the development of complex systems whose focus is mapping activities, tasks, events, and data within a problem domain into the technology artifacts of a solution domain.

The emphasis of Domain Driven Design is to understand the problem domain in order to create an abstract model of the problem domain which can then be implemented in a particular set of technologies. Domain Driven Design as a methodology provides guidelines for how this model development and technology development can result in a system that meets the needs of the people using it while also being robust in the face of change in the problem domain.

The process side of Domain Driven Design involves the collaboration between domain experts, people who know the problem domain, and the design/architecture experts, people who know the solution domain. The idea is to have a shared model with shared language so that as people from these two different domains with their two different perspectives discuss the solution they are actually discussing a shared knowledge base with shared concepts.

The lack of a shared problem domain understanding between the people who need a particular system and the people who are designing and implementing the system seems to be a core impediment to successful projects. Domain Driven Design is a methodology to address this impediment.

It is more than having an object model. The focus is really about the shared communication and improving collaboration so that the actual needs within the problem domain can be discovered and an appropriate solution created to meet those needs.

Domain-Driven Design: The Good and The Challenging provides a brief overview with this comment:

DDD helps discover the top-level architecture and inform about the mechanics and dynamics of the domain that the software needs to replicate. Concretely, it means that a well done DDD analysis minimizes misunderstandings between domain experts and software architects, and it reduces the subsequent number of expensive requests for change. By splitting the domain complexity in smaller contexts, DDD avoids forcing project architects to design a bloated object model, which is where a lot of time is lost in working out implementation details — in part because the number of entities to deal with often grows beyond the size of conference-room white boards.

Also see this article Domain Driven Design for Services Architecture which provides a short example. The article provides the following thumbnail description of Domain Driven Design.

Domain Driven Design advocates modeling based on the reality of business as relevant to our use cases. As it is now getting older and hype level decreasing, many of us forget that the DDD approach really helps in understanding the problem at hand and design software towards the common understanding of the solution. When building applications, DDD talks about problems as domains and subdomains. It describes independent steps/areas of problems as bounded contexts, emphasizes a common language to talk about these problems, and adds many technical concepts, like entities, value objects and aggregate root rules to support the implementation.

Martin Fowler has written a number of articles in which Domain Driven Design as a methodology is mentioned. For instance this article, BoundedContext, provides an overview of the bounded context concept from Domain Driven Development.

In those younger days we were advised to build a unified model of the entire business, but DDD recognizes that we've learned that "total unification of the domain model for a large system will not be feasible or cost-effective" 1. So instead DDD divides up a large system into Bounded Contexts, each of which can have a unified model - essentially a way of structuring MultipleCanonicalModels.

Addressing localhost from a VirtualBox virtual machine

In Virtual Box

  1. Set your network to Bridge networking
  2. Go to Advanced set Promiscuous Mode: Allow All

Now the tricky bit is your localhost, if you are running from Node.js set the IP address to 0.0.0.0, then lookup your own IP address, for example cmd:ipconfig --> 10.0.1.3

Type that address in with the port number. And it will work.

How to set the matplotlib figure default size in ipython notebook?

In iPython 3.0.0, the inline backend needs to be configured in ipython_kernel_config.py. You need to manually add the c.InlineBackend.rc... line (as mentioned in Greg's answer). This will affect both the inline backend in the Qt console and the notebook.

Delaying function in swift

You can use GCD (in the example with a 10 second delay):

Swift 2

let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
    self.functionToCall()
})

Swift 3 and Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    self.functionToCall()
})

Swift 5 or Later

 DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
        //call any function
    }

How to add an item to an ArrayList in Kotlin?

If you have a MUTABLE collection:

val list = mutableListOf(1, 2, 3)
list += 4

If you have an IMMUTABLE collection:

var list = listOf(1, 2, 3)
list += 4

note that I use val for the mutable list to emphasize that the object is always the same, but its content changes.

In case of the immutable list, you have to make it var. A new object is created by the += operator with the additional value.

How to write multiple line string using Bash with variables?

I'm using Mac OS and to write multiple lines in a SH Script following code worked for me

#! /bin/bash
FILE_NAME="SomeRandomFile"

touch $FILE_NAME

echo """I wrote all
the  
stuff
here.
And to access a variable we can use
$FILE_NAME  

""" >> $FILE_NAME

cat $FILE_NAME

Please don't forget to assign chmod as required to the script file. I have used

chmod u+x myScriptFile.sh

How do I execute code AFTER a form has loaded?

You could use the "Shown" event: MSDN - Form.Shown

"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."

How can I use a search engine to search for special characters?

duckduckgo.com doesn't ignore special characters, at least if the whole string is between ""

https://duckduckgo.com/?q=%22*222%23%22

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

Here's what worked well for me:

find . -path '*/.svn' -prune -o -type f -exec gawk '/Dansk/{a=1}/Norsk/{b=1}/Svenska/{c=1}END{ if (a && b && c) print FILENAME }' {} \;
./path/to/file1.sh
./another/path/to/file2.txt
./blah/foo.php

If I just wanted to find .sh files with these three, then I could have used:

find . -path '*/.svn' -prune -o -type f -name "*.sh" -exec gawk '/Dansk/{a=1}/Norsk/{b=1}/Svenska/{c=1}END{ if (a && b && c) print FILENAME }' {} \;
./path/to/file1.sh

How do I display a ratio in Excel in the format A:B?

At work we only have Excel 2003 available and these two formulas seem to work perfectly for me:

=(ROUND(SUM(B3/C3),0))&":1"

or

=B3/GCD(B3,C3)&":"&C3/GCD(B3,C3)

Regular expression for excluding special characters

Do you really want to blacklist specific characters or rather whitelist the allowed charachters?

I assume that you actually want the latter. This is pretty simple (add any additional symbols to whitelist into the [\-] group):

^(?:\p{L}\p{M}*|[\-])*$

Edit: Optimized the pattern with the input from the comments

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

This error can be thrown when you import a different library for @Id than Javax.persistance.Id ; You might need to pay attention this case too

In my case I had

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import org.springframework.data.annotation.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;

when I change the code like this, it got worked

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import javax.persistence.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

ListBox with ItemTemplate (and ScrollBar!)

I pasted your code into test project, added about 20 items and I get usable scroll bars, no problem, and they work as expected. When I only add a couple items (such that scrolling is unnecessary) I get no usable scrollbar. Could this be the case? that you are not adding enough items?

If you remove the ScrollViewer.VerticalScrollBarVisibility="Visible" then the scroll bars only appear when you have need of them.

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

I'd create a cte and do an inner join. It's not efficient but it's convenient

with table as (
SELECT DATE, STATUS, TITLE, ROW_NUMBER() 
OVER (PARTITION BY DATE, STATUS,  TITLE ORDER BY QUANTITY ASC) AS Row_Num
 FROM TABLE)

select *

from table t
join select(
max(Row_Num) as Row_Num
,DATE
,STATUS
,TITLE
from table 
group by date, status, title) t2  
on t2.Row_Num = t.Row_Num and t2
and t2.date = t.date
and t2.title = t.title

How do I add a library path in cmake?

The simplest way of doing this would be to add

include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)

add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib

The modern CMake version that doesn't add the -I and -L flags to every compiler invocation would be to use imported libraries:

add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
  IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
  INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)

set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path

If setting the INTERFACE_INCLUDE_DIRECTORIES doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include). However, this no longer works with CMake 3.6 or newer.

Convert string to List<string> in one line?

If you already have a list and want to add values from a delimited string, you can use AddRange or InsertRange. For example:

existingList.AddRange(names.Split(','));

Comparing object properties in c#

If you are only comparing objects of the same type or further down the inheritance chain, why not specify the parameter as your base type, rather than object ?

Also do null checks on the parameter as well.

Furthermore I'd make use of 'var' just to make the code more readable (if its c#3 code)

Also, if the object has reference types as properties then you are just calling ToString() on them which doesn't really compare values. If ToString isn't overwridden then its just going to return the type name as a string which could return false-positives.

Exception of type 'System.OutOfMemoryException' was thrown.

If you're using IIS Express, select Show All Application from IIS Express in the task bar notification area, then select Stop All.

Now re-run your application.

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

Python: For each list element apply a function across the list

You can do this using list comprehensions and min() (Python 3.0 code):

>>> nums = [1,2,3,4,5]
>>> [(x,y) for x in nums for y in nums]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
>>> min(_, key=lambda pair: pair[0]/pair[1])
(1, 5)

Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do from __future__ import division so that 1/5 correctly equals 0.2 instead of 0.

How do I convert seconds to hours, minutes and seconds?

The solutions above will work if you're looking to convert a single value for "seconds since midnight" on a date to a datetime object or a string with HH:MM:SS, but I landed on this page because I wanted to do this on a whole dataframe column in pandas. If anyone else is wondering how to do this for more than a single value at a time, what ended up working for me was:

 mydate='2015-03-01'
 df['datetime'] = datetime.datetime(mydate) + \ 
                  pandas.to_timedelta(df['seconds_since_midnight'], 's')

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

Laravel Pagination links not including other GET parameters

Include This In Your View Page

 $users->appends(Input::except('page'))

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

There's a handy function, oidvectortypes, that makes this a lot easier.

SELECT format('%I.%I(%s)', ns.nspname, p.proname, oidvectortypes(p.proargtypes)) 
FROM pg_proc p INNER JOIN pg_namespace ns ON (p.pronamespace = ns.oid)
WHERE ns.nspname = 'my_namespace';

Credit to Leo Hsu and Regina Obe at Postgres Online for pointing out oidvectortypes. I wrote similar functions before, but used complex nested expressions that this function gets rid of the need for.

See related answer.


(edit in 2016)

Summarizing typical report options:

-- Compact:
SELECT format('%I.%I(%s)', ns.nspname, p.proname, oidvectortypes(p.proargtypes))

-- With result data type: 
SELECT format(
       '%I.%I(%s)=%s', 
       ns.nspname, p.proname, oidvectortypes(p.proargtypes),
       pg_get_function_result(p.oid)
)

-- With complete argument description: 
SELECT format('%I.%I(%s)', ns.nspname, p.proname, pg_get_function_arguments(p.oid))

-- ... and mixing it.

-- All with the same FROM clause:
FROM pg_proc p INNER JOIN pg_namespace ns ON (p.pronamespace = ns.oid)
WHERE ns.nspname = 'my_namespace';

NOTICE: use p.proname||'_'||p.oid AS specific_name to obtain unique names, or to JOIN with information_schema tables — see routines and parameters at @RuddZwolinski's answer.


The function's OID (see pg_catalog.pg_proc) and the function's specific_name (see information_schema.routines) are the main reference options to functions. Below, some useful functions in reporting and other contexts.

--- --- --- --- ---
--- Useful overloads: 

CREATE FUNCTION oidvectortypes(p_oid int) RETURNS text AS $$
    SELECT oidvectortypes(proargtypes) FROM pg_proc WHERE oid=$1;
$$ LANGUAGE SQL IMMUTABLE;

CREATE FUNCTION oidvectortypes(p_specific_name text) RETURNS text AS $$
    -- Extract OID from specific_name and use it in oidvectortypes(oid).
    SELECT oidvectortypes(proargtypes) 
    FROM pg_proc WHERE oid=regexp_replace($1, '^.+?([^_]+)$', '\1')::int;
$$ LANGUAGE SQL IMMUTABLE;

CREATE FUNCTION pg_get_function_arguments(p_specific_name text) RETURNS text AS $$
    -- Extract OID from specific_name and use it in pg_get_function_arguments.
    SELECT pg_get_function_arguments(regexp_replace($1, '^.+?([^_]+)$', '\1')::int)
$$ LANGUAGE SQL IMMUTABLE;

--- --- --- --- ---
--- User customization: 

CREATE FUNCTION pg_get_function_arguments2(p_specific_name text) RETURNS text AS $$
    -- Example of "special layout" version.
    SELECT trim(array_agg( op||'-'||dt )::text,'{}') 
    FROM (
        SELECT data_type::text as dt, ordinal_position as op
        FROM information_schema.parameters 
        WHERE specific_name = p_specific_name 
        ORDER BY ordinal_position
    ) t
$$ LANGUAGE SQL IMMUTABLE;

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

SOLVED

  1. Just run CMD as an administrator.
  2. Make sure your using the correct truststore password

Comparing chars in Java

You can just write your chars as Strings and use the equals method.

For Example:

String firstChar = "A";
String secondChar = "B";
String thirdChar = "C";

if (firstChar.equalsIgnoreCase(secondChar) ||
        (firstChar.equalsIgnoreCase(thirdChar))) // As many equals as you want
{
    System.out.println(firstChar + " is the same as " + secondChar);
} else {
    System.out.println(firstChar + " is different than " + secondChar);
}

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

This worked for me:

  1. Delete the originally created site.
  2. Recreate the site in IIS
  3. Clean solution
  4. Build solution

Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.

Print array elements on separate lines in Bash?

Using for:

for each in "${alpha[@]}"
do
  echo "$each"
done

Using history; note this will fail if your values contain !:

history -p "${alpha[@]}"

Using basename; note this will fail if your values contain /:

basename -a "${alpha[@]}"

Using shuf; note that results might not come out in order:

shuf -e "${alpha[@]}"

Iterating through a range of dates in Python

Here's code for a general date range function, similar to Ber's answer, but more flexible:

def count_timedelta(delta, step, seconds_in_interval):
    """Helper function for iterate.  Finds the number of intervals in the timedelta."""
    return int(delta.total_seconds() / (seconds_in_interval * step))


def range_dt(start, end, step=1, interval='day'):
    """Iterate over datetimes or dates, similar to builtin range."""
    intervals = functools.partial(count_timedelta, (end - start), step)

    if interval == 'week':
        for i in range(intervals(3600 * 24 * 7)):
            yield start + datetime.timedelta(weeks=i) * step

    elif interval == 'day':
        for i in range(intervals(3600 * 24)):
            yield start + datetime.timedelta(days=i) * step

    elif interval == 'hour':
        for i in range(intervals(3600)):
            yield start + datetime.timedelta(hours=i) * step

    elif interval == 'minute':
        for i in range(intervals(60)):
            yield start + datetime.timedelta(minutes=i) * step

    elif interval == 'second':
        for i in range(intervals(1)):
            yield start + datetime.timedelta(seconds=i) * step

    elif interval == 'millisecond':
        for i in range(intervals(1 / 1000)):
            yield start + datetime.timedelta(milliseconds=i) * step

    elif interval == 'microsecond':
        for i in range(intervals(1e-6)):
            yield start + datetime.timedelta(microseconds=i) * step

    else:
        raise AttributeError("Interval must be 'week', 'day', 'hour' 'second', \
            'microsecond' or 'millisecond'.")

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Where can I find the TypeScript version installed in Visual Studio?

You can run it in NuGet Package Manager Console in Visual Studio 2013.

How to read a .properties file which contains keys that have a period character using Shell script

I use simple grep inside function in bash script to receive properties from .properties file.

This properties file I use in two places - to setup dev environment and as application parameters.

I believe that grep may work slow in big loops but it solves my needs when I want to prepare dev environment.

Hope, someone will find this useful.

Example:

File: setup.sh

#!/bin/bash

ENV=${1:-dev}

function prop {
    grep "${1}" env/${ENV}.properties|cut -d'=' -f2
}

docker create \
    --name=myapp-storage \
    -p $(prop 'app.storage.address'):$(prop 'app.storage.port'):9000 \
    -h $(prop 'app.storage.host') \
    -e STORAGE_ACCESS_KEY="$(prop 'app.storage.access-key')" \
    -e STORAGE_SECRET_KEY="$(prop 'app.storage.secret-key')" \
    -e STORAGE_BUCKET="$(prop 'app.storage.bucket')" \
    -v "$(prop 'app.data-path')/storage":/app/storage \
    myapp-storage:latest

docker create \
    --name=myapp-database \
    -p "$(prop 'app.database.address')":"$(prop 'app.database.port')":5432 \
    -h "$(prop 'app.database.host')" \
    -e POSTGRES_USER="$(prop 'app.database.user')" \
    -e POSTGRES_PASSWORD="$(prop 'app.database.pass')" \
    -e POSTGRES_DB="$(prop 'app.database.main')" \
    -e PGDATA="/app/database" \
    -v "$(prop 'app.data-path')/database":/app/database \
    postgres:9.5

File: env/dev.properties

app.data-path=/apps/myapp/

#==========================================================
# Server properties
#==========================================================
app.server.address=127.0.0.70
app.server.host=dev.myapp.com
app.server.port=8080

#==========================================================
# Backend properties
#==========================================================
app.backend.address=127.0.0.70
app.backend.host=dev.myapp.com
app.backend.port=8081
app.backend.maximum.threads=5

#==========================================================
# Database properties
#==========================================================
app.database.address=127.0.0.70
app.database.host=database.myapp.com
app.database.port=5432
app.database.user=dev-user-name
app.database.pass=dev-password
app.database.main=dev-database

#==========================================================
# Storage properties
#==========================================================
app.storage.address=127.0.0.70
app.storage.host=storage.myapp.com
app.storage.port=4569
app.storage.endpoint=http://storage.myapp.com:4569
app.storage.access-key=dev-access-key
app.storage.secret-key=dev-secret-key
app.storage.region=us-east-1
app.storage.bucket=dev-bucket

Usage:

./setup.sh dev

Check if Variable is Empty - Angular 2

You can play here with different types and check the output,

Demo

export class ParentCmp {
  myVar:stirng="micronyks";
  myVal:any;
  myArray:Array[]=[1,2,3];
  myArr:Array[];

    constructor() {
      if(this.myVar){
         console.log('has value')     // answer
      }
      else{
        console.log('no value');
      }

      if(this.myVal){
         console.log('has value') 
      }
      else{
        console.log('no value');      //answer
      }


       if(this.myArray){
          console.log('has value')    //answer
       }
       else{
          console.log('no value');
       }

       if(this.myArr){
             console.log('has value')
       }
       else{
             console.log('no value');  //answer
       }
    } 

}

How to delete row based on cell value

You could copy down a formula like the following in a new column...

=IF(ISNUMBER(FIND("-",A1)),1,0)

... then sort on that column, highlight all the rows where the value is 1 and delete them.

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Concatenating variables and strings in React

You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id} - you need to indicate which are variables and which are string literals. Since anything inside {} is an inline JSX expression, you can do:

href={"#demo" + this.state.id}

This will use the string literal #demo and concatenate it to the value of this.state.id. This can then be applied to all strings. Consider this:

var text = "world";

And this:

{"Hello " + text + " Andrew"}

This will yield:

Hello world Andrew 

You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr} (interpolated expression), which is closer to what you seem to be trying to do:

href={`#demo${this.state.id}`}

This will basically substitute the value of this.state.id, concatenating it to #demo. It is equivalent to doing: "#demo" + this.state.id.

Using a SELECT statement within a WHERE clause

Subquery is the name.

At times it's required, but good/bad depends on how it's applied.

Change auto increment starting number?

If you need this procedure for variable fieldnames instead of id this might be helpful:

DROP PROCEDURE IF EXISTS update_auto_increment;
DELIMITER //
CREATE PROCEDURE update_auto_increment (_table VARCHAR(128), _fieldname VARCHAR(128))
BEGIN
    DECLARE _max_stmt VARCHAR(1024);
    DECLARE _stmt VARCHAR(1024);    
    SET @inc := 0;

    SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(',_fieldname,'), 0) + 1 INTO @inc FROM ', _table);
    PREPARE _max_stmt FROM @MAX_SQL;
    EXECUTE _max_stmt;
    DEALLOCATE PREPARE _max_stmt;

    SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT =  ', @inc);
    PREPARE _stmt FROM @SQL;
    EXECUTE _stmt;
    DEALLOCATE PREPARE _stmt;
END //
DELIMITER ;

CALL update_auto_increment('your_table_name', 'autoincrement_fieldname');

How can one check to see if a remote file exists using PHP?

This is not an answer to your original question, but a better way of doing what you're trying to do:

Instead of actually trying to get the site's favicon directly (which is a royal pain given it could be /favicon.png, /favicon.ico, /favicon.gif, or even /path/to/favicon.png), use google:

<img src="http://www.google.com/s2/favicons?domain=[domain]">

Done.

Adding timestamp to a filename with mv in BASH

Well, it's not a direct answer to your question, but there's a tool in GNU/Linux whose job is to rotate log files on regular basis, keeping old ones zipped up to a certain limit. It's logrotate

How to uncheck a radio button?

Thanks Patrick, you made my day! It's mousedown you have to use. However I've improved the code so you can handle a group of radio buttons.

//We need to bind click handler as well
//as FF sets button checked after mousedown, but before click
$('input:radio').bind('click mousedown', (function() {
    //Capture radio button status within its handler scope,
    //so we do not use any global vars and every radio button keeps its own status.
    //This required to uncheck them later.
    //We need to store status separately as browser updates checked status before click handler called,
    //so radio button will always be checked.
    var isChecked;

    return function(event) {
        //console.log(event.type + ": " + this.checked);

        if(event.type == 'click') {
            //console.log(isChecked);

            if(isChecked) {
                //Uncheck and update status
                isChecked = this.checked = false;
            } else {
                //Update status
                //Browser will check the button by itself
                isChecked = true;

                //Do something else if radio button selected
                /*
                if(this.value == 'somevalue') {
                    doSomething();
                } else {
                    doSomethingElse();
                }
                */
            }
    } else {
        //Get the right status before browser sets it
        //We need to use onmousedown event here, as it is the only cross-browser compatible event for radio buttons
        isChecked = this.checked;
    }
}})());

Hide Show content-list with only CSS, no javascript used

I used a hidden checkbox to persistent view of some message. The checkbox could be hidden (display:none) or not. This is a tiny code that I could write.

You can see and test the demo on JSFiddle

HTML:

<input type=checkbox id="show">
<label for="show">Help?</label>
<span id="content">Do you need some help?</span>

CSS:

#show,#content{display:none;}
#show:checked~#content{display:block;}

Run code snippet:

_x000D_
_x000D_
#show,#content{display:none;}_x000D_
#show:checked~#content{display:block;}
_x000D_
<input id="show" type=checkbox>_x000D_
<label for="show">Click for Help</label>_x000D_
<span  id="content">Do you need some help?</span>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/9s8scbL7/

How to download/checkout a project from Google Code in Windows?

Thanks Mr. Tom Chantler adding that to get the exe http://downloadsvn.codeplex.com/ to pull the SVN source

just note that suppose you're downloading the below project: you have to enter exactly the following to donwload it in the exe URL:

http://myproject.googlecode.com/svn/trunk/

developer not taking care of appending the h t t p : / / if it does not exist. Hope it saves somebody's time.

Scale image to fit a bounding box

This helped me:

.img-class {
  width: <img width>;
  height: <img height>;
  content: url('/path/to/img.png');
}

Then on the element (you can use javascript or media queries to add responsiveness):

<div class='img-class' style='transform: scale(X);'></div>

Hope this helps!

Is iterating ConcurrentHashMap values thread safe?

It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.

Full Screen Theme for AppCompat

To remove title bar in AppCompat:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
    }

CSS ''background-color" attribute not working on checkbox inside <div>

When you input the body tag, press space just one time without closing the tag and input bgcolor="red", just for instance. Then choose a diff color for your font.

How do I create a readable diff of two spreadsheets using git diff?

Newer versions of MS Office come with Spreadsheet Compare, which performs a fairly nice diff in a GUI. It detects most kinds of changes.

I need an unordered list without any bullets

If you're unable to make it work at the <ul> level, you might need to place the list-style-type: none; at the <li> level:

<ul>
    <li style="list-style-type: none;">Item 1</li>
    <li style="list-style-type: none;">Item 2</li>
</ul>

You can create a CSS class to avoid this repetition:

<style>
ul.no-bullets li
{
    list-style-type: none;
}
</style>

<ul class="no-bullets">
    <li>Item 1</li>
    <li>Item 2</li>
</ul>

When necessary, use !important:

<style>
ul.no-bullets li
{
    list-style-type: none !important;
}
</style>

Creating files in C++

#include <iostream>
#include <fstream>

int main() {
  std::ofstream o("Hello.txt");

  o << "Hello, World\n" << std::endl;

  return 0;
}

How to send POST in angularjs with multiple params?

var name = $scope.username;
var pwd = $scope.password;

var req = {
    method: 'POST',
    url: '../Account/LoginAccount',
    headers: {
        'Content-Type': undefined
    },
    params: { username: name, password: pwd }
}

$http(req).then(function (responce) {
    // success function
}, function (responce) {
    // Failure Function
});

Create a temporary table in MySQL with an index from a select

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
select_statement

Example :

CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
INSERT IGNORE INTO mytable SELECT id FROM table WHERE xyz;

how to get a list of dates between two dates in java

One solution would be to create a Calendar instance, and start a cycle, increasing it's Calendar.DATE field until it reaches the desired date. Also, on each step you should create a Date instance (with corresponding parameters), and put it to your list.

Some dirty code:

    public List<Date> getDatesBetween(final Date date1, final Date date2) {
    List<Date> dates = new ArrayList<Date>();

    Calendar calendar = new GregorianCalendar() {{
        set(Calendar.YEAR, date1.getYear());
        set(Calendar.MONTH, date1.getMonth());
        set(Calendar.DATE, date1.getDate());
    }};

    while (calendar.get(Calendar.YEAR) != date2.getYear() && calendar.get(Calendar.MONTH) != date2.getMonth() && calendar.get(Calendar.DATE) != date2.getDate()) {
        calendar.add(Calendar.DATE, 1);
        dates.add(new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)));
    }

    return dates;
}

asp.net mvc @Html.CheckBoxFor

Use this code:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "YourId" })
}

Java RegEx meta character (.) and ordinary dot?

If you want to end check whether your sentence ends with "." then you have to add [\.\]$ to the end of your pattern.

How to disable Compatibility View in IE

This should be enough to force an IE user to drop compatibility mode in any IE version:

<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

However, there are a couple of caveats one should be aware of:

  • The meta tag above should be included as the very first tag under <head>. Only the <title> tag may be placed above it.

If you don't do that, you'll get an error on IE9 Dev Tools: X-UA-Compatible META tag ignored because document mode is already finalized.

  • If you want this markup to validate, make sure you remember to close the meta tag with a /> instead of just >.

  • Starting with IE11, edge mode is the preferred document mode. To support/enable that, use the HTML5 document type declaration <!doctype html>.

  • If you need to support webfonts on IE7, make sure you use <!DOCTYPE html>. I've tested it and found that rendering webfonts on IE7 got pretty unreliable when using <!doctype html>.

The use of Google Chrome Frame is popular, but unfortunately it's going to be dropped sometime this month, Jan. 2014.

<meta http-equiv="X-UA-Compatible" content="IE=EDGE,chrome=1">

Extensive related info here. The tip on using it as the first meta tag is on a previously mentioned source here, which has been updated.

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

PHP AES encrypt / decrypt

If you are using PHP >= 7.2 consider using inbuilt sodium core extension for encrption.

Find more information here - http://php.net/manual/en/intro.sodium.php.

How do multiple clients connect simultaneously to one port, say 80, on a server?

TCP / HTTP Listening On Ports: How Can Many Users Share the Same Port

So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.

Intuitively (and wrongly), most people assume that it looks something like this:

    Local Computer    | Remote Computer
    --------------------------------
    <local_ip>:80     | <foreign_ip>:80

    ^^ not actually what happens, but this is the conceptual model a lot of people have in mind.

This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.

Three things must be understood:

1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.

2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.

3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.

So, this is really what gets created when a client connects to a server:

    Local Computer   | Remote Computer           | Role
    -----------------------------------------------------------
    0.0.0.0:80       | <none>                    | LISTENING
    127.0.0.1:80     | 10.1.2.3:<random_port>    | ESTABLISHED

Looking at What Actually Happens

First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).

    netstat -atnp | grep -i ":500 "

As expected, the output is blank. Now let's start a web server:

    sudo python3 -m http.server 500

Now, here is the output of running netstat again:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      - 

So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all". An easy mistake to make is to listen on address 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.

So now, let's connect a user to our machine:

    quicknet -m tcp -t localhost:500 -p Test payload.

This is a simple script (https://github.com/grokit/dcore/tree/master/apps/quicknet) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:54240      ESTABLISHED -

If you connect with another client and do netstat again, you will see the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:26813      ESTABLISHED -

... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.

Clang vs GCC - which produces faster binaries?

A peculiar difference I have noted on gcc 5.2.1 and clang 3.6.2 is that if you have a critical loop like:

for (;;) {
    if (!visited) {
        ....
    }
    node++;
    if (!*node) break;
  }

Then gcc will, when compiling with -O3 or -O2, speculatively unroll the loop eight times. Clang will not unroll it at all. Through trial and error I found that in my specific case with my program data, the right amount of unrolling is five so gcc overshot and clang undershot. However, overshooting was more detrimental to performance, so gcc performed much worse here.

I have no idea if the unrolling difference is a general trend or just something that was specific to my scenario.

A while back I wrote a few garbage collectors to teach myself more about performance optimization in C. And the results I got is in my mind enough to slightly favor clang. Especially since garbage collection is mostly about pointer chasing and copying memory.

The results are (numbers in seconds):

+---------------------+-----+-----+
|Type                 |GCC  |Clang|
+---------------------+-----+-----+
|Copying GC           |22.46|22.55|
|Copying GC, optimized|22.01|20.22|
|Mark & Sweep         | 8.72| 8.38|
|Ref Counting/Cycles  |15.14|14.49|
|Ref Counting/Plain   | 9.94| 9.32|
+---------------------+-----+-----+

This is all pure C code, and I make no claim about either compiler's performance when compiling C++ code.

On Ubuntu 15.10, x86.64, and an AMD Phenom(tm) II X6 1090T processor.

What jar should I include to use javax.persistence package in a hibernate based application?

If you are developing an OSGi system I would recommend you to download the "bundlefied" version from Springsource Enterprise Bundle Repository.

Otherwise its ok to use a regular jar-file containing the javax.persistence package

Html5 Full screen video

You can do it with jQuery.

I have my video and controls in their own <div> like this:

<div id="videoPlayer" style="width:520px; -webkit-border-radius:10px; height:420px; background-color:white; position:relative; float:left; left:25px; top:55px;" align="center">

    <video controls width="500" height="400" style="background-color:black; margin-top:10px; -webkit-border-radius:10px;">
         <source src="videos/gin.mp4" type="video/mp4" />
    </video>

    <script>  
        video.removeAttribute('controls');  
    </script> 

    <div id="vidControls" style="position:relative; width:100%; height:50px; background-color:white; -webkit-border-bottom-left-radius:10px; -webkit-border-bottom-right-radius:10px; padding-top:10px; padding-bottom:10px;">

         <table width="100%" height="100%" border="0">

             <tr>
                 <td width="100%" align="center" valign="middle" colspan="4"><input class="vidPos" type="range" value="0" step="0.1" style="width:500px;" /></td>
             </tr>

             <tr>
                 <td width="100%" align="center" valign="middle"><a href="javascript:;" class="playVid">Play</a></td>
                 <td width="100%" align="center" valign="middle"><a href="javascript:;" class="vol">Vol</a></td>
                 <td width="100%" align="left" valign="middle"><p class="timer"><strong>0:00</strong> / 0:00</p></td>
                 <td width="100%" align="center" valign="middle"><a href="javascript:;" class="fullScreen">Full</a></td>
              </tr>

            </table>

         </div>

      </div>

And then my jQuery for the .fullscreen class is:

var fullscreen = 0;

$(".fullscreen").click(function(){
  if(fullscreen == 0){
    fullscreen = 1;
    $("video").appendTo('body');
    $("#vidControls").appendTo('body');
    $("video").css('position', 'absolute').css('width', '100%').css('height', '90%').css('margin', 0).css('margin-top', '5%').css('top', '0').css('left', '0').css('float', 'left').css('z-index', 600);
    $("#vidControls").css('position', 'absolute').css('bottom', '5%').css('width', '90%').css('backgroundColor', 'rgba(150, 150, 150, 0.5)').css('float', 'none').css('left', '5%').css('z-index', 700).css('-webkit-border-radius', '10px');

}
else
    {

        fullscreen = 0;

        $("video").appendTo('#videoPlayer');
        $("#vidControls").appendTo('#videoPlayer');

        //change <video> css back to normal

        //change "#vidControls" css back to normal

    }

});

It needs a little cleaning up as I'm still working on it but that should work for most browsers as far as I can see.

Hope it helps!

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

Provide the :name option to add_index, e.g.:

add_index :studies,
  ["user_id", "university_id", "subject_name_id", "subject_type_id"], 
  unique: true,
  name: 'my_index'

If using the :index option on references in a create_table block, it takes the same options hash as add_index as its value:

t.references :long_name, index: { name: :my_index }

PHP, Get tomorrows date from date

Use DateTime

$datetime = new DateTime('tomorrow');
echo $datetime->format('Y-m-d H:i:s');

Or:

$datetime = new DateTime('2013-01-22');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

Or:

$datetime = new DateTime('2013-01-22');
$datetime->add(new DateInterval("P1D"));
echo $datetime->format('Y-m-d H:i:s');

Or in PHP 5.4+:

echo (new DateTime('2013-01-22'))->add(new DateInterval("P1D"))
                                 ->format('Y-m-d H:i:s');

How to use multiple @RequestMapping annotations in spring?

The shortest way is: @RequestMapping({"", "/", "welcome"})

Although you can also do:

  • @RequestMapping(value={"", "/", "welcome"})
  • @RequestMapping(path={"", "/", "welcome"})

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

I installed docker from snap repository. So I also had to start from snap (running Ubuntu).

sudo snap start docker

Otherwise you can also install it from their repositories.

Spring Boot Java Config Set Session Timeout

You should be able to set the server.session.timeout in your application.properties file.

ref: http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Jquery If radio button is checked

if($('#test2').is(':checked')) {
    $(this).append('stuff');
} 

Proxy with express.js

I found a shorter solution that does exactly what I want https://github.com/http-party/node-http-proxy

After installing http-proxy

npm install http-proxy --save

Use it like below in your server/index/app.js

var proxyServer = require('http-route-proxy');
app.use('/api/BLABLA/', proxyServer.connect({
  to: 'other_domain.com:3000/BLABLA',
  https: true,
  route: ['/']
}));

I really have spent days looking everywhere to avoid this issue, tried plenty of solutions and none of them worked but this one.

Hope it is going to help someone else too :)

How do I find which transaction is causing a "Waiting for table metadata lock" state?

mysql 5.7 exposes metadata lock information through the performance_schema.metadata_locks table.

Documentation here

Pass array to mvc Action via AJAX

Set the traditional property to true before making the get call. i.e.:

jQuery.ajaxSettings.traditional = true

$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {... 

Classes residing in App_Code is not accessible

Right click on the .cs file in the App_Code folder and check its properties.

Make sure the "Build Action" is set to "Compile".

Should try...catch go inside or outside a loop?

If you put the try/catch inside the loop, you'll keep looping after an exception. If you put it outside the loop you'll stop as soon as an exception is thrown.

JS strings "+" vs concat method

In JS, "+" concatenation works by creating a new String object.

For example, with...

var s = "Hello";

...we have one object s.

Next:

s = s + " World";

Now, s is a new object.

2nd method: String.prototype.concat

Streaming via RTSP or RTP in HTML5

My observations regarding the HTML 5 video tag and rtsp(rtp) streams are, that it only works with konqueror(KDE 4.4.1, Phonon-backend set to GStreamer). I got only video (no audio) with a H.264/AAC RTSP(RTP) stream.

The streams from http://media.esof2010.org/ didn't work with konqueror(KDE 4.4.1, Phonon-backend set to GStreamer).

C++ Best way to get integer division and remainder

In addition to the aforementioned std::div family of functions, there is also the std::remquo family of functions, return the rem-ainder and getting the quo-tient via a passed-in pointer.

[Edit:] It looks like std::remquo doesn't really return the quotient after all.

How to flush output after each `echo` call?

Try this:

while (@ob_end_flush());      
ob_implicit_flush(true);

echo "first line visible to the browser";
echo "<br />";

sleep(5);

echo "second line visible to the browser after 5 secs";

Just notice that this way you're actually disabling the output buffer for your current script. I guess you can reenable it with ob_start() (i'm not sure).

Important thing is that by disabling your output buffer like above, you will not be able to redirect your php script anymore using the header() function, because php can sent only once per script execution http headers. You can however redirect using javascript. Just let your php script echo following lines when it comes to that:

        echo '<script type="text/javascript">';
        echo 'window.location.href="'.$url.'";';
        echo '</script>';
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
        echo '</noscript>'; 
        exit;

JPA & Criteria API - Select only specific columns

You can do something like this

Session session = app.factory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Users> root = query.from(Users.class);
query.select(root.get("firstname"));
String name = session.createQuery(query).getSingleResult();

where you can change "firstname" with the name of the column you want.

Split (explode) pandas dataframe string entry to separate rows

Here is a fairly straightforward message that uses the split method from pandas str accessor and then uses NumPy to flatten each row into a single array.

The corresponding values are retrieved by repeating the non-split column the correct number of times with np.repeat.

var1 = df.var1.str.split(',', expand=True).values.ravel()
var2 = np.repeat(df.var2.values, len(var1) / len(df))

pd.DataFrame({'var1': var1,
              'var2': var2})

  var1  var2
0    a     1
1    b     1
2    c     1
3    d     2
4    e     2
5    f     2

T-SQL: Looping through an array of known values

What I do in this scenario is create a table variable to hold the Ids.

  Declare @Ids Table (id integer primary Key not null)
  Insert @Ids(id) values (4),(7),(12),(22),(19)

-- (or call another table valued function to generate this table)

Then loop based on the rows in this table

  Declare @Id Integer
  While exists (Select * From @Ids)
    Begin
      Select @Id = Min(id) from @Ids
      exec p_MyInnerProcedure @Id 
      Delete from @Ids Where id = @Id
    End

or...

  Declare @Id Integer = 0 -- assuming all Ids are > 0
  While exists (Select * From @Ids
                where id > @Id)
    Begin
      Select @Id = Min(id) 
      from @Ids Where id > @Id
      exec p_MyInnerProcedure @Id 
    End

Either of above approaches is much faster than a cursor (declared against regular User Table(s)). Table-valued variables have a bad rep because when used improperly, (for very wide tables with large number of rows) they are not performant. But if you are using them only to hold a key value or a 4 byte integer, with a index (as in this case) they are extremely fast.

How can I generate a list of consecutive numbers?

Using Python's built in range function:

Python 2

input = 8
output = range(input + 1)

print output
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Python 3

input = 8
output = list(range(input + 1))

print(output)
[0, 1, 2, 3, 4, 5, 6, 7, 8]

JQUERY ajax passing value from MVC View to Controller

[HttpPost]
public ActionResult SaveComments(int id, string comments){
     var actions = new Actions(User.Identity.Name);
     var status = actions.SaveComments(id, comments);
     return Content(status);
}

Easiest way to use SVG in Android?

Android Studio supports SVG from 1.4 onwards

Here is a video on how to import.

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

A simple solution that i use, works from IE8+

Give min-height:100% on html so that if content is less then still page takes full view-port height and footer sticks at bottom of page. When content increases the footer shifts down with content and keep sticking to bottom.

JS fiddle working Demo: http://jsfiddle.net/3L3h64qo/2/

Css

html{
  position:relative; 
  min-height: 100%;
}
/*Normalize html and body elements,this style is just good to have*/
html,body{
  margin:0;
  padding:0;
}
.pageContentWrapper{
  margin-bottom:100px;/* Height of footer*/
} 
.footer{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height:100px;
    background:#ccc;
}

Html

   <html>
    <body>
        <div class="pageContentWrapper">
            <!-- All the page content goes here-->
        </div>
        <div class="footer">
        </div>
    </body>
    </html>

What is the difference between 127.0.0.1 and localhost

There is nothing different. One is easier to remember than the other. Generally, you define a name to associate with an IP address. You don't have to specify localhost for 127.0.0.1, you could specify any name you want.

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

It's according to spec.

12.5 The if Statement 
.....

2. If ToBoolean(GetValue(exprRef)) is true, then 
a. Return the result of evaluating the first Statement. 
3. Else, 
....

ToBoolean, according to the spec, is

The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:

And that table says this about strings:

enter image description here

The result is false if the argument is the empty String (its length is zero); otherwise the result is true

Now, to explain why "0" == false you should read the equality operator, which states it gets its value from the abstract operation GetValue(lref) matches the same for the right-side.

Which describes this relevant part as:

if IsPropertyReference(V), then 
a. If HasPrimitiveBase(V) is false, then let get be the [[Get]] internal method of base, otherwise let get
be the special [[Get]] internal method defined below. 
b. Return the result of calling the get internal method using base as its this value, and passing 
GetReferencedName(V) for the argument

Or in other words, a string has a primitive base, which calls back the internal get method and ends up looking false.

If you want to evaluate things using the GetValue operation use ==, if you want to evaluate using the ToBoolean, use === (also known as the "strict" equality operator)

html table cell width for different rows

You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.

You can however have cells span multiple columns, such as:

<table>
    <tr>
        <td>25</td>
        <td>50</td>
        <td>25</td>
    </tr>
    <tr>
        <td colspan="2">75</td>
        <td>20</td>
    </tr>
</table>

As an aside, you should avoid using style attributes like border and bgcolor and prefer CSS for those.

CSS selector for a checked radio button's label

I know this is an old question, but if you would like to have the <input> be a child of <label> instead of having them separate, here is a pure CSS way that you could accomplish it:

:checked + span { font-weight: bold; }

Then just wrap the text with a <span>:

<label>
   <input type="radio" name="test" />
   <span>Radio number one</span>
</label>

See it on JSFiddle.

Add MIME mapping in web.config for IIS Express

Thanks for this post. I got this worked for using mustache templates in my asp.net mvc project I used the following, and it worked for me.

<system.webServer>   
  <staticContent>
   <mimeMap fileExtension=".mustache" mimeType="text/html"/>
  </staticContent>
</system.WebServer>

Can local storage ever be considered secure?

Well, the basic premise here is: no, it is not secure yet.

Basically, you can't run crypto in JavaScript: JavaScript Crypto Considered Harmful.

The problem is that you can't reliably get the crypto code into the browser, and even if you could, JS isn't designed to let you run it securely. So until browsers have a cryptographic container (which Encrypted Media Extensions provide, but are being rallied against for their DRM purposes), it will not be possible to do securely.

As far as a "Better way", there isn't one right now. Your only alternative is to store the data in plain text, and hope for the best. Or don't store the information at all. Either way.

Either that, or if you need that sort of security, and you need local storage, create a custom application...

Taking inputs with BufferedReader in Java

You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass. Although, you can do something like this in regard to your query :

import java.io.*;
class Test
{
   public static void main(String args[])throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
       for(int i=0;i<t;i++)
       {
         String str=br.readLine();
         String num[]=br.readLine().split(" ");
         int num1=Integer.parseInt(num[0]);
         int num2=Integer.parseInt(num[1]);
         //rest of your code
       }
    }
}

I hope this will help you.

Replace input type=file by an image

its really simple you can try this:

$("#image id").click(function(){
    $("#input id").click();
});

Set default value of javascript object attributes

This seems to me the most simple and readable way of doing so:

let options = {name:"James"}
const default_options = {name:"John", surname:"Doe"}

options = Object.assign({}, default_options, options)

Object.assign() reference

How do I keep Python print from adding newlines or spaces?

Regain control of your console! Simply:

from __past__ import printf

where __past__.py contains:

import sys
def printf(fmt, *varargs):
    sys.stdout.write(fmt % varargs)

then:

>>> printf("Hello, world!\n")
Hello, world!
>>> printf("%d %d %d\n", 0, 1, 42)
0 1 42
>>> printf('a'); printf('b'); printf('c'); printf('\n')
abc
>>>

Bonus extra: If you don't like print >> f, ..., you can extending this caper to fprintf(f, ...).

Print PHP Call Stack

Strange that noone posted this way:

debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);

This actually prints backtrace without the garbage - just what method was called and where.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

For anyone who is trying to convert JSON to dictionary just for retrieving some value out of it. There is a simple way using Newtonsoft.JSON

using Newtonsoft.Json.Linq
...

JObject o = JObject.Parse(@"{
  'CPU': 'Intel',
  'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}");

string cpu = (string)o["CPU"];
// Intel

string firstDrive = (string)o["Drives"][0];
// DVD read/writer

IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive

Meaning of $? (dollar question mark) in shell scripts

Outputs the result of the last executed unix command

0 implies true
1 implies false

How to prevent user from typing in text field without disabling the field?

One other method that could be used depending on the need $('input').onfocus(function(){this.blur()}); I think this is how you would write it. I am not proficient in jquery.

Append data frames together in a for loop

In the Coursera course, an Introduction to R Programming, this skill was tested. They gave all the students 332 separate csv files and asked them to programmatically combined several of the files to calculate the mean value of the pollutant.

This was my solution:

  # create your empty dataframe so you can append to it.
  combined_df <- data.frame(Date=as.Date(character()),
                    Sulfate=double(),
                    Nitrate=double(),
                    ID=integer())
  # for loop for the range of documents to combine
  for(i in min(id): max(id)) {
    # using sprintf to add on leading zeros as the file names had leading zeros
    read <- read.csv(paste(getwd(),"/",directory, "/",sprintf("%03d", i),".csv", sep=""))
    # in your loop, add the files that you read to the combined_df
    combined_df <- rbind(combined_df, read)
  }

How do I iterate through the files in a directory in Java?

Check out the FileUtils class in Apache Commons - specifically iterateFiles:

Allows iteration over the files in given directory (and optionally its subdirectories).

Putting text in top left corner of matplotlib plot

One solution would be to use the plt.legend function, even if you don't want an actual legend. You can specify the placement of the legend box by using the loc keyterm. More information can be found at this website but I've also included an example showing how to place a legend:

ax.scatter(xa,ya, marker='o', s=20, c="lightgreen", alpha=0.9)
ax.scatter(xb,yb, marker='o', s=20, c="dodgerblue", alpha=0.9)
ax.scatter(xc,yc marker='o', s=20, c="firebrick", alpha=1.0)
ax.scatter(xd,xd,xd, marker='o', s=20, c="goldenrod", alpha=0.9)
line1 = Line2D(range(10), range(10), marker='o', color="goldenrod")
line2 = Line2D(range(10), range(10), marker='o',color="firebrick")
line3 = Line2D(range(10), range(10), marker='o',color="lightgreen")
line4 = Line2D(range(10), range(10), marker='o',color="dodgerblue")
plt.legend((line1,line2,line3, line4),('line1','line2', 'line3', 'line4'),numpoints=1, loc=2) 

Note that because loc=2, the legend is in the upper-left corner of the plot. And if the text overlaps with the plot, you can make it smaller by using legend.fontsize, which will then make the legend smaller.

Short form for Java if statement

here is one line code

name = (city.getName() != null) ? city.getName() : "N/A";

here is example how it work, run below code in js file and understand the result. This ("Data" != null) is condition as we do in normal if() and "Data" is statement when this condition became true. this " : " act as else and "N/A" is statement for else condition. Hope this help you to understand the logic.

_x000D_
_x000D_
name = ("Data" != null) ? "Data" : "N/A";_x000D_
_x000D_
console.log(name);
_x000D_
_x000D_
_x000D_

Getting Java version at runtime

Example for Apache Commons Lang:

import org.apache.commons.lang.SystemUtils;

    Float version = SystemUtils.JAVA_VERSION_FLOAT;

    if (version < 1.4f) { 
        // legacy
    } else if (SystemUtils.IS_JAVA_1_5) {
        // 1.5 specific code
    } else if (SystemUtils.isJavaVersionAtLeast(1.6f)) {
        // 1.6 compatible code
    } else {
        // dodgy clause to catch 1.4 :)
    }

What is PostgreSQL equivalent of SYSDATE from Oracle?

NOW() is the replacement of Oracle Sysdate in Postgres.

Try "Select now()", it will give you the system timestamp.

Faking an RS232 Serial Port

I use com0com - With Signed Driver, on windows 7 x64 to emulate COM3 AND COM4 as a pair.

Then i use COM Dataport Emulator to recieve from COM4.

Then i open COM3 with the app im developping (c#) and send data to COM3.

The data sent thru COM3 is received by COM4 and shown by 'COM Dataport Emulator' who can also send back a response (not automated).

So with this 2 great programs i managed to emulate Serial RS-232 comunication.

Hope it helps.

Both programs are free!!!!!

Can we call the function written in one JavaScript in another JS file?

If all files are included , you can call properties from one file to another (like function, variable, object etc.)

The js functions and variables that you write in one .js file - say a.js will be available to other js files - say b.js as long as both a.js and b.js are included in the file using the following include mechanism(and in the same order if the function in b.js calls the one in a.js).

<script language="javascript" src="a.js"> and 
<script language="javascript" src="b.js">

When should one use a spinlock instead of mutex?

The rule for using spinlocks is simple: use a spinlock if and only if the real time the lock is held is bounded and sufficiently small.

Note that usually user implemented spinlocks DO NOT satisfy this requirement because they do not disable interrupts. Unless pre-emptions are disabled, a pre-emption whilst a spinlock is held violates the bounded time requirement.

Sufficiently small is a judgement call and depends on the context.

Exception: some kernel programming must use a spinlock even when the time is not bounded. In particular if a CPU has no work to do, it has no choice but to spin until some more work turns up.

Special danger: in low level programming take great care when multiple interrupt priorities exist (usually there is at least one non-maskable interrupt). In this higher priority pre-emptions can run even if interrupts at the thread priority are disabled (such as priority hardware services, often related to the virtual memory management). Provided a strict priority separation is maintained, the condition for bounded real time must be relaxed and replaced with bounded system time at that priority level. Note in this case not only can the lock holder be pre-empted but the spinner can also be interrupted; this is generally not a problem because there's nothing you can do about it.

C# - How to get Program Files (x86) on Windows 64 bit

If you're using .NET 4, there is a special folder enumeration ProgramFilesX86:

Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)

npm start error with create-react-app

I fix this using this following command:

npm install -g react-scripts

How to upgrade docker container after its image changed

This is something I've also been struggling with for my own images. I have a server environment from which I create a Docker image. When I update the server, I'd like all users who are running containers based on my Docker image to be able to upgrade to the latest server.

Ideally, I'd prefer to generate a new version of the Docker image and have all containers based on a previous version of that image automagically update to the new image "in place." But this mechanism doesn't seem to exist.

So the next best design I've been able to come up with so far is to provide a way to have the container update itself--similar to how a desktop application checks for updates and then upgrades itself. In my case, this will probably mean crafting a script that involves Git pulls from a well-known tag.

The image/container doesn't actually change, but the "internals" of that container change. You could imagine doing the same with apt-get, yum, or whatever is appropriate for you environment. Along with this, I'd update the myserver:latest image in the registry so any new containers would be based on the latest image.

I'd be interested in hearing whether there is any prior art that addresses this scenario.

Java: method to get position of a match in a String?

This works using regex.

String text = "I love you so much";
String wordToFind = "love";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);

while (match.find()) {
     System.out.println("Found love at index "+ match.start() +" - "+ (match.end()-1));
}

Output :

Found 'love' at index 2 - 5

General Rule :

  • Regex search left to right, and once the match characters has been used, it cannot be reused.

How to call a method in another class in Java?

You should capitalize names of your classes. After doing that do this in your school class,

Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);

Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters

How to get DropDownList SelectedValue in Controller in MVC

Simple solution not sure if this has been suggested or not. This also may not work for some things. That being said this is the simple solution below.

new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true}

List<SelectListItem> InvoiceStatusDD = new List<SelectListItem>();
InvoiceStatusDD.Add(new SelectListItem { Value = "0", Text = "All Invoices" });
InvoiceStatusDD.Add(new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true});
InvoiceStatusDD.Add(new SelectListItem { Value = "7", Text = "Client Approved Invoices" });

@Html.DropDownList("InvoiceStatus", InvoiceStatusDD)

You can also do something like this for a database driven select list. you will need to set selected in your controller

@Html.DropDownList("ApprovalProfile", (IEnumerable<SelectListItem>)ViewData["ApprovalProfiles"], "All Employees")

Something like this but better solutions exist this is just one method.

foreach (CountryModel item in CountryModel.GetCountryList())
    {
        if (item.CountryPhoneCode.Trim() != "974")
        {
            countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });

        }
        else {


            countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });

        }
    }

How to send UTF-8 email?

I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:

function utf8_to_latin2($str)
{
    return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
    {
        mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
        "From: $form\r\n".
        "Reply-To: $reply\r\n".
        "X-Mailer: PHP/" . phpversion());
    }

I have made another mailer function, because apple device could not read well the previous version.

function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
    $s= "=?utf-8?b?".base64_encode($s)."?=";
    $headers = "MIME-Version: 1.0\r\n";
    $headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
    $headers.= "Content-Type: text/plain;charset=utf-8\r\n";
    $headers.= "Reply-To: $reply\r\n";  
    $headers.= "X-Mailer: PHP/" . phpversion();
    mail($to, $s, $body, $headers);
}

How to import the class within the same directory or sub directory?

Python 2

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory".

Then just do...

from user import User
from dir import Dir

The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.

bin/
    main.py
    classes/
        user.py
        dir.py

So if the directory was named "classes", then you'd do this:

from classes.user import User
from classes.dir import Dir

Python 3

Same as previous, but prefix the module name with a . if not using a subdirectory:

from .user import User
from .dir import Dir

src absolute path problem

I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.

What does it mean: The serializable class does not declare a static final serialVersionUID field?

it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...)

That's not correct, and you will be unable to cite an authoriitative source for that claim. It should be changed whenever you make a change that is incompatible under the rules given in the Versioning of Serializable Objects section of the Object Serialization Specification, which specifically does not include additional fields or change of field order, and when you haven't provided readObject(), writeObject(), and/or readResolve() or /writeReplace() methods and/or a serializableFields declaration that could cope with the change.

Float a div above page content

Yes, the higher the z-index, the better. It will position your content element on top of every other element on the page. Say you have z-index to some elements on your page. Look for the highest and then give a higher z-index to your popup element. This way it will flow even over the other elements with z-index. If you don't have a z-index in any element on your page, you should give like z-index:2; or something higher.

Creating an empty list in Python

I use [].

  1. It's faster because the list notation is a short circuit.
  2. Creating a list with items should look about the same as creating a list without, why should there be a difference?

Vertical Text Direction

To display text in vertical (Bottom-top) we can simply use:

writing-mode: vertical-lr; 

transform: rotate(180deg);

_x000D_
_x000D_
#myDiv{_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
#mySpan{_x000D_
writing-mode: vertical-lr; _x000D_
transform: rotate(180deg);_x000D_
}
_x000D_
<div id="myDiv"> _x000D_
_x000D_
<span id="mySpan"> Here We gooooo !!! </span>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note we can add this to ensure Browser Compatibility:

-webkit-transform: rotate(180deg);   
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);

we can also read more about writing-mode property here on Mozilla docs.

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

How to get all possible combinations of a list’s elements?

You can also use the powerset function from the excellent more_itertools package.

from more_itertools import powerset

l = [1,2,3]
list(powerset(l))

# [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

We can also verify, that it meets OP's requirement

from more_itertools import ilen

assert ilen(powerset(range(15))) == 32_768

Erase whole array Python

It's simple:

array = []

will set array to be an empty list. (They're called lists in Python, by the way, not arrays)

If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.

How to search in a List of Java object

You can give a try to Apache Commons Collections.

There is a class CollectionUtils that allows you to select or filter items by custom Predicate.

Your code would be like this:

Predicate condition = new Predicate() {
   boolean evaluate(Object sample) {
        return ((Sample)sample).value3.equals("three");
   }
};
List result = CollectionUtils.select( list, condition );

Update:

In java8, using Lambdas and StreamAPI this should be:

List<Sample> result = list.stream()
     .filter(item -> item.value3.equals("three"))
     .collect(Collectors.toList());

much nicer!

Timing Delays in VBA

If you are in Excel VBA you can use the following.

Application.Wait(Now + TimeValue("0:00:01"))

(The time string should look like H:MM:SS.)

How does MySQL CASE work?

CASE in MySQL is both a statement and an expression, where each usage is slightly different.

As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN -- Do other stuff
        END;
    END CASE;
  END;
  |

However, as an expression it can be used in clauses:

SELECT *
  FROM employees
  ORDER BY
    CASE title
      WHEN "President" THEN 1
      WHEN "Manager" THEN 2
      ELSE 3
    END, surname

Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

SELECT *
  FROM employees
  ORDER BY
    CASE 
      WHEN title = "President" THEN 1
      WHEN title = "Manager" THEN 2
      ELSE 3
    END, surname

I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

How can I give the Intellij compiler more heap space?

To resolve this issue follow the below given steps-

1). In inteli Go to File> Setting Option and Search for Vm Option In the field of Vm Option for Importer give value -Xmx512m. Intelij Setting Options

2). Go to Control Pannel Select View by :Large icons then Go to Java one promp window will appear with name java control pannel then go to java Java VM Options

select view option. java view options

In Java Run time Environment Setting pass Run time Parameters as -Xmx1024m.

3). If above given options does not work then change the size of pom.xml

How to check the version before installing a package using apt-get?

Linux Mint, Debian 9, Ubuntu 16.04 and older:

Short info:

apt policy <package_name>

Detailed info (With Description and Depends):

apt show <package_name>

How to initialise a string from NSData in Swift

Another answer based on extensions (boy do I miss this in Java):

extension NSData {
    func toUtf8() -> String? {
        return String(data: self, encoding: NSUTF8StringEncoding)
    }
}

Then you can use it:

let data : NSData = getDataFromEpicServer()
let string : String? = data.toUtf8() 

Note that the string is optional, the initial NSData may be unconvertible to Utf8.

JFrame in full screen Java

JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize()));

This just makes the frame the size of the screen

Open button in new window?

You can acheive this using window.open() method, passing _blank as one of the parameter. You can refer the below links which has more information on this.

http://www.w3schools.com/jsref/met_win_open.asp

http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx

Hope this will help you.

How can I disable inherited css styles?

If you control both the HTML and CSS, I'd suggest switching to using ID's on all the divs needed for the rounded corner.

CSS

#d1 {
    background: #CFFEB6 url('tr.gif') no-repeat top right;
}
#d2 {
    background: url('br.gif') no-repeat bottom right;
}
#d3 {
    background: url('bl.gif') no-repeat bottom left;
}
#d4 {
    padding: 10px;
}

HTML

<div id="d1"><div id="d2"><div id="d3"><div id="d4">
    <div class='button'><a href='#'>Test</a></div>
</div></div></div></div>

What is the best way to implement nested dictionaries?

As for "obnoxious try/catch blocks":

d = {}
d.setdefault('key',{}).setdefault('inner key',{})['inner inner key'] = 'value'
print d

yields

{'key': {'inner key': {'inner inner key': 'value'}}}

You can use this to convert from your flat dictionary format to structured format:

fd = {('new jersey', 'mercer county', 'plumbers'): 3,
 ('new jersey', 'mercer county', 'programmers'): 81,
 ('new jersey', 'middlesex county', 'programmers'): 81,
 ('new jersey', 'middlesex county', 'salesmen'): 62,
 ('new york', 'queens county', 'plumbers'): 9,
 ('new york', 'queens county', 'salesmen'): 36}

for (k1,k2,k3), v in fd.iteritems():
    d.setdefault(k1, {}).setdefault(k2, {})[k3] = v

MySQL Install: ERROR: Failed to build gem native extension

First of all you need to differentiate between the MySQL as Server, MySQL as Client and the Ruby bindings to MySQL.

I'm not familiar with Mac, but for *nix OS you need to install MySQL through your package manager. To get the Ruby bindings installed with

gem install mysql

you need the development headers of ruby (in Ubuntu it is the package ruby-dev) and the development headers of the MySQL-Client (currently libmysqlclient16-dev in Ubuntu). I don't know if they are named different on Mac, but after you got those installed the Ruby bindings should install without any error.

How to assign from a function which returns more than one value?

To obtain multiple outputs from a function and keep them in the desired format you can save the outputs to your hard disk (in the working directory) from within the function and then load them from outside the function:

myfun <- function(x) {
                      df1 <- ...
                      df2 <- ...
                      save(df1, file = "myfile1")
                      save(df2, file = "myfile2")
}
load("myfile1")
load("myfile2")

vim - How to delete a large block of text without counting the lines?

Go to the starting line and type ma (mark "a"). Then go to the last line and enter d'a (delete to mark "a").

That will delete all lines from the current to the marked one (inclusive). It's also compatible with vi as well as vim, on the off chance that your environment is not blessed with the latter.

Setting a timeout for socket operations

Use the Socket() constructor, and connect(SocketAddress endpoint, int timeout) method instead.

In your case it would look something like:

Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);

Quoting from the documentation

connect

public void connect(SocketAddress endpoint, int timeout) throws IOException

Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.

Parameters:

endpoint - the SocketAddress
timeout - the timeout value to be used in milliseconds.

Throws:

IOException - if an error occurs during the connection
SocketTimeoutException - if timeout expires before connecting
IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket

Since: 1.4

You have not accepted the license agreements of the following SDK components

Maybe I'm late, but this helped me accept SDK licenses for OSX,

If you have android SDK tools installed, run the following command

~/Library/Android/sdk/tools/bin/sdkmanager --licenses

Accept all licenses by pressing y

Voila! You have accepted SDK licenses and are good to go..

Using Linq to group a list of objects into a new grouped list of list of objects

Still an old one, but answer from Lee did not give me the group.Key as result. Therefore, I am using the following statement to group a list and return a grouped list:

public IOrderedEnumerable<IGrouping<string, User>> groupedCustomerList;

groupedCustomerList =
        from User in userList
        group User by User.GroupID into newGroup
        orderby newGroup.Key
        select newGroup;

Each group now has a key, but also contains an IGrouping which is a collection that allows you to iterate over the members of the group.

How to iterate object keys using *ngFor

i would do this:

<li *ngFor="let item of data" (click)='onclick(item)'>{{item.picture.url}}</li>

When 1 px border is added to div, Div size increases, Don't want to do that

You can create the element with border with the same color of your background, then when you want the border to show, just change its color.

What is the memory consumption of an object in Java?

Each object has a certain overhead for its associated monitor and type information, as well as the fields themselves. Beyond that, fields can be laid out pretty much however the JVM sees fit (I believe) - but as shown in another answer, at least some JVMs will pack fairly tightly. Consider a class like this:

public class SingleByte
{
    private byte b;
}

vs

public class OneHundredBytes
{
    private byte b00, b01, ..., b99;
}

On a 32-bit JVM, I'd expect 100 instances of SingleByte to take 1200 bytes (8 bytes of overhead + 4 bytes for the field due to padding/alignment). I'd expect one instance of OneHundredBytes to take 108 bytes - the overhead, and then 100 bytes, packed. It can certainly vary by JVM though - one implementation may decide not to pack the fields in OneHundredBytes, leading to it taking 408 bytes (= 8 bytes overhead + 4 * 100 aligned/padded bytes). On a 64 bit JVM the overhead may well be bigger too (not sure).

EDIT: See the comment below; apparently HotSpot pads to 8 byte boundaries instead of 32, so each instance of SingleByte would take 16 bytes.

Either way, the "single large object" will be at least as efficient as multiple small objects - for simple cases like this.

Asp.net 4.0 has not been registered

To resolve 'ASP.NET 4.0 has not been registered. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly' error when opening a solution we can:

1 Ensure the IIS feature is turned on with ASP.NET. Go to Control Panel\All Control Panel Items\Programs and Features then click 'Turn Windows Featrues on. Then in the IIS --> WWW servers --> App Dev Features ensure that ASP.NET is checked.

enter image description here

2 And run the following cmd line to install

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -i

enter image description here

Hope this helps

Convert JS date time to MySQL datetime

JS time value for MySQL

var datetime = new Date().toLocaleString();

OR

const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );

OR

const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD  HH:mm:ss.000' );

you can send this in params its will work.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

My guess is it's an encoding problem, for instance your file is UTF-8 but SQL will not read it the way it should, so it attempts to insert 100ÿ or something along these lines into your table.

Possible fixes:

  1. Specify Codepage
  2. Change the Encoding of the source using Powershell

Code samples:

1.
BULK INSERT myTable FROM 'c:\Temp\myfile.csv' WITH (
  FIELDTERMINATOR = '£',
  ROWTERMINATOR = '\n',
  CODEPAGE = 'ACP' -- ACP corresponds to ANSI, also try UTF-8 or 65001 for Unicode
);

2.
get-content "myfile.csv" | Set-content -Path "myfile.csv" -Encoding String
# String = ANSI, also try Ascii, Oem, Unicode, UTF7, UTF8, UTF32

Angular update object in object array

You can try this also to replace existing object

toDoTaskList = [
                {id:'abcd', name:'test'},
                {id:'abcdc', name:'test'},
                {id:'abcdtr', name:'test'}
              ];

newRecordToUpdate = {id:'abcdc', name:'xyz'};
this.toDoTaskList.map((todo, i) => {
         if (todo.id == newRecordToUpdate .id){
            this.toDoTaskList[i] = updatedVal;
          }
        });

Reduce git repository size

Thanks for your replies. Here's what I did:

git gc
git gc --aggressive
git prune

That seemed to have done the trick. I started with around 10.5MB and now it's little more than 980KBs.

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

HTML

<h1 class="green-background"> Whatever text you want. </h1>

CSS

.green-background { 
    text-align: center;
    padding: 5px; /*Optional (Padding is just for a better style.)*/
    background-color: green; 
}

Overwriting txt file in java

This simplifies it a bit and it behaves as you want it.

FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");

try {
 f.write(source);
 ...
} catch(...) {
} finally {
 //close it here
}

User Authentication in ASP.NET Web API

If you want to authenticate against a user name and password and without an authorization cookie, the MVC4 Authorize attribute won't work out of the box. However, you can add the following helper method to your controller to accept basic authentication headers. Call it from the beginning of your controller's methods.

void EnsureAuthenticated(string role)
{
    string[] parts = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
    if (parts.Length != 2 || !Membership.ValidateUser(parts[0], parts[1]))
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No account with that username and password"));
    if (role != null && !Roles.IsUserInRole(parts[0], role))
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "An administrator account is required"));
}

From the client side, this helper creates a HttpClient with the authentication header in place:

static HttpClient CreateBasicAuthenticationHttpClient(string userName, string password)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userName + ':' + password)));
    return client;
}

What does 'var that = this;' mean in JavaScript?

Here is an example `

$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();

            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                    var imgAlt = $(this).find('img').attr('alt'); //Here value of "this" is '.our-work-single-page'. 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

So you can see that value of this is two different values depending on the DOM element you target but when you add "that" to the code above you change the value of "this" you are targeting.

`$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();
            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                var that = this;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                   ***$(that).css("background-color", "#ffe700");*** //Here value of "that" is ".our-work-group > p > a"....
                    var imgAlt = $(this).find('img').attr('alt'); 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

.....$(that).css("background-color", "#ffe700"); //Here value of "that" is ".our-work-group > p > a" because the value of var that = this; so even though we are at "this"= '.our-work-single-page', still we can use "that" to manipulate previous DOM element.

How often should you use git-gc?

It depends mostly on how much the repository is used. With one user checking in once a day and a branch/merge/etc operation once a week you probably don't need to run it more than once a year.

With several dozen developers working on several dozen projects each checking in 2-3 times a day, you might want to run it nightly.

It won't hurt to run it more frequently than needed, though.

What I'd do is run it now, then a week from now take a measurement of disk utilization, run it again, and measure disk utilization again. If it drops 5% in size, then run it once a week. If it drops more, then run it more frequently. If it drops less, then run it less frequently.

Get request URL in JSP which is forwarded by Servlet

Also you could use

${pageContext.request.requestURI}

PHP MySQL Google Chart JSON - Complete Example

Some might encounter this error either locally or on the server:

syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);

This means that their environment does not support short tags the solution is to use this instead:

<?php echo $jsonTable; ?>

And everything should work fine!