classification
Contents
5.5. classification#
5.5.1. overview#
regressors don’t classify well
e.g. outliers skew fit
asymptotic classifier - assumes infinite data
linear classifer \(\implies\) boundaries are hyperplanes
discriminative - model \(P(Y\vert X)\) directly
usually lower bias \(\implies\)smaller asymptotic error
slow convergence ~ \(O(p)\)
generative - model \(P(X, Y) = P(X\vert Y) P(Y)\)
usually higher bias \(\implies\) can handle missing data
this is because we assume some underlying X
fast convergence ~ \(O[\log(p)]\)
decision theory - models don’t require finding \(p(y \vert x)\) at all
5.5.2. binary classification#
\(\hat{y} = \text{sign}(\theta^T x)\)
usually \(\theta^Tx\) includes bias term, but generally we don’t want to regularize bias
Model |
\(\mathbf{\hat{\theta}}\) objective (minimize) |
|---|---|
Perceptron |
\(\sum_i \max(0, -y_i \cdot \theta^T x_i)\) |
Linear SVM |
\(\theta^T\theta + C \sum_i \max(0,1-y_i \cdot \theta^T x_i)\) |
Logistic regression |
\(\theta^T\theta + C \sum_i \log[1+\exp(-y_i \cdot \theta^T x_i)]\) |
svm, perceptron use +1/-1, logistic use 1/0
perceptron - tries to find separating hyperplane
whenever misclassified, update w
can add in delta term to maximize margin
5.5.3. multiclass classification#
reducing multiclass (K categories) to binary
one-against-all
train K binary classifiers
class i = positive otherwise negative
take max of predictions
one-vs-one = all-vs-all
train \(C(K, 2)\) binary classifiers
labels are class i and class j
inference - any class can get up to k-1 votes, must decide how to break ties
flaws - learning only optimizes local correctness
single classifier - one hot vector encoding
multiclass perceptron (Kesler)
if label=i, want \(\theta_i ^Tx > \theta_j^T x \quad \forall j\)
if not, update \(\theta_i\) and \(\theta_j\)* accordingly
kessler construction
\(\theta = [\theta_1 ... \theta_k] \)
want \(\theta_i^T x > \theta_j^T x \quad \forall j\)
rewrite \(\theta^T \phi (x,i) > \theta^T \phi (x,j) \quad \forall j\)
here \(\phi (x, i)\) puts x in the ith spot and zeros elsewhere
\(\phi\) is often used for feature representation
define margin: \(\Delta (y,y') = \begin{cases} \delta& if \: y \neq y' \\ 0& if \: y=y'\end{cases}\)
check if \(y=\text{argmax}_{y'} \theta^T \phi(x,y') + \delta (y,y')\)
multiclass SVMs (Crammer & Singer)
minimize total norm of weights s.t. true label score is at least 1 more than second best label
multinomial logistic regression = multi-class log-linear model (softmax on outputs)
we control the peakedness of this by dividing by stddev
5.5.4. discriminative#
<IP_ADDRESS>. logistic regression#
\(p(Y=1|x, \theta) = \text{logistic}(\theta^Tx)\)
assume Y ~ \(\text{Bernoulli}(p)\) with \(p=\text{logistic}(\theta^Tx\))
can solve this online with GD of likelihood
better to solve with iteratively reweighted least squares
\(Logit(p) = \log[p / (1-p)] = \theta^Tx\)
multiway logistic classification
assume \(P(Y^k=1|x, \theta) = \frac{e^{\theta_k^Tx}}{\sum_i e^{\theta_i^Tx}}\), just as arises from class-conditional exponential family distributions
logistic weight change represents change in odds
fitting requires penalty on weights, otherwise they might not converge (i.e. go to infinity)
<IP_ADDRESS>. binary models#
probit (binary) regression
\(p(Y=1|x, \theta) = \phi(\theta^Tx)\) where \(\phi\) is the Gaussian CDF
pretty similar to logistic
noise-OR (binary) model
consider \(Y = X_1 \lor X_2 \lor … X_m\) where each has a probability of failing
define \(\theta\) to be the failure probabilities
\(p(Y=1|x, \theta) = 1-e^{-\theta^Tx}\)
other (binary) exponential models
\(p(Y=1|x, \theta) = 1-e^{-\theta^Tx}\) but x doesn’t have to be binary
complementary log-log model: \(p(Y=1|x, \theta) = 1-\text{exp}[e^{-\theta^Tx}]\)
<IP_ADDRESS>. svms#
svm benefits
maximum margin separator generalizes well
kernel trick makes it very nonlinear
nonparametric - retains training examples (although often get rid of many)
at test time, can’t just store w - have to store support vectors
\(\hat{y} =\begin{cases} 1 &\text{if } w^Tx +b \geq 0 \\ -1 &\text{otherwise}\end{cases}\)
\(\hat{\theta} = \text{argmin} \:\frac{1}{2} \vert \vert \theta\vert \vert ^2 \\s.t. \: y^{(i)}(\theta^Tx^{(i)}+b)\geq1, i = 1,...,m\)
functional margin \(\gamma^{(i)} = y^{(i)} (\theta^T x +b)\)
limit the size of \((\theta, b)\) so we can’t arbitrarily increase functional margin
function margin \(\hat{\gamma}\) is smallest functional margin in a training set
geometric margin = functional margin / \(\vert \vert \theta \vert \vert \)
if \(\vert \vert \theta \vert \vert =1\), then same as functional margin
invariant to scaling of w
derived from maximizing margin: $\(\max \: \gamma \\\: s.t. \: y^{(i)} (\theta^T x^{(i)} + b) \geq \gamma, i=1,..,m\\ \vert \vert \theta\vert \vert =1\)$
difficult to solve, especially because of \(\vert \vert w\vert \vert =1\) constraint
assume \(\hat{\gamma}=1\) ~ just a scaling factor
now we are maximizing \(1/\vert \vert w\vert \vert \)
soft margin classifier - allows misclassifications
assigns them penalty proportional to distance required to move them back to correct side
min \(\frac{1}{2}||\theta||^2 \textcolor{blue}{ + C \sum_i^n \epsilon_i} \\s.t. y^{(i)} (\theta^T x^{(i)} + b) \geq 1 \textcolor{blue}{- \epsilon_i}, i=1:m \\ \textcolor{blue}{\epsilon_i \geq0, 1:m}\)
large C can lead to overfitting
benefits
number of parameters remains the same (and most are set to 0)
we only care about support vectors
maximizing margin is like regularization: reduces overfitting
actually solve dual formulation (which only requires calculating dot product) - QP
replace dot product \(x_j \cdot x_k\) with kernel function \(K(x_j, x_k)\), that computes dot product in expanded feature space
linear \(K(x,z) = x^Tz\)
polynomial \(K (x, z) = (1+x^Tz)^d\)
radial basis kernel \(K (x, z) = \exp(-r\vert \vert x-z\vert \vert ^2)\)
transforming then computing is O(\(m^2\)), but this is just \(O(m)\)
practical guide
use m numbers to represent categorical features
scale before applying
fill in missing values
start with RBF
valid kernel: kernel matrix is Psd
<IP_ADDRESS>. decision trees / rfs - R&N 18.3; HTF 9.2.1-9.2.3#
follow rules: predict based on prob distr. of points in same leaf you end up in
inductive bias
prefer small trees
prefer tres with high IG near root
good for certain types of problems
instances are attribute-value pairs
target function has discrete output values
disjunctive descriptions may be required
training data may have errors
training data may have missing attributes
greedy - use statistical test to figure out which attribute is best
split on this attribute then repeat
growing algorithm
information gain - decrease in entropy
weight resulting branches by their probs
biased towards attributes with many values
use GainRatio = Gain/SplitInformation
can incorporate SplitInformation - discourages selection of attributes with many uniformly distributed values
sometimes SplitInformation is very low (when almost all attributes are in one category)
might want to filter using Gain then use GainRatio
regression tree
must decide when to stop splitting and start applying linear regression
must minimize SSE
can get stuck in local optima
avoid overfitting
empirically, early stopping is worse than overfitting then pruning (bc it doesn’t see combinations of useful attributes)
overfit then prune - proven more succesful
reduced-error pruning - prune only if doesn’t decrease error on validation set
\(\chi^2\) pruning - test if each split is statistically significant with \(\chi^2\) test
rule post-pruning = cost-complexity pruning
infer the decision tree from the training set, growing the tree until the training data is fit as well as possible and allowing overfitting to occur.
convert the learned tree into an equivalent set of rules by creating one rule for each path from the root node to a leaf node.
these rules are easier to work with, have no structure
prune (generalize) each rule by removing any preconditions that result in improving its estimated accuracy.
sort the pruned rules by their estimated accuracy, and consider them in this sequence when classifying subsequent instances.
incorporating continuous-valued attributes
choose candidate thresholds which separate examples that differ in their target classification
just evaluate them all
missing values
could fill in most common value
could assign values probabilistically
differing costs
can bias the tree to favor low-cost attributes
ex. divide gain by the cost of the attribute
high variance - instability - small changes in data yield changes to tree
many trees
bagging = bootstrap aggregation - an ensemble method
bootstrap - resampling with replacement
train multiple models by randomly drawing new training data
bootstrap with replacement can keep the sampling size the same as the original size
random forest - for each split of each tree, choose from only m of the p possible features
smaller m decorrelates trees, reduces variance
RF with m=p \(\implies\) bagging
voting
consensus: take the majority vote
average: take average of distribution of votes
reduces variance, better for improving more variable (unstable) models
adaboost - weight models based on their performance
optimal classification trees - simultaneously optimize all splits, not one at a time
importance scores
dataset-level
for all splits where the feature was used, measure how much variance reduced (either summed or averaged over splits)
the sum of importances is scaled to 1
prediction-level: go through the splits and add up the changes (one change per each split) for each features
note: this bakes in interactions of other variables
ours: only apply rules based on this variable (all else constant)
why not perturbation based?
trees group things, which can be nice
trees are unstable
<IP_ADDRESS>. decision rules#
if-thens, rule can contain ands
good rules have large support and high accuracy (they tradeoff)
decision list is ordered, decision set is not (requires way to resolve rules)
most common rules: Gini - classification, variance - regression
ways to learn rules
oneR - learn from a single feature
sequential covering - iteratively learn rules and then remove data points which are covered
ex rule could be learn decision tree and only take purest node
bayesian rule lists - use pre-mined frequent patterns
generally more interpretable than trees, but doesn’t work well for regression
features often have to be categorical
rulefit
learns a sparse linear model with the original features and also a number of new features that are decision rules
train trees and extract rules from them - these become features in a sparse linear model
feature importance becomes a little stickier….
5.5.5. generative#
<IP_ADDRESS>. gaussian class-conditioned classifiers#
binary case: posterior probability \(p(Y=1|x, \theta)\) is a sigmoid \(\frac{1}{1+e^{-z}}\) where \(z = \beta^Tx+\gamma\)
multiclass extends to softmax function: \(\frac{e^{\beta_k^Tx}}{\sum_i e^{\beta_i^Tx}}\) - \(\beta\)s can be used for dim reduction
probabilistic interpretation
assumes classes are distributed as different Gaussians
it turns out this yields posterior probability in the form of sigmoids / softmax
only a linear classifier when covariance matrices are the same (LDA)
otherwise a quadratic classifier (like QDA) - decision boundary is quadratic
MLE for estimates are pretty intuitive
decision boundary are points satisfying \(P(C_i\vert X) = P(C_j\vert X)\)
regularized discriminant analysis - shrink the separate covariance matrices towards a common matrix
\(\Sigma_k = \alpha \Sigma_k + (1-\alpha) \Sigma\)
parameter estimation: treat each feature attribute and class label as random variables
assume distributions for these
for 1D Gaussian, just set mean and var to sample mean and sample var
can use directions for dimensionality reduction (class-separation)
<IP_ADDRESS>. naive bayes classifier#
assume multinomial Y
with clever tricks, can produce \(P(Y^i=1|x, \eta)\) again as a softmax
let \(y_1,...y_l\) be the classes of Y
want Posterior \(P(Y\vert X) = \frac{P(X\vert Y)(P(Y)}{P(X)}\)
MAP rule - maximum a posterior rule
use prior P(Y)
given x, predict \(\hat{y}=\text{argmax}_y P(y\vert X_1,...,X_p)=\text{argmax}_y P(X_1,...,X_p\vert y) P(y)\)
generally ignore constant denominator
naive assumption - assume that all input attributes are conditionally independent given y
\(P(X_1,...,X_p\vert Y) = P(X_1\vert Y)\cdot...\cdot P(X_p\vert Y) = \prod_i P(X_i\vert Y)\)
learning
learn L distributions \(P(y_1),P(y_2),...,P(y_l)\)
for i in 1:\(\vert Y \vert\)
learn \(P(X \vert y_i)\)
for discrete case we store \(P(X_j\vert y_i)\), otherwise we assume a prob. distr. form
naive: \(\vert Y\vert \cdot (\vert X_1\vert + \vert X_2\vert + ... + \vert X_p\vert )\) distributions
otherwise: \(\vert Y\vert \cdot (\vert X_1\vert \cdot \vert X_2\vert \cdot ... \cdot \vert X_p\vert )\)
smoothing - used to fill in 0s
\(P(x_i\vert y_j) = \frac{N(x_i, y_j) +1}{N(y_j)+\vert X_i\vert }\)
then, \(\sum_i P(x_i\vert y_j) = 1\)
<IP_ADDRESS>. exponential family class-conditioned classifiers#
includes Gaussian, binomial, Poisson, gamma, Dirichlet
\(p(x|\eta) = \text{exp}[\eta^Tx - a(\eta)] h(x)\)
for classification, anything from exponential family will result in posterior probability that is logistic function of a linear function of x
<IP_ADDRESS>. text classification#
bag of words - represent text as a vector of word frequencies X
remove stopwords, stemming, collapsing multiple - NLTK package in python
assumes word order isn’t important
can store n-grams
multivariate Bernoulli: \(P(X\vert Y)=P(w_1=true,w_2=false,...\vert Y)\)
multivariate Binomial: \(P(X\vert Y)=P(w_1=n_1,w_2=n_2,...\vert Y)\)
this is inherently naive
time complexity
training O(n*average_doc_length_train+\(\vert c\vert \vert dict\vert \))
testing O(\(\vert Y\vert \) average_doc_length_test)
implementation
have symbol for unknown words
underflow prevention - take logs of all probabilities so we don’t get 0
\(y = \text{argmax }\log \:P(y) + \sum_i \log \: P(X_i\vert y)\)
5.5.6. instance-based (nearest neighbors)#
also called lazy learners = nonparametric models
make Voronoi diagrams
can take majority vote of neighbors or weight them by distance
distance can be Euclidean, cosine, or other
should scale attributes so large-valued features don’t dominate
Mahalanobois distance metric accounts for covariance between neighbors
in higher dimensions, distances tend to be much farther, worse extrapolation
sometimes need to use invariant metrics
ex. rotate digits to find the most similar angle before computing pixel difference
could just augment data, but can be infeasible
computationally costly so we can approximate the curve these rotations make in pixel space with the invariant tangent line
stores this line for each point and then find distance as the distance between these lines
finding NN with k-d (k-dimensional) tree
balanced binary tree over data with arbitrary dimensions
each level splits in one dimension
might have to search both branches of tree if close to split
finding NN with locality-sensitive hashing
approximate
make multiple hash tables
each uses random subset of bit-string dimensions to project onto a line
union candidate points from all hash tables and actually check their distances
comparisons
error rate of 1 NN is never more than twice that of Bayes error
5.5.7. likelihood calcs#
<IP_ADDRESS>. single Bernoulli#
\(L(p) = P\)[Train | Bernoulli(p)]= \(P(X_1,...,X_n\vert p)=\prod_i P(X_i\vert p)=\prod_i p^{X_i} (1-p)^{1-X_i}\)
\(=p^x (1-p)^{n-x}\) where x = \(\sum x_i\)
\(\log[L(p)] = \log[p^x (1-p)^{n-x}]=x \log(p) + (n-x) \log(1-p)\)
\(0=\frac{dL(p)}{dp} = \frac{x}{p} - \frac{n-x}{1-p} = \frac{x-xp - np+xp}{p(1-p)}=x-np\)
\(\implies \hat{p} = \frac{x}{n}\)
<IP_ADDRESS>. multinomial#
\(L(\theta) = P(x_1,...,x_n\vert \theta_1,...,\theta_p) = \prod_i^n P(d_i\vert \theta_1,...\theta_p)=\prod_i^n factorials \cdot \theta_1^{x_1},...,\theta_p^{x_p}\)- ignore factorials because they are always same
require \(\sum \theta_i = 1\)
\(\implies \theta_i = \frac{\sum_{j=1}^n x_{ij}}{N}\) where N is total number of words in all docs
5.5.8. boosting#
adaboost
freund & schapire
reweight data points based on errs of previous weak learners, then train new classifiers
classify as an ensemble
gradient boosting
leo breiman
actually fits the residual errors made by the previous predictors
newer algorithms for gradient boosting (speed / approximations)
xgboost (2014 - popularized around 2016)
implementation of gradient boosted decision trees designed for speed and performance
things like caching, etc.
light gbm (2017)
can get gradient of each point wrt to loss - this is like importance for point (like weights in adaboost)
when picking split, filter out unimportant points
Catboost (2017)
boosting with different cost function (\(y \in \{-1, 1\}\), or for \(L_2\)Boost, also \(y \in \mathbb R\))
Adaboost
LogitBoost
\(L_2\)Boost
\(\exp(y\hat{y})\)
\(\log_2 (1 + \exp(-2y \hat y ))\)
\((y - \hat y)^2 / 2\)


Chamisa’s ally Tinashe Kambarami wins court case
by Staff ReporterReports coming from Tredgold building indicate that the former Bulawayo Deputy Mayor Tinashe Kambarami and Councillor Silas Chigora have been acquitted by magistrate Shepherd Mjanji on a charge of malicious damage to Bulawayo City Council property.
According to online publication CITE the court said the state did not provide enough evidence to obtain a conviction.
State witnesses Tobias Dube and Richard Ndlovu who are said to be employed by the City Council under the security department are reported to have testified that they did not see the two accused persons break the alleged property.
Another witness who is a police officer Golden Sibanda testified that he and other police officers were only called in to rescue the two councillors who had hidden in the mayor’s box after a mob wanted to lynch them.
The pair were arrested in July this year after a fight with the Town Clerk Christopher Dube.
More details to follow…


js/jqListbox.plugin-1.3.js
file to your web root (or in a subfolder)div
) which will contain your list
container element.
ul
list under a
div
element
you can style your div
as fixed height and overflow: auto
to
imitate a listbox with scroll.
ul
) which will contain your list
items.
.jqListbox()
on the element containing your list items. When a
new item will be appended
it will be appended into your container element. Don't confuse the optional wrapper element
created for styling and the container element containing your list items!
ul
list you must call .jqListbox
on the
ul
element: $('ul#myul').jqListbox();
li
).
Items will be matched with the defined itemSelector
relative to your container element
like
$('ul#myul').find(itemSelector);
.jqListbox()
on your container element after jQuery and jqListbox loaded
and the DOM is ready
Container: the main container for all of your items. If you are using a list
then the container can be the

element.
You must call .jqListbox()
on your container element.
Wrapper: an optional element containing your container element mainly because of styling via CSS.
Item: one of your item in your listbox.
listboxValueEncoder: a function which will be called any time your listbox has
changed (insert, update, etc). The array of the stored items will be passed to this function. Your
function must return a value which can be used for example to post back to your backend application
and save it. It is recommended to use JSON.stringify()
listboxValueDecoder: a function which will be called when you need to decode your
elements. This function is used when the initial values is set from a value generated by the
listboxValueEncoder
.
itemRenderer: a function which will be called when your items are rendered. This function is called once for every item so you must return a string or jQuery object which must be appended to your list container element.
JSON: JavaScript Object Notation. Text representation of JavaScript objects. Read more here and here.
This plugin needs jQuery 1.x (tested with 1.11.3), 2.x (tested with 2.1.4) or 3.x (tested with 3.2.1). You can download jQuery from here or you can use the jQuery CDN. You must include jQuery on every page where jqListbox is used.
Once jQuery is included you must include jqListbox after jQuery is loaded.
For production sites you should use the minified version of the plugin (filename ends with
.min.js
).

No specific style sheet is needed for the jqListbox plugin. Also no style sheets are included in the package.
You can use this plugin with your own CSS styles.
You can use any structure you like! Just ensure that your items are wrapped under a container.
You will need a container which holds your items. You can initialize the plugin on this container. Also typically you will need to declare when and how to insert, update, remove and render items.
Item selector must be defined relative to your container element because it will be matched
with $(container).find(itemSelector);
when needed!
The default itemSelector is li
.
You can override this option via the option itemSelector
.
In the following example your container element will be ul#customlist
while your
items will be the li
tags.

 ...
Simply call the plugin jqListbox()
on your container element. You can define custom
options as a passed parameter object.

ul
and li
tags wrapped under a container div
. Watch out for comments and
descriptions. Check the inline documentation in the source file for reference!

 ...
The itemRenderer
function defines how an item is rendered. The default is to render li
items
from a basic Array of string
structure (var items = ['Item','Item',...];
).
The itemRenderer
function will be called every time a rendering is needed. The actual
rendered item, its position and the instance of the current jqListbox will be passed as parameters.
In this example we are assuming that your items are Objects which contains a field
and a
price
property which needs to be rendered.

The listboxValueEncoder
function produces the result of your listbox (remember the image
on the top of the documentation).
jqListbox supporting setting this value in an input by default (see option targetInput
) but
it is up to you what to do with this value. Typically you want to post it back to your backend
application to save it.
The default function used by jqListbox is to convert your array of items to a JSON string. Typically
this is what you need: encode your values to JSON string - later you can decode this string on
backend side if needed (json_decode
in PHP) to save in DB for example.
If you need something else then JSON.stringify()
for encoding the values of your listbox
just fire up your own function via the option listboxValueEncoder
.
By default jqListbox will try to set this value in an input with id #listbox-value
.
You can override this selector with the option targetInput
. Set the value of this option
to false
to completely disable this functionality and do it on your own.
Now for the example we will modify the targetInput
selector to point to our newly created
hidden input. We must add a dummy form above our ul
list.
 <form id="target-form" method="post" action="/post.php"> <input type="hidden" name="output" id="output"> </form>

 ...
If you need custom output logic
The onAfterRender
event will be triggered any time when the listbox has changed and
re-rendered
so it is good to put new output rendering logic there. Don't forget to disable the
targetInput
option if you need custom logic! Check out the options below.
A decoder is needed if you want to initialize/pre-set elements in your listbox from encoded values.
Generally the listboxValueDecoder
function is the opposite function of the listboxValueEncoder
.
The default value of the listboxValueDecoder
is a function which calls the JSON.parse()
,
the opposite of JSON.stringify()
- so it will return the original array of your items.
If you remember we are already using the default function of listboxValueEncoder
so we are
good
to also leave the default option for listboxValueEncoder
for now.
For inserting, updating, deleting your elements you should add some action buttons. You must define your own logic for this actions and call jqListbox's methods to handle your items.
For this example we are creating a button and add a new item on click.
Insert new element
Updating is similar to inserting: you must call the update
method to update
the selected item.
If multiple selection is allowed and more than one element is selected then you can update
all of them with the same data or pass an array of updated elements to update each selected
element with different data (so you must pass one updated element for every selected element) to the
updateMulti
method. Yes, there are two update methods: the update
and the
updateMulti
(and the third is the updateAt
).
Update element
Also deletion is similar to updating. Calling the remove
method will remove
all of the selected elements.
Remove selected
Calling the clear
method will remove all of the elements.
Clear
The built-in moveup
method supports multiple selection.
When calling moveup
all of the selected items will be moved up by one position.
If the very-first element is moved up it will be moved to the end of the list and all other elements
will be pushed up by one position.
Move up
The built-in movedown
method supports multiple selection.
When calling movedown
all of the selected items will be moved down by one position.
If the very-last element is moved down it will be moved to the beginning of the list and all other
elements
will be pushed down by one position.
Move up
Of course you don't want to enable the update or remove action if no items are selected. You can easily do this by setting up some easy logic.
The onBeforeRender
or the onAfterRender
are two good candidates for
this kind of logics.
What you want is: if no element is selected (countSelected()
method returns 0) then
disable the update,remove,moveup and movedown actions. In this example we just add a disabled class
to these buttons.

There are a lot of callbacks triggered by different events: for example you can fire up some custom logic before a new element is inserted or elements are updated. Also you can change the newly inserted element before the insertion, etc. There are a lot of possibilities in these callbacks!
You can use the following methods in jqListbox.
Every method can be accessed via the jqListbox instance but there are some methods which are
intended for internal use only - for example you won't need to call setupAutoClickHandler by hand.
I'm listing only the methods intended for use in your code - however you can check all of the methods
in the documented source file.
Call these methods on the jqListbox instance on your element like $('#customlist').jqListbox('remove');
.
Simply pass parameters like $('#customlist').jqListbox('removeByIndex', 4);
. In the
callbacks where the
current instance is passed you can simply use the methods of the passed instance (like listbox.removeByIndex(4);
| Method | Description | Parameters | Returns |
|---|---|---|---|
| count | Returns the number of elements in the listbox. | - |
int - the length of the listbox
|
| countSelected | Returns the number of selected elements in the listbox. | - |
int
|
| reset | Resets the listbox: clear, initialize items based on the options and renders the initial state. | - | - |
| render | Renders the listbox (items) and the output value. | - | - |
| insert | Inserts a new item at the end of the listbox. |
item - the new item
|
int - the new length of the listbox
|
| insertAt | Inserts a new item at the given position. Negative value means counting for the end (0 means first position, -1 means last position). |
item - the new item
position - the position
|
int - the new length of the listbox
|
| insertMulti | Inserts multiple items at the end of the listbox |
items - array of new items
|
int - the new length of the listbox
|
| insertMultiAt | Inserts multiple items at the given position. Negative value means counting for the end (0 means first position, -1 means last position). |
items - array of new items
position - the position
|
int - the new length of the listbox
|
| update | Updates the selected element(s). If multiple elements are selected then all of the elements will be updated with the passed data. |
updatedItem - data (Object) of the new item
|
int - the number of the selected items
|
| updateMulti | Updates the selected element(s). You must pass as many updated items as many items are selected: each of them will be updated with the next item in the array (0-0, 1-1, etc.) |
updatedItems - array of new items
|
int - the number of the selected items
|
| updateAt | Updated the item in the given position. Negative value means counting for the end (0 means first position, -1 means last position). |
updatedItem - the new item
position - the position
|
Object - the updated item data
|
| remove | Removes all of the selected items | - |
int - the new length of the listbox
|
| removeByIndex | Removes an item in the given position. |
position - the position
|
int - the new length of the listbox
|
| clear | Removes all items | - | - |
| moveup | Moves up selected items by one position. | - | - |
| moveupByIndex | Moves up the item in position by one. |
position - the position
|
- |
| movedown | Moved down selected items by one position. | - | - |
| movedownByIndex | Moved down the item in position by one. |
position - the position
|
- |
| switchElements | Switches to elements by position. |
pos1 - the position
pos2 - the position
|
- |
| shiftElementsUp | Shift every elements by one position up | - | - |
| shiftElementsDown | Shift every elements by one position down | - | - |
| transferSelectedTo | Transfer the currently selected elements to another jqListbox instance. |
listbox - the another container of the jqListbox instance. This must be the
jQuery element for example $('#anotherlistbox') .
copy - optional. Set this parameter to true if you want to
copy the elements instead of move (transfer).
|
- |
| transferByIndexTo | Transfer one element in the given position to another jqListbox instance. |
listbox - the another container of the jqListbox instance. This must be the
jQuery element for example $('#anotherlistbox') .
index - the index of the element to copy/move.
copy - optional. Set this parameter to true if you want to
copy the element instead of move (transfer).
|
- |
| transferByIndexMultiTo | Transfer multiple elements by position to another jqListbox instance. |
listbox - the another container of the jqListbox instance. This must be the
jQuery element for example $('#anotherlistbox') .
indices - the array of indices of the elements to copy/move.
copy - optional. Set this parameter to true if you want to
copy the elements instead of move (transfer).
|
- |
| getItemByIndex | Returns the item in position. Range checks must be done by you! |
pos - the position
|
Object |
| getTargetValue |
Returns the target (encoded) value of the listbox by calling listboxValueEncoder
and
returning its return value.
|
- |
string|Object - the return value of the listboxValueEncoder function
|
| setFromTargetValue |
Overwrite the current internally stored array from the passed encoded value by calling the
listboxValueDecoder function.
|
data
|
int - the new length of the listbox
|
| getAsArray | Returns the internally stored array of the items. | - |
Array
|
| setFromArray | Overwrite the current internally stored array with the provided new one. Render and other methods won't be called. |
newItems - the array of the new items
|
int - the new length of the listbox
|
| select | Selects the element in the given position. |
position - the position
|
- |
| deselect | Deselects the element in the given position if it is selected. |
position - the position
|
- |
| selectAll | Selects all elements in the listbox. | - | - |
| deselect | Deselects any selected elements. | - | - |
| getSelected | Returns the array of the positions of the selected elements. | - |
Array
|
| isSelected | Returns true if the element in the given position is selected. |
position - the position
|
jboolean
|
| getSelectedItems | Returns the array of the selected elements. | - |
Array
|
| getSelectedJQueryItems | Returns the jQuery collection of the selected elements. | - |
jQuery
|
| getJQueryItemByIndex | Returns the jQuery item in the given position. |
position - the position
|
jQuery
|
| itemWalk |
Calls the provided function with each item one-by-one.
The current item, its position, its jQuery item and the current jqListbox instance is passed as parameters. |
fn - Function to be called
|
- |
| selectedWalk |
Calls the provided function with each selected item one-by-one.
The current item, its position, its jQuery item and the current jqListbox instance is passed as parameters. |
fn - Function to be called
|
- |
You can pass several options to the jqListbox plugin on initialization.
| Option | Type | Description | Default value |
|---|---|---|---|
| itemSelector | string |
The jQuery selector used to find your items in your list. The selector will be used as
$(container).find(itemSelector) so you must define it relative to your container.
|
li |
| targetInput | string|boolean |
The jQuery selector used to find your target input (where the final value of your listbox will be set). Set this option to false to disable the automatic value setting. | #listbox-value |
| initialValues | Array|boolean |
An array of your initial values to be pre-set when initializing the listbox. False by default - no initial values will be set. | false |
| initialEncodedValues | string|boolean |
An array of your encoded initial values to be pre-set when initializing the listbox. This must be a string compatible with your decoder. False by default - no initial values will be set. | false |
If initialValues is false and initialEncodedValues is false then jqListbox will try to pre-set
your
values from your targetInput: if this option is not false and your input contains some encoded
elements
jqListbox will set the elements from there. So the order of this is:
initialValues > initialEncodedValues > targetInput > empty listbox
|
|||
| selectedClass | string|boolean |
A class name used on selected items. jqListbox by default puts this class on your items when selecting. Set this option to false to disable this functionality. | selected |
| autoSelectOnClick | boolean |
If true then items will be automatically selected on a click event.
|
true |
| multiselect | boolean |
If true multiple selection is allowed. | true |
| CALLBACKS | |||
| itemRenderer | Function |
Function to be used when rendering items. The current rendered item, its position and the jqListbox instance is passed as parameters. You should return a string or a jQuery object from this function. |
function (item, pos, jqListbox) { return '
' + item + '
'; } |
| listboxValueEncoder | Function |
Function used when rendering the output of your listbox. You should return a string from this function (which can be set in your targetInput for example. The array of items will be passed as parameter. |
function (items) { return JSON.stringify(items); } |
| listboxValueDecoder | Function |
Function used when decoding output values (transforming back to array). |
function (values) { if (values.length > 0) { return JSON.parse(values); } return []; } |
| onBeforeInit | Function|boolean |
Function called before initializing the jqListbox. The current jqListbox instance is passed as parameter. | false |
| onAfterInit | Function|boolean |
Function called after initializing the jqListbox. The current jqListbox instance is passed as parameter. | false |
| onBeforeItemInsert | Function|boolean |
Function called before an element or multiple elements are inserted to the listbox.
The to-be-inserted element(s) will be passed as an array (even if only one element is inserted).
Also the current jqListbox instance is passed as a parameter.
You can modify the to-be-inserted elements by returning a new array from this function. You can ignore the insertion by returning a boolean false from this function. |
false |
| onAfterItemInsert | Function|boolean |
Function called after an element or multiple elements are inserted to the listbox. The to-be-inserted element(s) will be passed as an array (even if only one element is inserted). Also the current jqListbox instance is passed as a parameter. | false |
| onBeforeItemUpdate | Function|boolean |
Function called before an element or multiple elements are updated in the listbox.
The to-be-updated element(s) will be passed as an array (even if only one element is updated).
The new (updated elements will be passed as an array. Also the current jqListbox instance is passed as a parameter. You can modify the updated elements by returning a new array from this function (so you can change the target values). You can ignore the update by returning a boolean false from this function. |
false |
| onAfterItemUpdate | Function|boolean |
Function called after an element or multiple elements are updated in the listbox.
The to-be-updated element(s) will be passed as an array (even if only one element is updated). The new (updated elements will be passed as an array. Also the current jqListbox instance is passed as a parameter. |
false |
| onBeforeItemRemove | Function|boolean |
Function called before an element or multiple elements are removed from the listbox.
The to-be-removed element(s) will be passed as an array (even if only one element is removed).
Also the current jqListbox instance is passed as a parameter. You can modify the list of to-be-removed elements by returning a new array from this function (so you can change the target values). You can ignore the remove by returning a boolean false from this function. |
false |
| onAfterItemRemove | Function|boolean |
Function called after an element or multiple elements are removed from the listbox.
The current jqListbox instance is passed as a parameter. |
false |
| onBeforeClear | Function|boolean |
Function called before the clear operation.
The current jqListbox instance is passed as a parameter. You can ignore the remove by returning a boolean false from this function. |
false |
| onAfterClear | Function|boolean |
Function called after the clear operation.
The current jqListbox instance is passed as a parameter. |
false |
| onAfterDataChanged | Function|boolean |
Function called after any type of change (insert, update, remove, clear, movedown, moveup and even after setFromArray and init)
but before any render happened. This way you can modify the data after it has just changed.
The array of current data will be passed as a parameter. This parameter will be an array of objects where the item property store the actual item while the isSelected property is true if the item is currently selected.
You must return the same structure (objects with item and isSelected properties).
The type of the operation will be passed as parameter. The current jqListbox instance is passed as a parameter. |
false |
| onChanged | Function|boolean |
Function called after any type of change: insert, update, remove, clear, movedown or moveup.
The type of the operation will be passed as parameter. The current jqListbox instance is passed as a parameter. This method will be called always after the render operation. You can't change
the original operations here (use the onBefore... callbacks for this).
|
false |
| onBeforeSelect | Function|boolean |
Function called before the select operation.
The position of the want-to-be selected item and the current jqListbox instance is passed as a parameter. Return false from this callback to ignore the whole select logic. |
false |
| onBeforeDeSelect | Function|boolean |
Function called before the deselect operation.
The position of the want-to-be deselected item and the current jqListbox instance is passed as a parameter. Return false from this callback to ignore the whole deselect logic. |
false |
| onBeforeRender | Function|boolean |
Function called before the render operation.
The current jqListbox instance is passed as a parameter. Return false from this callback to ignore the whole render logic. If you do this then no item and output rendering will be done. |
false |
| onAfterRender | Function|boolean |
Function called after the render operation.
The current jqListbox instance is passed as a parameter. |
false |
Each callback and method uses the scope of the container element which has the jqListbox instance. It
means that $(this)
will point
to the container jQuery element inside your callback.


backend.py
)
| Public calls (may require password for protected lexicons): | |
| modes | see the hierarchy of the modes |
| groups | see the available index modes and their components |
| modeinfo | see the available search fields of a mode |
| lexiconinfo | see the available search fields of a lexicon |
| lexiconorder | for retrieving the lexicon order |
| query | for normal querying |
| querycount | for querying with some statistics |
| minientry | for getting minientries |
| statistics | for getting statistics, aggregation |
| statlist | for getting statistics, table view |
| autocomplete | for autocompletion of lemgrams |
| saldopath | for showing the path from a saldo sense to PRIM |
| getcontext | for showing the (alphabetical) neighbours of an entry |
| explain | for normal querying |
| random | for retrieving a random lexical entry |
| suggest | make an update suggestion |
| suggestnew | suggest a new entry |
| checksuggestion | see the status of a suggestion |
| Password protected calls: | |
| delete | delete an entry by #ID |
| mkupdate | update a lexical entry |
| add | add a lexical entry |
| readd | add an entry which already has an id (one that has been deleted) |
| addbulk | add multiple entries |
| add_child | add an entry and link it to its parent |
| checksuggestions | view suggestions |
| acceptsuggestion | accept a suggestion |
| acceptandmodify | accept a suggestion after modifications have been made to it |
| rejectsuggestion | reject a suggestion |
| checkuser | for checking whether the user is ok |
| checkuserhistory | for retrieving the edit history of a user |
| checkhistory | for retrieving the edit history of an entry |
| checklexiconhistory | for retrieving the edit history of one or more lexicon |
| checkdifference | see the difference between two versions |
| export | export a lexicon |
q=simple||satt och
q=extended||and|field|operator|value | (positive) |
q=extended||not|field|operator|value | (negative) |
Example:
search all entries with a word form that is "blomma" or "äpple" and that has no part of speech tag:
q=extended||and|pos|missing||and||wf|equals|blomma|äpple
Available query parameters:
| 'q': | the query |
| 'mode': | which mode to search in. default: karp |
| 'resource': | one or more comma separated lexicon to search. default: all |
| 'size': | number of hits to show on each page. default: 25 |
| 'start': | the index of the first hit to show. default: 0 |
| 'sort': | one or more comma separated fields to sort on. default: depends on mode, usually lexiconOrder, score, baseform, lemgram |
| 'export': | get the result in another format. which options that are available depends on lexicon and mode. examples: xml, lmf, tsb, tab, csv. |
| 'format': | get each hit in the json structure in another format. which options that are available depends on lexicon and mode. examples: app, tryck. |
Asking for export will not return the json objects (the hits). The result will look like:
{"formatted": a string in the current format ... }
Asking for another format, will give the following result
{"hits": { "hits": [ {"_source": ..., "formatted": "...xml string..." ... } }
Examples:
URL/query?q=simple||stort hus&mode=stablekarp
URL/query?q=simple||flicka&mode=saldogroup&resource=saldo,saldom,saldoe
URL/query?q=extended||and|lemgram|startswith|dalinm--
URL/query?q=extended||and|wf|equals|äta||and|pos|missing&resource=kelly,lwt&mode=stablekarp
URL/query?q=extended||and|wf|regexp|.*o.*a&mode=bliss
URL/query?q=extended||and|wf|regexp|.*o.*a&start=25&mode=bliss
URL/query?q=extended||and|sense|exists&mode=historic_ii
URL/query?q=extended||and|wf|equals|sitta||not|wf|equals|satt&mode=external
URL/query?q=simple||muminfigurer&mode=term-swefin&format=csv
Result:
hits{ total : number of hits hits: a list with information about the hits hits[n]._source: all information in hit n hits[n]._source._id elasticsearch's identifier for the entry hits[n]._version: the current version of this entry hits[n]._source.lexiconName hits[n]._source.lexiconOrder hits[n]._source.FormRepresentations hits[n]._source.Sense hits[n]._source.WordForms hits[n]._source.ListOfComponents hits[n]._source.RelatedForm hits[n]._source.compareWith hits[n]._source.entryType hits[n]._source.saldoLinks hits[n]._source.see hits[n]._source.symbolCenter hits[n]._source.symbolHeight hits[n]._source.symbolPath hits[n]._source.symbolWidth For freetext search (simple||...) only: hits[n].highlight information and paths about the matching part of the entry }
Example:
Result:
hits{...} as above distribution a list of counts for each lexicon that contains at least one match distribution[n].key the order for the n:th lexicon distribution[n].doc_count the count for the n:th lexicon distribution[n].lexiconName.buckets.[0].doc_count the count for the n:th lexicon (again) distribution[n].lexiconName.buckets.[0].key the name of the n:th lexicon
Available query parameters:
| 'mode': | which mode to search in. default: karp |
| 'q': | the query |
| 'resource': | one or more comma separated lexica to search. default: all |
| 'show': | one or more comma separated fields to show. default: depends on mode, usually lexiconName, lemgram, baseform |
| 'size': | number of hits to show on each page. default: 25 |
Example:
URL/minientry?q=extended||and|wf|equals|sitta|ligga
URL/minientry?q=extended||and|writtenForm|equals|får||and|writtenForm|equals|fick&show=pos
Result: See query.
Available query parameters:
| 'q': | the query |
| 'mode': | which mode to search in. default: karp |
| 'resource': | one or more comma separated lexica to search. default: all |
| 'size': | number of hits to show in each bucket. default: 100 |
| 'buckets': | one or more comma separated fields to group the results by. default: lexiconName, pos |
| 'cardinality': | shows the cardinality number of values for the innermost of the requested buckets, instead of showing the actual values. Not compatible with 'q'. 'size' will be ignored. |
Example:
URL/statistics
URL/statistics?q=simple||kasusformer&mode=karp
URL/statistics?resource=hellqvist&mode=historic_ii
URL/statistics?buckets=pos.bucket,sense.bucket&size=200&mode=stablekarp
The result is not sorted.
Result: X is the name of the first bucket (default: lexiconName), Y (defaults to pos) the second and so on. For a search where a query or a resource is specified:
aggregations { q_statistics.doc_count : total number of hits q_satistics.X: information about the data grouped by X (the first bucket) q_satistics.X_missing: information about the data missing X q_satistics.X.buckets[n].key: X value q_satistics.X.buckets[n].doc_count: number of hits within the X value q_satistics.X.buckets[n].Y: information grouped by X and then Y q_satistics.X.buckets[n].Y.doc_count: number of hits within the Y value in X q_satistics.X_missing.buckets[n]: information about entries which do not have any X value q_satistics.X_missing.buckets[n].doc_count: number of hits that do not have any X value q_satistics.X.buckets[n].Y_missing: information grouped by X and then Y, showing cases without any value for Y q_satistics.X.buckets[n].Y.doc_count: number of hits within the Y value in X .... }
Available query parameters:
| 'q': | the query |
| 'mode': | which mode to search in. default: karp |
| 'resource': | one or more comma separated lexica to search. default: all |
| 'buckets': | one or more comma separated fields to group the results by. default: lexiconName, pos |
| 'size': | number of hits to show in each bucket. Does hence not correspond to the number of table rows. default: 100. |
Example:
URL/statlist
URL/statlist?q=simple||ärt&buckets=resource,lemgram.bucket
URL/statlist?resource=hellqvist
URL/statlist?mode=historic_i&buckets=pos.bucket
URL/statlist?buckets=pos.bucket&size=200&mode=stablekarp
Result:
{ "stat_table": [ [ "konstruktikon", "", 88 ], [ "saldom", "nn", 3 ], ... ] }
It does not match prefixes. Searching for "sig" does hence not give suggestions like "sigill" or "signatur".
Provides lemgram suggestions to Korp, by looking in mode 'external'.
Examples:
URL/autocomplete?mode=external&q=sig
URL/autocomplete?multi=kasta,docka&resource=saldom&mode=external
URL/autocomplete?q=kasus&resource=saldom,dalin,hellqvist
URL/autocomplete?q=kasta&resource=saldom
Available query parameters:
| 'q': | the query, a word form |
| 'multi': | a comma separated list of queries (word forms). do not use together with q |
| 'resource': | one or more comma separated lexica to search. default: all |
| 'mode': | which mode to search in. default: karp |
The result is not sorted and one lemgram may occur multiple times
Result:
hits{ total : number of hits hits : information about the hits hits[n]._source : information about hit n hits[n]._source.FormRepresentations.lemgram : lemgram }If 'multi' parameter is used, the output will be a dictionary with one key corresponding to every input word. The values will be the same format as for q:
{"kasta": {"hits": ... }, "docka": {"hits": ... } }
Example:
Result:
{ path: [input_sense..1, ... , PRIM..1] }
The sorting order is based on the mode configs. (The order must be strict, eg. no two words may have the same score. If they do, getcontext will not work properly.)
Example:
URL/getcontext/#lexicon?center=#ID
URL/getcontext/saldo?q=extended||and|pos|equals|nn&size=2
URL/getcontext/saol?q=extended||not|ptv|equals|true&size=2
Available query parameters:
| 'center': | the ES-ID of the entry to center the search around. default: the first entry |
| 'q': | an optional query to restrict entries that appear in the result |
| 'size': | number of hits to show on each side of the center word. default: 10 |
{ center: [ *the centered entry* ], pre: [ *a list of hits (that match the query) occurring immediately before the centered * ], post: [ *a list of hits (that match the query) occurring immediately after the centered entry *]}
Example:
Result:
ans the normal query result elastic_json_query the query translated to Elastic's api explain Elastic's result to a _validate/query?explain query.
Result:
{ "lexiconA": 1, "lexiconB": 3, "lexiconC": 8, ... }
Available query parameters:
| 'resource': | one or more comma separated lexica to search. default: all |
| 'mode': | which mode to search in. default: karp |
| 'show': | one or more comma separated fields to show. default: depends on mode, usually lexiconName, lemgram, baseform |
| 'show_all': | all fields of the entries will be shown if this flag is set to true (or any value). Overrides show |
| 'size': | number of hits to show on each page. default: 1 |
Example:
The field 'version' is optional, but will prevent an old version to later override a newer one. Example:
URL/suggest/#lexicon/#ID -d {"message" : ..., "user": ..., "version": ... }
URL/suggestnew/#lexicon -d {"message" : ..., "user": ..., "version": ... }
Result:
{ "es_ans": {...} // output from ES "es_loaded": 1, // 1 if the suggestion is stored in ES "id": // the #ID of the suggestion. Can be used to see the current status, accept or reject the suggestion "sql_loaded": 1, // 1 if the suggestion is stored in SQL "suggestion": true, sql_error // present if there were errors storing the suggestion }
Examples:
URL/delete/#lexicon/#ID
Result:
{ 'sql_loaded' : 1 if successfully marked as deleted in the SQL database, 'es_loaded' : 1 if successfully deleted from ElasticSearch (is no longer searchable), 'es_ans' : the answer from ES. }
XPOST URL/mkupdate/#lexicon/#ID -d '{'doc' : updated entry, 'version' : (last) version, 'message' : update message}'
XPOST URL/mkupdate/#lexicon/#ID -d '{'doc' : updated entry, 'version' : (last) version, 'message' : update message}'
{ 'sql_loaded' : 1 if successfully saved in the SQL database, 'es_loaded' : 1 if successfully stored in ElasticSearch (is searchable), 'es_ans' : {'_id':..., '_index':..., '_type':..., '_version': ...} //the answer from ES. }
Error messages:
Version conflict:
{"message": "Database exception: Error during update. Message: TransportError(409, u'RemoteTransportException[...]; nested: VersionConflictEngineException[...]: version conflict, current [3], provided [1]]; ')."}ID could not be found:
{"message": "Database exception: Error during update. Message: TransportError(404, u'RemoteTransportException[...]; nested: DocumentMissingException[...]: document missing]; ')"}
XPOST URL/add/#lexicon -d '{'doc' : {...,'lexiconName': 'saldo',lexiconOrder' : 0,...} 'version' : (last) version, 'message' : update message}'
XPOST URL/readd/#lexicon/#ID -d '{'doc' : {...,'lexiconName': 'saldo',lexiconOrder' : 0,...} 'version' : (last) version, 'message' : update message}'
Result:
{ 'sql_loaded' : 1 if successfully saved in the SQL database, 'es_loaded' : 1 if successfully stored in ElasticSearch (is searchable), 'es_ans' : {'_id':..., '_index':..., '_type':..., '_version': ..., 'created' : True} //the answer from ES. , 'suggestion': False. True if the update has been treated as suggestion. }
XPOST URL/addbulk/#lexicon -d '{'doc' : [{...entry1...}, {...entry2...}, ...], 'message' : update message}'
{ 'sql_loaded' : number of entries successfully saved in the SQL database, 'es_loaded' : number of entries successfully stored in ElasticSearch, 'ids' : a list of the new entries IDs, 'suggestion': False }
XPOST URL/addchild/#lexicon/#parentid -d '{'doc' : {...,'lexiconName': 'saldo',lexiconOrder' : 0,...} 'version' : (last) version, 'message' : update message}'
Result:
{ 'parent': the result of adding the link to the parent (see mkupdate). 'child' : the result of adding the child (see add). }
Required query parameters:
| 'resource': | one or more comma separated lexicons to search. default: all |
Available query parameters:
| 'size': | the number of suggestions to view (order by decreasing date). default: 50 |
| 'status': | waiting, rejected, accepted. default: all |
Example:
URL/checksuggestions?resource=konstruktikon&size=2&status=waiting
Result:
{ "updates": [ { "acceptmessage" // is set when the suggestion is accepted or rejected "date": // the date of suggestion "doc": // the suggested lexical entry "id": // the #ID of the suggestion "lexicon": // the lexicon it belongs to "message": // message from the suggester "origid": // the #ID of the entry the suggestion concerns "status": // the status of the suggestion (waiting, accepted or rejected) "user": // the name or email adress of the suggester "version": // the version of the entry that the suggestion concerns } ]
Example:
URL/checksuggestion/#lexicon/#IDThe #ID refers to the suggestion, not the original entry.
Result:
{ "updates": [ { "acceptmessage" // is set when the suggestion is accepted or rejected "date": // the date of suggestion "doc": // the suggested lexical entry "id": // the #ID of the suggestion "lexicon": // the lexicon it belongs to "message": // message from the suggester "origid": // the #ID of the entry the suggestion concerns "status": // the status of the suggestion (waiting, accepted or rejected) "user": // the name or email adress of the suggester "version": // the version of the entry that the suggestion concerns } ]
Example:
URL/acceptsuggestion/#lexicon/#ID -d {"message" : ...}The #ID refers to the suggestion, not the original entry. The message will be stored in the suggestion data base and in the live data base.
Result:
{ "es_ans": { "_id": // #ID of the updated entry "_index": "_type": "_version": }, "es_loaded": // 1 if successfully loaded to ES "sql_loaded": // 1 if successfully loaded to the live SQL "sugg_db_error": // present if there were errors storing the suggestion "sugg_db_loaded": // 1 if successfully loaded to suggestion SQL "sugg_es_ans": {"es_ans" : {...} // ans from ES ,"es_loaded": // 1 if removed from the suggestion ES ,"sql_loaded": // 1 if the suggestion was marked as accepted } }
Example:
URL/acceptandmodify/#lexicon/#ID -d {"doc": {...} "message" : ...}The #ID refers to the suggestion, not the original entry. The data is the new version that should be kept. The message will be stored in the suggestion data base and in the live data base.
Result:
{ "es_ans": { "_id": // #ID of the updated entry "_index": "_type": "_version": }, "es_loaded": // 1 if successfully loaded to ES "sql_loaded": // 1 if successfully loaded to the live SQL "sugg_db_error": // present if there were errors storing the suggestion "sugg_db_loaded": // 1 if successfully loaded to suggestion SQL "sugg_es_ans": {"es_ans" : {...} // ans from ES ,"es_loaded": // 1 if removed from the suggestion ES ,"sql_loaded": // 1 if the suggestion was marked as accepted } }
Example:
URL/rejectsuggestion/#lexicon/#ID -d {"message" : ...}The #ID refers to the suggestion, not the original entry. The message will be stored in the suggestion data base.
Result:
{ "es_ans": {...} // output from the deletion from the suggestion ES "es_loaded": // 1 if successfully removed to the suggestion ES "sugg_db_error": // present if there were errors storing the suggestion "sugg_db_loaded": // 1 if successfully loaded to suggestion SQL }
Result:
{ "authenticated": is the user name and password ok, "permitted_resources.lexica": lexicons that the user may see or edit }
| 'size': | number of hits to show on each page. default: 10 |
Result:
{ "updates": [ {"date" ,"doc" //the entry that has been edited ,"id" ,"message" ,"user" }, ... ] }
| 'size': | number of hits to show on each page. default: 10 |
Result:
{ "updates": [ {"date" ,"doc" //the entry that has been edited ,"id" ,"message" ,"user" }, ... ] }
| 'size': | number of hits to show on each page. default: 10 |
Examples. If a date is provided (in the correct format) only updates done later than this is shown.
URL/checklexiconhistory/#lexicon
URL/checklexiconhistory/blissword/20150922
Result:
{ "updates": [ {"date" ,"doc" //the entry that has been edited ,"id" ,"message" ,"user" ,"type" // CHANGED, ADDED or REMOVED, only present if checklexiconhistory is called }, ... ] }
Example.
URL/checkdifference/#lexicon/#ID/latest
URL/checkdifference/#lexicon/#ID/latest/#fromdate'
URL/checkdifference/#lexicon/#ID/#fromdate/#todate'
Result:
{ "diff" : [ {"field" // a field that has been changed between the two versions ,"after" // the content of the field in the later of the two versions ,"before" // the content of the field in the older of the two versions (not present if the field is added) "type" // added, changed och removed } ]}
Available parameters:
| 'date': | export the entries as they were a given date. default: latest |
| 'export': | export to another format than json, eg csv, tsv, xml. Not available for all lexicons! default: json |
| 'size': | number of hits to show. default: all entries |
Example.
URL/export/#lexicon
URL/export/#lexicon?date=20170901
URL/export/#lexicon?format=lmf&size=2
Result (if json):
{ "#lexicon" : [ ... the lexicon ... ] }


| Food for Couriers | ||
| Item | Location | Purchase Links |
| 15 Desert Scrub |
[Gem] • [Treasure] |
|
| 15 Desert Scrub |
[Gem] • [Treasure] |
| Tools of the Trade | ||
| Item | Location | Purchase Links |
| 2 Toolbox |
[Gem] •
[Treasure] |


The results of each {@link gov.nara.nwts.ftapp.filetest.FileTest} can be highly customized to meet a specific business need.


Toggle navigation
Queue Admin Page
Settings
Raft state
Raft log
Blob resources
Put blob
Start benchmark
Settings
Raft state
Raft log
Blob resources
Put blob
Start benchmark


A reading from the Book of the Prophet Jonah
The word of the LORD came to Jonah the second time,
saying, "Arise, go to
The word of the Lord
RESPONSORIAL PSALM Psalm 130:1-2.3-4.7bc-8 (R. 3)
R. If you, O Lord, should mark iniquities, Lord, who could stand?
Out of the depths I cry to you, O LORD; LORD, hear
my voice! O let your ears be attentive to the sound of my pleading.
R. If you, O Lord, should mark iniquities, Lord, who
could stand?
If you, O LORD, should mark iniquities, LORD, who
could stand? But with you is found forgiveness, that you may be revered.
R. If you, O Lord, should mark iniquities, Lord, who
could stand?
For with the LORD there is mercy, in him is
plentiful redemption. It is he who will redeem
R. If you, O Lord, should mark iniquities, Lord, who
could stand?
FIRST READING Galatians 1:13-24
“He revealed his Son to me, in order that I might preach him among the Gentiles.”
A reading from the Letter of Saint Paul to the Galatians
Brethren: You have heard of my former life in
Judaism, how I persecuted the
The word of the Lord
RESPONSORIAL PSALM
Psalm 139:1-3.13-14.15 (R. 24b)
R. Lead me, Lord, in the way everlasting.
 You yourself
know my resting and my rising; you discern my thoughts from afar. You mark when
I walk or lie down; you know all my ways through and through.
R. Lead me, Lord, in the way everlasting.
For it was you who formed
my inmost being, knit me together in my mother's womb. I thank you who
wonderfully made me; how wonderful are your works, which my soul knows well!
R. Lead me, Lord, in the way everlasting.
My frame was not hidden from you, when I was being
fashioned in secret and moulded in the depths of the earth.
R. Lead me, Lord, in the way everlasting.
R. Alleluia. Blessed are those who hear the word of God and keep it. R. Alleluia.
GOSPEL Luke 10:38-42
Martha received him into her house. Mary has chosen the good portion.
A reading from the holy Gospel according to Luke
At that time: Jesus entered a village; and a woman named
Martha received him into her house. And she had a sister called Mary, who sat
at the Lord's feet and listened to his teaching. But Martha was distracted with
much serving; and she went to him and said, "Lord, do you not care that my
sister has left me to serve alone? Tell her then to help me." But the Lord
answered her, "Martha, Martha, you are anxious and troubled about many
things; one thing is needful. Mary has chosen the good portion, which shall not
be taken away from her."
The Gospel of the Lord


Refurb iPhone XS and XS Max models are up to 19% today only at Amazon UK
Apple's iPhone 11 may be here, but that doesn't mean the iPhone XS isn't a stellar option if you're in the market for an upgrade. Right now over on Amazon UK, customers can take advantage of Amazon's Deal of the Day, and snag up to 19% off a renewed iPhone. Not only is the XS Max still a brilliant phone, this deal comes backed by Amazon's 1-year Renewed Guarantee. Renewed Amazon products look and work like new, they aren't Apple-certified but will have a battery capacity of at least 80%.
One-year warranty included
Refurbished iPhone XS and XS Max
Savings to be had on all of Apple's iPhone XS and XS Max models on Amazon UK. A 64GB XS will set you back £520, whilst the most expensive XS Max (256GB) is just £620.
From £520
The iPhone XS features a Super Retina Display of 5.8 inches, 12MP camera, Face ID and an IP68 water resistance rating (up to 2m for 30 minutes). The XS Max packs all of that in behind a 6.5-inch display that also hides a much larger battery for extended usage.
The biggest saving to be found is on the iPhone XS with 256GB capacity in the gold finish, which has a discount of 19%, down to £550 from £680, a whopping £130 off! Supplies are limited and already dwindling, so be sure to place your order as soon as possible. Once you've picked up your phone, take a look at our guide to the best iPhone XS accessories for ways to put your savings to good use.
We may earn a commission for purchases using our links. Learn more.


Copyright © 2009 Marc Worrell
Behaviours: gen_server.
Authors: Marc Worrell (marc@worrell.nl).
| code_change/3 | Convert process state when code is changed. |
| detach/3 | Unsubscribe from an event. |
| detach_all/2 | Detach all observers and delete the event. |
| first/2 | Call all observers till one returns something else than undefined. |
| foldl/3 | Do a fold over all observers, prio 1 observers first. |
| foldr/3 | Do a fold over all observers, prio 1 observers last. |
| get_observers/2 | Return all observers for a particular event. |
| handle_call/3 | Trap unknown calls. |
| handle_cast/2 | Add an observer to an event. |
| handle_info/2 | Handle timer ticks. |
| init/1 | Initiates the server, creates a new observer list. |
| map/2 | Call all observers, return the list of answers. |
| notify/2 | Cast the event to all observers. |
| notify1/2 | Cast the event to the first observer. |
| notify_observer/4 | Notify an observer of an event. |
| observe/3 | Subscribe to an event. |
| observe/4 | Subscribe to an event. |
| start_link/1 | Starts the notification server. |
| start_tests/0 | Start a notifier server for unit testing. |
| terminate/2 | This function is called by a gen_server when it is about to terminate. |
code_change(OldVsn, State, Extra) -> {ok, NewState}
Convert process state when code is changed
detach(Event, Observer, Context) -> any()
Unsubscribe from an event. Observer is a {M,F} or pid()
detach_all(Event, Context) -> any()
Detach all observers and delete the event
first(Msg, Context) -> any()
Call all observers till one returns something else than undefined. The prototype of the observer is: f(Msg, Context)
foldl(Msg, Acc0, Context) -> any()
Do a fold over all observers, prio 1 observers first. The prototype of the observer is: f(Msg, Acc, Context)
foldr(Msg, Acc0, Context) -> any()
Do a fold over all observers, prio 1 observers last
get_observers(Msg, Context) -> any()
Return all observers for a particular event
handle_call(Message::Request, From, State) -> {reply, Reply, State} | {reply, Reply, State, Timeout} | {noreply, State} | {noreply, State, Timeout} | {stop, Reason, Reply, State} | {stop, Reason, State}
Trap unknown calls
handle_cast(Message::Msg, State) -> {noreply, State} | {noreply, State, Timeout} | {stop, Reason, State}
Add an observer to an event
handle_info(Info, State) -> {noreply, State} | {noreply, State, Timeout} | {stop, Reason, State}
Handle timer ticks
init(Args) -> {ok, State} | {ok, State, Timeout} | ignore | {stop, Reason}
Initiates the server, creates a new observer list
map(Msg, Context) -> any()
Call all observers, return the list of answers. The prototype of the observer is: f(Msg, Context)
notify(Msg, Context) -> any()
Cast the event to all observers. The prototype of the observer is: f(Msg, Context) -> void
notify1(Msg, Context) -> any()
Cast the event to the first observer. The prototype of the observer is: f(Msg, Context) -> void
notify_observer(Msg, X2, IsCall, Context) -> any()
Notify an observer of an event
observe(Event, Observer, Context) -> any()
Subscribe to an event. Observer is a {M,F} or pid()
observe(Event, Observer, Priority, Context) -> any()
Subscribe to an event. Observer is a {M,F} or pid()
start_link(SiteProps) -> {ok, Pid} | ignore | {error, Error}
Starts the notification server
start_tests() -> any()
Start a notifier server for unit testing
terminate(Reason, State) -> void()
This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored.
Generated by EDoc, Apr 11 2012, 20:41:27.


Full Stack Developer
I have advanced proficiencies in C#, Angular, MVC, BootStrap, HTML, CSS, JavaScript, excellent microsoft technology skills skills and am familiar with SQL and Oracle. I also have a solid foundation in C#, AS.NET ,AngularJS, MVC and Node.JS. In addition to four years work experience, I hold a Masters degree in Computer Science. I have obtained microsoft Developer certification


{% extends "layout.html" %} {% block content %} {% include "queryactions.html" %}
Please enter a Datalog query and provenance request (e.g., Q(X) :- R(X,Y). WHY(Q(1)).) or select a past query from the dropdown.
More examples can be found in our github (Datalog Provenance).
{{ indblist|safe }}


|
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object ontopt.pen.ChartRow
public class ChartRow
Class from PEN Parser.
This class represents the row of a chart.
Copyright: Copyright (c) 2002-2009
Company: CISUC
| Constructor Summary | |
|---|---|
ChartRow(Rule pRule)
The constructor |
|
ChartRow(Rule pRule,
int[] pPositions)
The constructor |
| Method Summary | |
|---|---|
void |
addParentState(java.lang.Integer s)
Adds a new parent to this row |
void |
addParentStates(java.util.ArrayList<java.lang.Integer> s)
Adds a list of parents to this row |
boolean |
equals(ChartRow row)
Check if this row is equal to another. |
ChartRow |
getChartRowFromState(java.lang.Integer pState)
Gets the row corresponding to the specified state |
int |
getDot()
Gets the position of the dot relative to the size of this rule |
java.lang.Integer |
getNextConstituent()
Gets the next part of rule that needs to be fired |
java.util.ArrayList<java.lang.Integer> |
getParents()
Gets the list of parents |
int[] |
getPositions()
gets the array corresponding to the position of where this rule begins and where the dot lies. |
Rule |
getRule()
The rule associated to this row |
java.lang.Integer |
getState()
Gets the state of this row, the state is a unique id |
protected void |
incState(java.util.ArrayList<ChartRow> pStateList)
Adds this row to the state list. |
boolean |
isComplete()
Check if this rule has been completely fired |
protected void |
setDot(int dot)
Sets the position of the dot relative to the size of this rule |
protected void |
setPositions(int[] positions)
Sets the array of positions where the first value corresponds to where the rule begins and the second to where the dot lies always in respect to the input sentence. |
protected void |
setProcess(java.lang.String p)
Sets the name of the process |
java.lang.String |
toString()
gets the string representation of this row. |
| Methods inherited from class java.lang.Object |
|---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
|---|
public ChartRow(Rule pRule)
pRule
- The rule used in this rowpublic ChartRow(Rule pRule, int[] pPositions)
pRule
- The rule used in this rowpPositions
- An array where the first value corresponds to where the rule begins and the second to where
the dot lies always in respect to the input sentence.| Method Detail |
|---|
public ChartRow getChartRowFromState(java.lang.Integer pState)
pState
- The state to look for
protected void setProcess(java.lang.String p)
p
- The name to be setprotected void incState(java.util.ArrayList<ChartRow> pStateList)
pStateList
- The global state list that is sharedprotected void setDot(int dot)
dot
- the positionpublic int getDot()
public java.lang.Integer getState()
public void addParentState(java.lang.Integer s)
s
- the parent to addpublic void addParentStates(java.util.ArrayList<java.lang.Integer> s)
s
- the list of parentspublic java.util.ArrayList<java.lang.Integer> getParents()
public int[] getPositions()
protected void setPositions(int[] positions)
positions
- the array of positionspublic Rule getRule()
public boolean isComplete()
public java.lang.Integer getNextConstituent()
public boolean equals(ChartRow row)
row
- The row to compare to
public java.lang.String toString()
toString
in class java.lang.Object
|
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


{{About your IPv4-only Internet service.}}
{{This FAQ has been produced to try and address the questions of IPv4 only users}}{{More about your test results.}}
[% PROCESS "faq/dontfeelbad.inc" %] [% PROCESS "faq/nothingwillbreak.inc" %] [% PROCESS "faq/teredo_iponly.inc" %] [% PROCESS "faq/teredo_advice.inc" %] [% PROCESS "faq/dontstress.inc" %]


By adding Yout User id And password you are able to buy medicine as well as you can authentically sell medicines from your company as certified by indian medical association


Fellowship of the Ring
Can you list the 9 main characters who attempted to deliver the one ring to Mount Doom?


11 August 2009 - The Ministry of Health of Egypt has reported 2 new confirmed human case of avian influenza A(H5N1).
The first case is an 8 year-old female from Kfr Elsheikh district, Kfr Elsheikh Governorate. Her symptoms started on 24 July 2009. She was admitted to Kfr Elsheikh fever hospital on 25 July, where she received oseltamivir treatment. The patient is in a stable condition.
The second case is an 18 month-old male from Shebin Elkom district, Menofyia Governorate. His symptoms started on 28 July 2009. He was admitted to Shebin Elkom fever hospital on 29 July 2009, where he received oseltamivir treatment, and is in a stable condition.
Investigations into the source of infection indicated that both cases had close contact with dead and/or sick poultry.
The cases were confirmed by the Egyptian Central Public Health Laboratories.
Of the 83 cases confirmed to date in Egypt, 27 have been fatal.


Mitogen-activated protein kinase kinase kinases (MAPKKKs) are serine-threonine protein kinases that initiate protein kinase signaling cascades. They phosphorylate MITOGEN-ACTIVATED PROTEIN KINASE KINASES; (MAPKKs) which in turn phosphorylate MITOGEN-ACTIVATED PROTEIN KINASES; (MAPKs). (mesh:D020930)
| Synonym | Reference | Specificity |
| MAPK kinase kinase | Exact | |
| MAPKK kinases | Exact | |
| MAPKKK | Exact | |
| MAP3K | Exact |
| Identifier | Name | Relation |
| HGNC:6857 | MAP3K5 | isa |
| HGNC:29798 | MAP3K21 | isa |
| FPLX:TAOK | TAOK | isa |
| FPLX:RAF | RAF | isa |
| HGNC:6858 | MAP3K6 | isa |
| HGNC:6849 | MAP3K10 | isa |
| HGNC:17797 | MAP3K20 | isa |
| HGNC:6851 | MAP3K12 | isa |
| HGNC:31689 | MAP3K15 | isa |
| HGNC:6859 | MAP3K7 | isa |
| HGNC:6861 | MAP3K9 | isa |
| HGNC:6848 | MAP3K1 | isa |
| HGNC:6850 | MAP3K11 | isa |
| HGNC:6852 | MAP3K13 | isa |
| HGNC:6854 | MAP3K2 | isa |
| HGNC:6860 | MAP3K8 | isa |
| HGNC:6853 | MAP3K14 | isa |
| HGNC:26249 | MAP3K19 | isa |
| HGNC:6856 | MAP3K4 | isa |
| HGNC:6855 | MAP3K3 | isa |


Army interrogates locals in Yochaung area: military official
by Min Naing Soe
The army is interrogating locals from Ywartharyar Village in Yochaung area, Myebon Township whether they have associated with the Arakan Army (AA) or not and if they have been found guilty, they will be taken action against laws, said Col. General Staff Win Zaw Oo, spokesperson of Western Command.
An army column arrived at the village on November 9 and arrested five villagers on November 12 for interrogation, he said.
“We are interrogating them and if they don’t have close relation with the AA, we will not take them action. If they provided assistance to the AA, they will be taken action against laws. We interrogated them as we have information about the connection with the AA,” said the colonel.
Army columns were frequently attacked by mines when they passed Ywartharyar Village and nearby villages, he said.
The army interrogated 11 villagers and detained five of them for further interrogation. Although the army left the village, they are stationed at Yochaung Bridge.
An attack occurred near Ywartharyar Village on November 10 and a pregnant woman was killed. Although sources said she was killed by the soldiers, Col. Win Zaw Oo denied it.
Fighting broke out between army and AA occurred in eight townships in Rakhine State and the AA also detained and killed some government staffs, retired military men and village administrators as they are accused of being army informers.


Address Book
Name
Email
Phone Number
Address
Name
Email
Phone Number
Address
Remove Contact
{{contact.name}}
{{contact.email}}
{{contact.phone}}
{{contact.address}}
Remove


Log Functions¶
In this section, we will cover the following functions in-depth listed below:
uadmin.Action¶
Action is the process of doing something where you can check the status of your activities in the uAdmin project.
Type:
int
There are 12 types of actions:
Added - Saved a new record
Custom - For any other action that you would like to log
Deleted - Deleted a record
GetSchema - Opened the full schema of the model
LoginDenied - User invalid login
LoginSuccessful - User login
Logout - User logout
Modified - Save an existing record
PasswordResetDenied - A password reset attempt was rejected
PasswordResetRequest - A password reset was received
PasswordResetSuccessful - A password was reset
Read - Opened a record
Open "LOGS” in the uAdmin dashboard. You can see the Action field inside it as shown below.
Now go to the main.go. Let’s add each methods of actions in the log.
func main(){
// Some codes
for i := 0; i < 12; i++ {
// Initialize the log model
log := uadmin.Log{}
// Call each methods of action based on the specific loop count
switch i {
case 0:
log.Action = uadmin.Action(0).Added()
case 1:
log.Action = uadmin.Action(0).Custom()
case 2:
log.Action = uadmin.Action(0).Deleted()
case 3:
log.Action = uadmin.Action(0).GetSchema()
case 4:
log.Action = uadmin.Action(0).LoginDenied()
case 5:
log.Action = uadmin.Action(0).LoginSuccessful()
case 6:
log.Action = uadmin.Action(0).Logout()
case 7:
log.Action = uadmin.Action(0).Modified()
case 8:
log.Action = uadmin.Action(0).PasswordResetDenied()
case 9:
log.Action = uadmin.Action(0).PasswordResetRequest()
case 10:
log.Action = uadmin.Action(0).PasswordResetSuccessful()
default:
log.Action = uadmin.Action(0).Read()
}
// Add the method to the logs
log.Save()
}
}
Once you are done, rebuild your application. Check your "LOGS” again to see the result.
As expected, all types of actions were added in the logs. Good job man!
More examples of this function can be found in uadmin.Log.
Quiz:
uadmin.APILogAdd¶
APILogAdd controls the data API’s logging for add commands.
Type:
bool
For versions 0.2.0 and above and Settings model is available, visit API Log Add page for an example.
If Settings model is not available, follow this approach:
Prerequisites:
Go to the main.go and assign the value of the API Log Add to true.
func main(){
uadmin.APILogAdd = true
// Some codes
}
Run your application. Let’s call this URL in the address bar to add multiple records in the Document model with the following information below:
First Record
Name: Golang
Author: John
Second Record
Name: uAdmin
Author: Adam
# document is a model name
# name and author are field names
# __0 is the first index
# __1 is the second index
http://api.example.com/api/d/document/add/?_name__0=Golang&_author__0=John&_name__1=uAdmin&_author__1=Adam
Result:
{
"id": [
1,
2
],
"rows_count": 2,
"status": "ok"
}
It returns an array with a list of IDs for the newly created records.
Now go back to the uAdmin dashboard. Click on "LOGS”.
As expected, the user’s action in adding records through HTTP API was recorded in the Log model.
Exit your application. Go to the main.go and assign the value of the API Log Add to false.
func main(){
uadmin.APILogAdd = false
// Some codes
}
Run your application. Let’s call this URL to add a new record in the Document model with the following information below:
Name: Programming
Author: Admin
# document is a model name
# name and author are field names
http://api.example.com/api/d/document/add/?_name=Programming&_author=Admin
Result:
{
"id": 3,
"rows_count": 1,
"status": "ok"
}
It returns the ID of the newly created record.
Check the "LOGS” to see the result.
As expected, the user’s action in adding a record through HTTP API was not recorded in the Log model.
uadmin.APILogDelete¶
APILogDelete controls the data API’s logging for delete commands.
Type:
bool
For versions 0.2.0 and above and Settings model is available, visit API Log Delete page for an example.
If Settings model is not available, follow this approach:
Prerequisites:
Go to the main.go and assign the value of the API Log Delete to true.
func main(){
uadmin.APILogDelete = true
// Some codes
}
Run your application. Suppose you have five records in the Item model.
Call this URL in the address bar to delete records where the name of an item contains "iPad”.
# item is a model name
# name is a field name
# __contains is an operator that will search for string values that contract
http://api.example.com/api/d/item/delete/?name__contains=iPad
Result:
{
"rows_count": 2,
"status": "ok",
}
It returns the status and the rows affected by your query.
Now go back to the uAdmin dashboard. Click on "LOGS”.
As expected, the user’s action in deleting records through HTTP API that contains "iPad” in the item name was recorded in the Log model.
Exit your application. Go to the main.go and assign the value of the API Log Delete to false.
func main(){
uadmin.APILogDelete = false
// Some codes
}
Run your application. Let’s call this URL in the address bar to delete the fourth record in the database.
# item is a model name
# 4 is an ID number
http://api.example.com/api/d/item/delete/4/
Result:
{
"rows_count": 1,
"status": "ok"
}
It returns the status and the rows affected by your query.
Check the "LOGS” to see the result.
As expected, the user’s action in deleting the fourth record through HTTP API was not recorded in the Log model.
uadmin.APILogEdit¶
APILogEdit controls the data API’s logging for edit commands.
Type:
bool
For versions 0.2.0 and above and Settings model is available, visit API Log Edit page for an example.
If Settings model is not available, follow this approach:
Prerequisites:
Go to the main.go and assign the value of the API Log Edit to true.
func main(){
uadmin.APILogEdit = true
// Some codes
}
Run your application. Suppose you have five records in the Item model where all iPad items have a rating of 4.
Call this URL to edit the rating of all iPad items to a value of 5.
# item is a model name
# name is a field name
# __contains is an operator that will search for string values that contract
# rating=4&_rating=5 means that where rating is equal to 4, change the
# rating value to 5
http://api.example.com/api/d/item/edit/?rating=4&_rating=5
Result:
{
"rows_count": 2,
"status": "ok"
}
It returns the status and the rows affected by your query.
Now go back to the uAdmin dashboard. Click on "LOGS”.
As expected, the user’s action in editing records through HTTP API was recorded in the Log model.
Exit your application. Go to the main.go and assign the value of the API Log Edit to false.
func main(){
uadmin.APILogEdit = false
// Some codes
}
Run your application. Suppose the first record in the Item model is named as "Robot”.
Call this URL to edit the name of the first record in the database from "Robot” to "Supercomputer”.
# item is a model name
# 1 is an ID number
# name is a field name
http://api.example.com/api/d/item/edit/1/?_name=Supercomputer
Result:
{
"rows_count": 1,
"status": "ok"
}
It returns the status and the rows affected by your query.
Check the "LOGS” to see the result.
As expected, the user’s action in editing the first record through HTTP API was not recorded in the Log model.
uadmin.APILogRead¶
APILogRead controls the data API’s logging for read commands.
Type:
bool
For versions 0.2.0 and above and Settings model is available, visit API Log Read page for an example.
If Settings model is not available, follow this approach:
Prerequisites:
Go to the main.go and assign the value of the API Log Read to true.
func main(){
uadmin.APILogRead = true
// Some codes
}
Run your application. Suppose you have five records in the Item model.
Call this URL to read record(s) where rating is equal to 3.
# item is a model name
# rating is a field name
http://api.example.com/api/d/item/read/?rating=3
Result:
It returns a list of records where rating is equal to 3.
Now go back to the uAdmin dashboard. Click on "LOGS”.
As expected, the user’s action in reading records through HTTP API was recorded in the Log model.
Exit your application. Go to the main.go and assign the value of the API Log Read to false.
func main(){
uadmin.APILogRead = false
// Some codes
}
Run your application. Call this URL to read the second record in the Item model.
# item is a model name
# 2 is an ID number
http://api.example.com/api/d/item/read/2/
Result:
It returns a JSON object representing an item where ID=2.
Check the "LOGS” to see the result.
As expected, the user’s action in reading the second record through HTTP API was not recorded in the Log model.
uadmin.APILogSchema¶
APILogSchema controls the data API’s logging for schema commands.
Type:
bool
For versions 0.2.0 and above and Settings model is available, visit API Log Schema page for an example.
If Settings model is not available, follow this approach:
Prerequisite:
Go to the main.go and assign the value of the API Log Schema to true.
func main(){
uadmin.APILogSchema = true
// Some codes
}
Run your application. Suppose you have five records in the Item model.
Call this URL to read the full schema of the Item model.
# item is a model name
http://api.example.com/api/d/item/schema/
Result:
It returns a JSON object representing uAdmin’s ModelSchema of the Item model.
Now go back to the uAdmin dashboard. Click on "LOGS”.
As expected, the user’s action in getting the schema of the Item model through HTTP API was recorded in the Log model.
Exit your application. Go to the main.go and assign the value of the API Log Schema to false.
func main(){
uadmin.APILogSchema = false
// Some codes
}
Run your application. Recall this URL to read the full schema of the Item model.
# item is a model name
http://api.example.com/api/d/item/schema/
Check the "LOGS” to see the result.
As expected, the user’s action in getting the schema of the Item model through HTTP API was not recorded in the Log model.
uadmin.Log¶
Log is a system in uAdmin that is used to add, modify, and delete the status of the user activities.
Structure:
type Log struct {
Model
Username string `uadmin:"filter;read_only"`
Action Action `uadmin:"filter;read_only"`
TableName string `uadmin:"filter;read_only"`
TableID int `uadmin:"filter;read_only"`
Activity string `uadmin:"code;read_only" gorm:"type:longtext"`
RollBack string `uadmin:"link;"`
CreatedAt time.Time `uadmin:"filter;read_only"`
}
There are 12 types of actions:
Added - Saved a new record
Custom - For any other action that you would like to log
Deleted - Deleted a record
GetSchema - Opened the full schema of the model
LoginDenied - User invalid login
LoginSuccessful - User login
Logout - User logout
Modified - Save an existing record
PasswordResetDenied - A password reset attempt was rejected
PasswordResetRequest - A password reset was received
PasswordResetSuccessful - A password was reset
Read - Opened a record
There are 5 functions that you can use in Log:
ParseRecord - It means to analyze a record specifically. It uses this format as shown below:
func(a reflect.Value, modelName string, ID uint, user *User, action Action, r *http.Request) (err error)
Parameters:
a reflect.Value: An interface initialized in NewModel function
modelName string: The name of the model in lowercase letters
ID uint: The ID of the model
user *User: What account is using in the session
action Action: An activity status
r *http.Request: A data structure that represents the client HTTP request
Go to Example #2: ParseRecord function to see how ParseRecord works.
PasswordReset - It keeps track when the user resets his password. It uses this format as shown below:
func(user string, action Action, r *http.Request) (err error)
Parameters:
user string: An account username
action Action: An activity status
r *http.Request: A data structure that represents the client HTTP request
Go to Example #3: PasswordReset function to see how PasswordReset works.
Save() - Saves the object in the database
SignIn - It keeps track when the user signs in his account. It uses this format as shown below:
func(user string, action Action, r *http.Request) (err error)
Parameters:
user string: An account username
action Action: An activity status
r *http.Request: A data structure that represents the client HTTP request
Go to Example #4: SignIn function to see how SignIn works.
String() - Returns the Log ID
Examples:
Page:
Quiz:
uadmin.LogAdd¶
LogAdd adds a log when a record is added.
Type:
bool
For versions 0.2.0 and above and Settings model is available, visit Log Add page for an example.
If Settings model is not available, follow this approach:
Go to the main.go and apply this function to "true”. Put it above the uadmin.Register.
func main() {
uadmin.LogAdd = true
uadmin.Register(
// Some codes
)
Run your application and go to "LOGS” model.
Suppose that you have this record in your logs as shown below:
Go back to uAdmin dashboard then select "TODOS”.
Click "Add New Todo”.
Input the name value in the text box (e.g. Read a book). Click Save button afterwards.
Result
Now go back to the "LOGS” to see the result.
Exit your application for a while. Go to the main.go once again. This time, apply this function to "false”.
func main() {
uadmin.LogAdd = false // <----
uadmin.Register(
// Some codes
)
Rebuild and run your application. Go to "TODOS” model and add another data inside it.
Result
Now go back to the "LOGS” to see the result.
As you can see, the log content remains the same. Well done!
See uadmin.LogRead for the continuation.
uadmin.LogDelete¶
LogAdd adds a log when a record is deleted.
Type:
bool
For versions 0.2.0 and above and Settings model is available, visit Log Delete page for an example.
If Settings model is not available, follow this approach:
Before you proceed to this example, see uadmin.LogEdit.
Go to the main.go and apply the LogDelete function to "true”. Put it above the uadmin.Register.
func main() {
uadmin.LogAdd = false
uadmin.LogRead = false
uadmin.LogEdit = false
uadmin.LogDelete = true // <----
uadmin.Register(
// Some codes
)
Run your application and go to "LOGS” model.
Suppose that you have this record in your logs as shown below:
Go back to uAdmin dashboard then select "TODOS”.
Select any of your existing data that you wish to delete (e.g. Washing the dishes)
Now go back to the "LOGS” to see the result.
Exit your application for a while. Go to the main.go once again. This time, apply the LogDelete function to "false”.
func main() {
uadmin.LogAdd = false
uadmin.LogRead = false
uadmin.LogEdit = false
uadmin.LogDelete = false // <---
uadmin.Register(
// Some codes
)
Rebuild and run your application. Go to "TODOS” model and delete the remaining data (e.g. Read a book).
Now go back to the "LOGS” to see the result.
As you can see, the log content remains the same. Well done!
Quiz:
uadmin.LogEdit¶
LogAdd adds a log when a record is edited.
Type:
bool
For versions 0.2.0 and above and Settings model is available, visit Log Edit page for an example.
If Settings model is not available, follow this approach:
Before you proceed to this example, see uadmin.LogRead.
Go to the main.go and apply the LogEdit function to "true”. Put it above the uadmin.Register.
func main() {
uadmin.LogAdd = false
uadmin.LogRead = false
uadmin.LogEdit = true // <----
uadmin.Register(
// Some codes
)
Run your application and go to "LOGS” model.
Suppose that you have this record in your logs as shown below:
Go back to uAdmin dashboard then select "TODOS”.
Select any of your existing data (e.g. Build a robot)
Change it to "Assembling the CPU” for instance.
Result
Now go back to the "LOGS” to see the result.
Exit your application for a while. Go to the main.go once again. This time, apply the LogEdit function to "false”.
func main() {
uadmin.LogAdd = false
uadmin.LogRead = false
uadmin.LogEdit = false // <----
uadmin.Register(
// Some codes
)
Rebuild and run your application. Go to "TODOS” model and modify any of your existing data (e.g. Assembling the CPU).
Change it to "Washing the dishes” for instance.
Result
Now go back to the "LOGS” to see the result.
As you can see, the log content remains the same. Well done!
See uadmin.LogDelete for the continuation.
uadmin.LogRead¶
LogRead adds a log when a record is read.
Type:
bool
For versions 0.2.0 and above and Settings model is available, visit Log Read page for an example.
If Settings model is not available, follow this approach:
Before you proceed to this example, see uadmin.LogAdd.
Go to the main.go and apply the LogRead function to "true”. Put it above the uadmin.Register.
func main() {
uadmin.LogAdd = false
uadmin.LogRead = true // <----
uadmin.Register(
// Some codes
)
Run your application and go to "LOGS” model.
Suppose that you have this record in your logs as shown below:
Go back to uAdmin dashboard then select "TODOS”.
Select any of your existing data.
Result
Now go back to the "LOGS” to see the result.
Exit your application for a while. Go to the main.go once again. This time, apply the LogRead function to "false”.
func main() {
uadmin.LogAdd = false
uadmin.LogRead = false // <----
uadmin.Register(
// Some codes
)
Rebuild and run your application. Go to "TODOS” model and add select any of your existing data.
Result
Now go back to the "LOGS” to see the result.
As you can see, the log content remains the same. Well done!
See uadmin.LogEdit for the continuation.