LaTeX Tricks/Others…

What I have Googled and what my friends taught me… (Updating…)

Miscellaneous

Paper & Tech report 2-in-1

Question: How to remove some sentences from the paper (due to space limits) while keeping them in the technical report?

Solution: I use the following macros so that I don’t have to maintain two sets of LaTeX files. Command “\ignorespaces” prevents LaTex from inserting a space (between sentences).

% ============================================================
% Is this a technical report?
% If not, comment out the following line.
% \def\techreport{true}
% ============================================================
% Tech report or paper?
\ifx\techreport\undefined
 % Paper
 \newcommand{\onlytech}[1]{\ignorespaces}
 \newcommand{\onlypaper}[1]{#1}
 % Add more if necessary.
\else
 % Technical reports
 \newcommand{\onlytech}[1]{#1}
 \newcommand{\onlypaper}[1]{\ignorespaces}
 % Add more if necessary.
\fi

In the document environment:

\onlypaper{This sentence only appears in the paper.}
\onlytech{This sentence shows in the tech report only.}

Redefine colorswinpho8colors

\definecolor{red}{HTML}{E51400} %red
\definecolor{blue}{HTML}{0050EF} %cobalt
\definecolor{green}{HTML}{008A00} %emerald
\definecolor{purple}{HTML}{AA00FF} %violet

Windows Theme colors: http://www.creepyed.com/2012/11/windows-phone-8-theme-colors-hex-rgb/

Change colors of URLs/references

\hypersetup{
colorlinks,  % remove the box
linkcolor=red,
citecolor=green,
urlcolor=blue
}

About Equations

How to rescale equations formatted using ‘align’

\noindent
\resizebox{.95\columnwidth}{!}{
 \begin{minipage}{\columnwidth}
 \begin{align*}
  x &= y \\
  x &= y
 \end{align*}
 \end{minipage}
}

Ref: http://stackoverflow.com/questions/22734142/how-to-rescale-equations-formatted-using-align-resizebox-doesnt-appear-to-wo

About Tables

Automatically resize the width of a table

The command “\resizebox” is useful for resizing other things too.

\begin{table}
\centering
\caption{..}
\resizebox{\columnwidth}{!}{
\begin{tabular}.....
\end{tabule}
}
\end{table}

About Theorems & Proofs

Packages: thmtools, thm-restate

This package is useful when I have to restate theorems in the appendix.

Documentation: http://mirror.unl.edu/ctan/macros/latex/exptl/thmtools/thmtools.pdf

Customize the proof environment

\renewcommand{\proofname}{\rm\bf{Proof:}}
\renewcommand\qedsymbol{\rule{1.8mm}{2.5mm}} % a slim balck square

About The Appendix

Show the appendix in the technical reports only.

\ifx\techreport\undefined
  % Paper, ...
\else
  % Tech report
  \clearpage
  \appendix
  \setcounter{section}{1}
  \input{appendix_file}
\fi

About tikz

Manual:

http://ftp.yzu.edu.tw/CTAN/graphics/pgf/base/doc/pgfmanual.pdf

Common line types

solid, (densely loosely) dotted, (densely loosely) dashed, (densely loosely) dashdotdotted

https://www.ubuntu-user.com/Magazine/Archive/2014/22/Creating-vector-graphics-with-LaTeX-and-TikZ/(offset)/2#article_f3)

Squeezing Space

Squeezing the space between theorems and the main text

\makeatletter
\def\thm@space@setup{
 \thm@preskip=0.8\topsep
 \thm@postskip=\thm@preskip % or whatever, if you don't want them to be equal
}
\makeatother

Squeezing the space between figures and their caption

\usepackage[skip=4pt,font={bf}]{caption}
\captionsetup[subfloat]{captionskip=2pt}

Squeezing other spacings

% Put these commands after "begin document"
\setlength{\textfloatsep}{1pt}
\setlength{\dbltextfloatsep}{1pt}
\setlength{\floatsep}{1pt}
\setlength{\dblfloatsep}{1pt}
\setlength{\abovedisplayskip}{0.6\baselineskip}
\setlength{\belowdisplayskip}{0.6\baselineskip}

For ACM templates

Remove the copyright box

\ifx\techreport\undefined
\else
 \makeatletter
 \def\@copyrightspace{\relax}
 \makeatother
\fi

Other links

Squeezing Space in LaTeX: http://www-h.eng.cam.ac.uk/help/tpl/textprocessing/squeeze.html#Contentsandbibliography

What commands are there for horizontal spacing?http://tex.stackexchange.com/questions/74353/what-commands-are-there-for-horizontal-spacing

Learning Influence Probabilities In Social Networks

In my personal research about influence maximization, I need datasets with learned influence probabilities.

This post is about two things.

  • The tool that I’ve been using.
  • The datasets that I’ve found, and how I deal with different datasets.

Background

Goal: Learn influence probabilities in social networks.

Paper: Goyal, A., Bonchi, F., & Lakshmanan, L. V. (2010, February). Learning influence probabilities in social networks. In Proceedings of the third ACM international conference on Web search and data mining (pp. 241-250). ACM.

Source Codes:

  • http://www.cs.ubc.ca/~goyal/code-release.php
  • Download codes for this paper: Amit Goyal, Francesco Bonchi, Laks V.S. Lakshmanan, A Data-based approach to Social Influence Maximization, To appear in PVLDB 2012.
  • For more details about the software, please refer to the readme file inside. I will only focus on how to use the tool to learn influence probabilities on edges.

Compilation:

  • Simply “Make” (I am using Archlinux & GCC5.3.0)
  • Solution to the error “getpid was not declared in this scope”:
    • Add #include <unistd.h>

Bernoulli distribution under the static model:

  • Static model: independent of time and simply to learn
  • Bernoulli distribution under the static model: p_{v,u}= A_{v2u} / A_{v}
    • p_{v,u}: learned influence probability of v on u
    • A_{v2u}: the number of actions propagated from v to u
    • A_{v}: the number of actions v performed
    • The first scan of the tool outputs A_{v2u} and A_{v}.

Now, we try to fit influence probabilities for some public datasets. (Warning: I’m still extremely new to Python, so please forgive me if codes look ugly…)

Flixster Dataset

  • Download here: http://www.cs.ubc.ca/~jamalim/datasets/
    • Download the main dataset
    • Download “The ratings in Flixster are associated with timestamps”
  • Prepare the file “graph.txt”
    • Append a zero column to links.txt
    • Desired format: Each line contains “user_from user_to 0”.
  • Prepare the file “actions_log.txt”
    • Preprocess Ratings.time.txt as follows
    • Remove the first line
    • Remove the third column (rating)
    • Convert the date column (the last column) to a column of timestamps
    • Sort action logs on action-ids and tuples on an action are chronologically ordered.
    • Desired format: Each line contains “user_id action_id timestamp”.
  • Prepare the file “actions_ids.txt”
    • Desired format: Each line contains an action id
  •  Misc.
    • Clean the file:  iconv -f utf-8 -t utf-8 -c Ratings.timed.txt > ratings.timed.txt

The preprocessing step

#!/usr/bin/env python
import time
from datetime import date, datetime
from igraph import *

# Input: links.txt (undirected)
# Output grpah.txt
# Read the graph
g = Graph.Read_Edgelist("raw/links.txt", directed=False)
print("Number of nodes: ", g.vcount())
print("Number of undirected edges: ", g.ecount())
# Simplify
g = g.simplify()
g.es["weight"] = 0  # dummy weight
print("After simplify:")
print("Number of nodes: ", g.vcount())
print("Number of undirected edges: ", g.ecount())
# Output the undirected graph (with weights)
g.write_ncol("learn/graph_undir.txt", names=None)
g.to_directed(mutual=True)
# Output the directed graph (with weights)
print("Number of directed edges: ", g.ecount())
g.write_ncol("learn/graph_dir.txt", names=None)

# Input: ratings.timed.txt
# Output: actions.txt
fin_rating = open("raw/ratings.timed.txt", "r")
line = fin_rating.readline()  # skip the first line
movie_set = set()
action_logs = []
for line in fin_rating:
    arr = line.replace('\00', '').split()
    if len(arr) == 5 :
        user = int(arr[0])
        movie = int(arr[1])
        movie_set.add(movie)
        timestamp = int(datetime.strptime(arr[3], '%Y-%m-%d').strftime("%s"))
        action_logs.append([user, movie, timestamp])
fin_rating.close()
print("Number of logs: ", len(action_logs))
print("Number of action ids: ", len(movie_set))

# Sort action logs and output
print("Sorting action_logs...")
action_logs.sort(key = lambda t:(t[1],t[0],t[2]))
print("Writing action_logs...")
with open("learn/action_logs.txt", "w") as fout_action:
    for line in action_logs:
        if line[2] > 1000000000:
            fout_action.write("%d %d %d\n" % (line[0], line[1], line[2]))

# Output all action-ids
with open("learn/action_ids.txt", "w") as fout_actionid:
    for id in movie_set:
        fout_actionid.write("%d\n" % id)

Codes for converting the output file

  • Run: ./InfluenceModels -c config.txt
  • We convert file "edgesCounts.txt" to a file "inf_prob.txt" containing a set of directed edges with probabilities, using codes as follows.

My config file for InfluenceModels

# Config file for learning paramters (Scan 1)

phase : 1
computeUserInf : 0
graphFile : learn/graph_undir.txt
actionsFile : learn/action_logs.txt
outdir : learn 
maxTuples : 0
trainingActionsFile : learn/action_ids.txt

Now, we try to get a weighted directed graph. The weights are the learned influence probabilities. BTW, I only keep the largest weakly connected component.

#!/usr/bin/env python
from igraph import *

# Read the directed graph (output of preprocess.py)
g = Graph.Read_Ncol("learn/graph_dir.txt", directed=True)
g.es["weight"] = 0.0
print("Number of nodes: ", g.vcount())
print("Number of directed edges: ", g.ecount())

# Read actions performed by each user
print("Loading usersCounts...")
f_nodes = open("learn/usersCounts.txt", "r")
user_action = {}
for line in f_nodes:
    v, a_v = [int(x) for x in line.split()]
    user_action[v] = a_v
f_nodes.close()

# Read edges, and replace the weights in g by influence probabilities
print("Loading edgesCounts...")
f_edges = open("learn/edgesCounts.txt", "r")
for line in f_edges:
    line = line.split()
    u, v, a_u2v, a_v2u = [int(x) for x in line[0:4]]
    if u in user_action.keys() and v in user_action.keys():
        # u -> v
        uid = g.vs.find(str(u))
        vid = g.vs.find(str(v))
        eid_uv = g.get_eid(uid, vid, error=False)
        if eid_uv >=0 and user_action[u] > 0:
            g.es[eid_uv]["weight"] = round(float(a_u2v) / user_action[u], 6)
        # v -> u
        eid_vu = g.get_eid(vid, uid, error=False)
        if eid_vu >= 0 and user_action[v] > 0:
            g.es[eid_vu]["weight"] = round(float(a_v2u) / user_action[v], 6)
f_edges.close()

# Delete edges with zero influence probabilities
g.delete_edges(g.es.select(weight_le=0))
print("Number of edges after deletion: ", g.ecount())

lwcc = g.clusters(mode='weak').giant()
lwcc.vs["name"] = range(lwcc.vcount())
print("Largest weakly connected component")
print("Number of nodes: ", lwcc.vcount(), float(lwcc.vcount()) / g.vcount())
print("Number of directed edges: ", lwcc.ecount())

# Output to files
with open("flixster_learn/attribute.txt", "w") as f_attr:
    f_attr.write("n=%d\n" % lwcc.vcount())
    f_attr.write("m=%d\n" % lwcc.ecount())

lwcc.write_ncol("flixster_learn/graph_ic.inf")
with open("flixster_learn/graph_ic_nm.inf", "w") as f_graph_nm:
    f_graph_nm.write("%d %d\n" % (lwcc.vcount(), lwcc.ecount()))
    with open("flixster_learn/graph_ic.inf", "r") as f_tmp:
        f_graph_nm.write(f_tmp.read())

Other datasets

Here are several datasets that both user links and user action logs are available.

Compile the first igraph project in Visual Studio 2013

Download:

http://igraph.org/c/#downloads

Currently, I am testing igraph-0.7.1-msvc.

Compile the igraph library:

  1. Open the igraph.sln solution file in igraph-0.7.1-msvc from Visual Studio 2013. Let the Visual Studio convert the solution file for you.
  2. Add a compiler option (for both Debug and Release): Open Project menu -> Properties -> C/C++ -> Command Line. In Additional options, add the following option: “/DPRPACK_IGRAPH_SUPPORT=1” (without the quotes)
  3. Debug -> Build and Release -> Build

Compile igraphtest:

  1. Adding a path to the directory containing ‘igraph.lib’ (for both Debug and Release). Open Project -> Properties -> VC++ Directory -> Library Directory -> Edit. Add new path which points to the Debug/Release directory in your igraph directory (igraph-0.7.1-msvc folder/Debug, for example).
  2. Open Project -> Properties -> VC++ Directory -> Include Directory -> Edit. Add new path which points to the include directory in your igraph-0.7.1-msvc folder.
  3. Make sure “Project -> Properties -> Linker -> General -> Additional Library Directories” points to your igraph Debug/Release directory.
  4. Make sure the setting of “Project -> Properties -> C/C++ -> Code Generation -> Runtime Library” in the Debug mode (resp. Release mode) matches the setting in the Debug (resp. Release mode) mode of the igraph project.

Compile other projects:

  1. Error: “error LNK2001: unresolved external symbol “public: __thiscall prpack….”. Fix:
    1. Make a new folder “prpack” in your <your_project_src> folder.
    2. Copy igraph-0.7.1-msvc folder/prpack/prpack_*  to <your_project_src>/prpack folder.
    3. In Visual Studio 2013, Add prpack_* to your “Header Files” and “Source Files”
    4. Add a compiler option (for both Debug and Release): Open Project menu -> Properties -> C/C++ -> Command Line. In Additional options, add the following option: “/DPRPACK_IGRAPH_SUPPORT=1” (without the quotes)
    5. Edit your prpack_solver.cpp, add “#include <algorithm>#, otherwise you may see a compile error.
  2. Error during debugging: “Run time Check failure #3: *** is being used without being initialized”. I saw this error when I run the “example/eigenvector_centrality.c” provided by igraph. Because I do not want to modify their codes, here goes my fix (yes, I know turn this off is not a good idea):
    1. While compiling igraph and your project, set “Open Project -> Properties -> C/C++ -> Code Generation -> Basic Runtime Checks” as “Default”.

The above steps help me compile my first igraph project successfully finally. I will keep updating this list if I see more errors…

Reference:

  1. https://dungleba.wordpress.com/2014/10/14/installing-igraph-in-visual-studio-2013/
  2. http://stackoverflow.com/questions/26579997/igraph-c-compiling-link-errors-in-visual-studio

PPT to EPS without Acrobat Pro (Windows)

Step 1: Add an ps/eps printer
Control Panel -> View devices and printers -> Add a printer ->
Add a local printer -> Use an existing port (FILE: print to file) ->
Choose a color printer with suffix “PS” -> next next next until it’s done

Step 2: Prepare a PPT to print
Open a new PPT ->
Design -> Page Setup (Choose protrait for slides orientation and let height > width)
Copy-and-pasge / draw something in PPT

Step 3: Get a PS
File -> print -> choose the new printer you just added -> printer properties ->
Advanced -> Postscript Options -> PostScript Output Option : EPS -> OK and print
(Remember to scale your PPT to fit paper.)

printer_setting

printer_setting

Step 4: Adjusting the bounding box
Rename the file you get (may be *.prn) to *.eps and open it with GSview
File -> PS to EPS -> DO NOT Automatically calculate Bounding Box -> Yes -> Set the bounding box by your self and save as a new_file.eps

I got problems when I try to use \includegraphics{xx.eps} (pdfLatex). There are unwanted white margins. Here is how I solve this:
\includegraphics[bb=33 420 579 618, width=3in]{k_state}
What is bb (bounding box)? You can open your eps file with NotePad or something else, then you will see something like “%%BoundingBox: 55 410 527 720”.

Learning to use Sublime Text 3

(Updating…)

Packages that I installed:

  1. Package control:
    Installation: https://sublime.wbond.net/installation
    Usage instruction: https://sublime.wbond.net/docs/usage

Package Control is driven by the Command Pallete. To open the pallete, press ctrl+shift+p (Win, Linux) or cmd+shift+p (OS X). All Package Control commands begin with Package Control:, so start by typing Package.

  1. Terminal:
    Launch terminals from the current file or the root project folder
    Installation: https://sublime.wbond.net/packages/Terminal
    Usage instruction: http://wbond.net/sublime_packages/terminal

Open Terminal at File
Press ctrl+shift+t on Windows and Linux, or Cmd+Shift+t on OS X
Open Terminal at Project Folder
Press ctrl+alt+shift+t on Windows and Linux, or Cmd+Alt+Shift+t on OS X

  1. VAlign
    I first installed Alignment, but it does not work for my sublime text 3.
    This one works.
    Installation: https://sublime.wbond.net/packages/VAlign
    Usage: Select multiple lines and press Ctrl+.

Things to do about 32-bit and 64-bit programs

How to determining 32/64 bits in C/C++

Source: http://stackoverflow.com/questions/1505582/determining-32-vs-64-bit-in-c

// Check windows
#if _WIN32 || _WIN64
#if _WIN64
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif

// Check GCC
#if __GNUC__
#if __x86_64__ || __ppc64__
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif

How to compile 32 bit programs on 64 bit Ubuntu OS

Source:
How to compile a 32-bit application using gcc on the 64-bit Linux version

I am using Ubuntu 13.10. When I tried ‘gcc -m32 -o output32 hello.c’, I got this:

In file included from :0:0:
/usr/include/stdc-predef.h:30:26: fatal error: bits/predefs.h: No such file or directory
 #include 
                          ^
compilation terminated.

Solution for this error: sudo apt-get install gcc-multilib.

Ubuntu

Just mark something that I have tried.

Fcitx-sougoupinyin Installation

sudo apt-get remove ibus
sudo add-apt-repository ppa:fcitx-team/nightly
sudo apt-get update
sudo apt-get install fcitx fcitx-sougoupinyin
sudo apt-get install install fcitx-table-all
sudo apt-get install language-selector-gnome

Now you can find “Language Support” in “Settings”,Choose “Fcitx” in “Keybord input method system”. Log in again, and you can see Fcitx right there. # Dropbox How To Fix The Dropbox GUI And Indicator Issue On Ubuntu 13.10 Saucy Salamander

The Dropbox client has some issues, when installed on the brand new Ubuntu 13.10 Saucy Salamander. The sync works properly, but the user is not allowed to access the Dropbox GUI and the indicator is missing. This may be caused by the latest update of Unity 7, which does not fully support Dropbox yet.

sudo apt-get update
sudo apt-get install libappindicator1

Other materials

Mount a remote SSH folder in Ubuntu (cmd and GUI)

Things To Do After Installing Ubuntu 13.10

How to fix Wired Network interface “Device not managed” error in Debian or Kali Linux?

How to backup and restore Ubuntu