text:
Q: keras model.fit ValueError: The outer 2 dimensions of indices.shape=[1,11,1] must match the outer 2 dimensions of updates.shape=[2] I am training a keras model with custom loss and evaluation metric. It trains without metric. But it gave following error when i try to train like:
model.compile(optimizer= keras.optimizers.Adam(learning_rate = 1e-3), loss = inner_product, metrics=dice_index_metric)
 model.fit([X_train], [y_train], epochs=50, batch_size = 1, validation_split=0.2,
                 callbacks = keras.callbacks.EarlyStopping(monitor="val_loss", min_delta=0, patience=5), verbose=2)

Error:

ValueError                                Traceback (most recent call last)
<ipython-input-38-270dbe25d468> in <module>
----> 1 hist = model.fit([X_train], [y_train1], epochs=50, batch_size = 1, validation_split=0.2,
      2                  callbacks = keras.callbacks.EarlyStopping(monitor="val_loss", min_delta=0, patience=5), verbose=2)

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\keras\engine\training.py in _method_wrapper(self, *args, **kwargs)
    106   def _method_wrapper(self, *args, **kwargs):
    107     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
--> 108       return method(self, *args, **kwargs)
    109
    110     # Running inside `run_distribute_coordinator` already.

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1096                 batch_size=batch_size):
   1097               callbacks.on_train_batch_begin(step)
-> 1098               tmp_logs = train_function(iterator)
   1099               if data_handler.should_sync:
   1100                 context.async_wait()

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\eager\def_function.py in __call__(self, *args, **kwds)
    778       else:
    779         compiler = "nonXla"
--> 780         result = self._call(*args, **kwds)
    781
    782       new_tracing_count = self._get_tracing_count()

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\eager\def_function.py in _call(self, *args, **kwds)
    821       # This is the first call of __call__, so we have to initialize.
    822       initializers = []
--> 823       self._initialize(args, kwds, add_initializers_to=initializers)
    824     finally:
    825       # At this point we know that the initialization is complete (or less

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\eager\def_function.py in _initialize(self, args, kwds, add_initializers_to)
    694     self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)
    695     self._concrete_stateful_fn = (
--> 696         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
    697             *args, **kwds))
    698

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\eager\function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   2853       args, kwargs = None, None
   2854     with self._lock:
-> 2855       graph_function, _, _ = self._maybe_define_function(args, kwargs)
   2856     return graph_function
   2857

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\eager\function.py in _maybe_define_function(self, args, kwargs)
   3211
   3212       self._function_cache.missed.add(call_context_key)
-> 3213       graph_function = self._create_graph_function(args, kwargs)
   3214       self._function_cache.primary[cache_key] = graph_function
   3215       return graph_function, args, kwargs

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\eager\function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   3063     arg_names = base_arg_names + missing_arg_names
   3064     graph_function = ConcreteFunction(
-> 3065         func_graph_module.func_graph_from_py_func(
   3066             self._name,
   3067             self._python_function,

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    984         _, original_func = tf_decorator.unwrap(python_func)
    985
--> 986       func_outputs = python_func(*func_args, **func_kwargs)
    987
    988       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\eager\def_function.py in wrapped_fn(*args, **kwds)
    598         # __wrapped__ allows AutoGraph to swap in a converted function. We give
    599         # the function a weak reference to itself to avoid a reference cycle.
--> 600         return weak_wrapped_fn().__wrapped__(*args, **kwds)
    601     weak_wrapped_fn = weakref.ref(wrapped_fn)
    602

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\func_graph.py in wrapper(*args, **kwargs)
    971           except Exception as e:  # pylint:disable=broad-except
    972             if hasattr(e, "ag_error_metadata"):
--> 973               raise e.ag_error_metadata.to_exception(e)
    974             else:
    975               raise

ValueError: in user code:

    C:\Users\haluk\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\keras\engine\training.py:806 train_function  *
        return step_function(self, iterator)
    <ipython-input-36-2c54f0983574>:5 dice_index_metric  *
        y_pred1 = tf.scatter_nd(ind, updates, tf.shape(y_pred))
    C:\Users\haluk\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\ops\gen_array_ops.py:8855 scatter_nd  **
        _, _, _op, _outputs = _op_def_library._apply_op_helper(
    C:\Users\haluk\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\op_def_library.py:742 _apply_op_helper
        op = g._create_op_internal(op_type_name, inputs, dtypes=None,
    C:\Users\haluk\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\func_graph.py:591 _create_op_internal
        return super(FuncGraph, self)._create_op_internal(  # pylint: disable=protected-access
    C:\Users\haluk\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\ops.py:3477 _create_op_internal
        ret = Operation(
    C:\Users\haluk\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\ops.py:1974 __init__
        self._c_op = _create_c_op(self._graph, node_def, inputs,
    C:\Users\haluk\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\ops.py:1815 _create_c_op
        raise ValueError(str(e))

    ValueError: The outer 2 dimensions of indices.shape=[1,11,1] must match the outer 2 dimensions of updates.shape=[2]: Shapes must be equal rank, but are 2 and 1 for '{{node ScatterNd}} = ScatterNd[T=DT_INT32, Tindices=DT_INT32](strided_slice_2, Const_3, Shape_1)' with input shapes: [1,11,1], [2], [2].

Custom metric is as follows:
def dice_index_metric(y_true, y_pred):
    ind = tf.argsort(y_pred,axis=-1,direction='ASCENDING',stable=False,name=None)[-2:]
    ind = ind[..., tf.newaxis]
    updates = tf.constant([1, 1])
    y_pred1 = tf.scatter_nd(ind, updates, tf.shape(y_pred))
    innerproduct = tf.minimum(y_true, y_pred1)
    innerproduct = tf.reduce_sum(innerproduct)
    union= tf.maximum(y_true, y_pred1)
    union = tf.reduce_sum(union)
    return innerproduct/union

Custom metric converts predictions vector to a vector which top 2 element in the predictions are 1 and others are 0 then compare this to truth value and calculate their (# of intersection)/(# of union) So Lets say predictions from model is:
pred = [0.01, 0.3, 0,4 0.01, 0.01, 0.2, 0.02, 0.05],
Top 2 values are 0.3 and 0.4 with indexes 1, 2. Then I should recommend this:
reccomend = [0, 1, 1, 0, 0, 0, 0, 0],
If truth values are as follows than their intersection is only index 2 and their union is [1,2,3] than i should return 1/3.
truth = [0, 0, 1, 1, 0, 0, 0, 0]
model:
inputs = keras.Input(shape =(None,23))

features = layers.LSTM(100)(inputs)

next = layers.Dense(11, activation=activations.sigmoid)(features)

next = layers.Softmax()(next)

model = keras.Model(inputs=[inputs] , outputs=next, name="LSTMmodel2")

A: First, from your code
ind = tf.argsort(y_pred,axis=-1,direction='ASCENDING',stable=False,name=None)[-2:]

you have forgotten that y_pred is in batch. Which means y_pred's shape is not [11,] but rather [N,11], and assuming from your error message, batch size is 1.
Therefore, the line above splits in the axis of batch (which is axis 0).
This is why the error says
indices.shape=[1,11,1]

Second, scatter_nd does not work like that. Unlike gather_nd, it does not support batch_dims. The last axis value of 'indices' is the only thing that can contribute to the place where 'update' element can go into.
For example,
tf.scatter_nd([[1,2],[1,3]],[1,1],shape=(2,10))
#<tf.Tensor: shape=(2, 10), dtype=int32,
#numpy=array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#             [0, 0, 1, 1, 0, 0, 0, 0, 0, 0]])>

So in your case,
N = tf.shape(y_pred)[0]
# Shape: [N,2]
ind = tf.argsort(y_pred,axis=-1,direction='ASCENDING',stable=False,name=None)[:,-2:]

# Shape: [N,2,1]
ind = ind[...,tf.newaxis]

# Dummy range to add index for batch axis
# Shape : [N,1,1]
r = tf.range(N)[:,tf.newaxis,tf.newaxis]

# Shape : [N,2,1]
r = tf.repeat(r,2,axis=1)

# Shape : [N,2,2]
ind = tf.concat([r,ind],axis=-1)

# Shape : [N,2]
updates = tf.ones((N,2))

y_pred1 = tf.scatter_nd(ind, updates, tf.shape(y_pred))

is the right way to use tf.scatter_nd
However, it looks so dirty. I would rather recommand using this way:
second_max = tf.sort(y_pred,axis=-1,direction='ASCENDING')[:,-2,tf.newaxis]
y_pred1 = tf.cast(y_pred>=second_max,tf.int32)


text:
Q: How can I bind a DataGridTemplateColumn to column value instead of row value? I have a property grid control that has many cell editors that automatically gets applied using a CellEditorTemplateSelector. Each property grid row is bound against a simple PropertyItemViewModel.
Now, I'm trying to reuse all these cell editors and present it in a DataGrid to be able to compare multiple object values side by side. So I added a PropertiesRow object that contains a list of PropertyItemViewModel (same as the above property grid).
To present each cell, I have a simple data template that uses the same template selector as the property grid.
<DataTemplate x:Key="CellDataTemplate">
    <ContentControl
         Content="{Binding Mode=OneWay}"
         ContentTemplateSelector="{StaticResource CellEditorTemplateSelector}" />
</DataTemplate>

However, for this to work, the template expects a PropertyItemViewModel (not the PropertiesRow), so I have to somehow feed it through a binding that fetches the correct one from PropertiesRow.PropertyItems[columnIndex]. So when I add the columns through the code, I tried something like this:
void AddColumns()
{
    foreach (Property shownProperty in _ShownProperties)
    {
        _DataGrid.Columns.Add(new DataGridTemplateColumn()
        {
            Header = shownProperty.Name;
            Binding = new Binding("PropertyItems[" + index + "]");
            CellTemplate = (DataTemplate) FindResource("CellDataTemplate");
        });
    }
}

However, DataGridTemplateColumn does not have a Binding property! So I tried to generate an intermediate DataTemplate for each column, but that is starting to be very complex, and I feel there must be a simpler way of doing this.
Any suggestions?

A: I was having trouble with the XAML above but I got this to work. Had to set Path='' or the compiler was unhappy.
Content="{Binding Mode=OneWay, Path='',
                  RelativeSource={RelativeSource FindAncestor, AncestorType=DataGridCell,
                                  AncestorLevel=1},
                  Converter={StaticResource CellToColumnValueConverter}}"

A: I found a way to do it, which is not clean by MVVM standards because it plays with the DataGridCells directly, but it works fine otherwise.
I left my cell template as is, except instead of leaving it bound to my PropertiesRow object, which has no indication of which column we are in, I bind using a relative source binding to the parent DataGridCell:
<DataTemplate x:Key="CellDataTemplate">
    <ContentControl
        Content="{Binding Mode=OneWay,
     RelativeSource={RelativeSource FindAncestor,
                              AncestorType={x:Type Controls:DataGridCell}},
     Converter={StaticResource CellToColumnValueConverter}}}"
        ContentTemplateSelector="{StaticResource CellEditorTemplateSelector}" />
</DataTemplate>

I then added a CellToColumnValueConverter which takes the DataGridCell and transforms it into a PropertyItem using the index of the column:
public class CellToColumnValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        DataGridCell cell = (DataGridCell) value;
        int displayIndex = cell.Column.DisplayIndex;
        PropertiesRow r = (PropertiesRow) cell.DataContext;
        return r.PropertyItems[displayIndex];
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ant media server: Exception in thread "main" java.lang.UnsupportedClassVersionError I have downloaded the installation files of the ant media server and now I am following this tutorial to try to run the server.
So I've run this command:

./start.sh

But, I keep getting this error:

Exception in thread "main" java.lang.UnsupportedClassVersionError:
org/red5/server/Bootstrap has been compiled by a more recent version
of the Java Runtime (class file version 55.0), this version of the
Java Runtime only recognizes class file versions up to 53.0

Here's the whole stack trace:

Running java -version gives me this:

Running javac -version gives me this:

The OS info is:

Any idea what's going-on?

I have tried installing java 8 by following the commands here:

So now when I run java -version, I get this:

But, I still get the same error.

FYI, when I run this command:

sudo update-alternatives --config java

This is what I get:

I have selected option 1.
I have run the same commands for javac.
So now when I run java -version, I have this:

And when I run javac -version, I have this:

And I am still getting the same error.

The JAVA_HOME environment variable is also set to:

JAVA_HOME=/usr/lib/jvm/java-8-oracle

A: The error is telling you that the class was compiled with a newer version than the one you're running.
You need to run it with Java 11 (version 55) but you are using Java 9 (version 53).


text:
Q: Creating tables and displaying without RAD components My job gave me a challenge to do the following... I am still a rookie and learning as fast as I can but I have this curve ball and can't quite get my mind to it.
If it is not to much trouble... how can I create, modify and display Tables with the below exceptions?
RAD is out. No dataset, query or table components of any kind. For example, don't use : DataSource, DataSet, DBGrid, DBText, DBEdit etc.) A connection component like TADOConnection is acceptable.

A: You can use the ADOConnection.Execute Method to fetch data from a query and then iterate and display in some sort of manner, e.g. using a TStringGrid or the famous TVirtualTreeView

A: If you can use adoconnection, you can probably use the ADOQuery component.
Then you get something like this:
sl.Clear;
ADOQuery.Close;
try
  ADOQuery.SQL.Text:='SELECT names FROM phonebook';
  ADOQuery.Open;
  While not ADOQuery.Eof do begin
    sl.Add(AdoQuery.FieldByName('names').AsString);
    ADOQuery.Next;
  end;
finally
  ADOQuery.Close;
end;

or:
ADOQuery.Close;
try
  ADOQuery.SQL.Text := 'INSERT INTO phonebook (name,number)VALUES'+QuotedStr(NameString) +',' + QuotedStr(numberstring) +')'
  ADOQuery.ExecSQL;
finally
  ADOQuery.Close;
end;

(this uses non-parameterized queries, using parameterized queries is ofcourse better.)


text:
Q: How do I 'await' information from a modal? I have a codesandbox for this question: https://codesandbox.io/s/chakra-modal-input-forked-jelhlr?file=/src/App.jsx
I want to get the filename via the modal, and when the user completes that action, I want to do stuff with that information, in this case I want to make an api request.
Thanks!
EDIT:
I have a form with the following onSubmit:
// 1. prepare data for POST request
const data=prepareData();
// 2. get title for data entry from user
onOpen();
// 3. send data via POST request
const response=await axios.post('route',{title,data})

The way things are, the modal shows at step 2 and without waiting for user input, step 3 occurs. I want to get the title name from the user and then I want step 3 to occur.

A: I found the package react-modal-promise that does exact this. Works perfectly!

A: The value of the textbook is saved into the ref titleInputRef.
This means you can access the value of the ref/textbox with the following:
titleInputRef.current.value

To log the value to the console, for example:
console.log(titleInputRef.current.value)


text:
Q: Why do moderators choose to not delete obvious off-topic questions after they have closed them? I see this happen quite often, and while I don't agree/disagree, I am just wondering why.
Often on the sites I visit regularly (Stack Overflow and Meta Stack Exchange), I see moderators closing obvious off-topic questions, but not deleting them. There is no way to salvage those posts, the only thing that can happen is that the author gets into an argument with other members about the closing.
So that made me wonder: why do moderators not hit the delete button right after they have closed such questions? Is it common practice or policy not to do so? What are the reasons behind it?
(Sample question for those interested)

A: There are a few possible reasons here. If a post definitely cannot be saved, keeping it closed and visible does, hopefully, show an example of what we don't want on the site.
As long as it doesn't qualify for staying (upvoted answers etc) it will get removed automatically by the cleanup processes.
You mention arguments - believe me, removing causes far worse arguments than simply closing. It's better to make sure actions like this are visible.

A: Deleting questions drastically reduces the visibility of the question and the moderator actions taken there. If the question stays undeleted by the moderator, the community can still act on it with the usual community moderation tools. Closure by a moderator can be reversed by the community, deletion can't be reversed without a moderator.
The automatic deletion is also pretty effective for anything that isn't upvoted or answered, so manual deletion is simply not necessary for those cases.
Sometimes I do immediately delete, but usually only if the question is either already causing trouble, or I expect it to do so. For example aggressive or insulting comments triggered by the topic.


text:
Q: Does Connection.setAutoCommit(true) work for SQL stored procedures and functions? DB is Oracle.
I want to use Connection.setAutoCommit for SQL stored procedures and functions. Will it work?
For calling procedures I use CallableStatement

A: It won't work , connection.setAutoCommit(true), in this connection is a Java Object. You can't use same in the stored procedures.
we have a sql system variable named autocommit , if we set it as on when we write the stored procedures , your procedure will autocommit the results what ever you are trying to execute.

A: Yes it works. Actually auto-commit is on by default. This chapter will give you an idea but to save you some time:

By default, JDBC's auto-commit feature is on, which means that each SQL statement is committed as it is executed. If more than one SQL statement is executed by your program, then a small performance increase can be achieved by turning off auto-commit.

Read the CallableStatement part too:

As you may recall, CallableStatement objects are used to execute database stored procedures. I've saved CallableStatement objects until last, because they are the slowest performers of all the JDBC SQL execution interfaces. This may sound counterintuitive, because it's commonly believed that calling stored procedures is faster than using SQL, but that's simply not true. Given a simple SQL statement, and a stored procedure call that accomplishes the same task, the simple SQL statement will always execute faster. Why? Because with the stored procedure, you not only have the time needed to execute the SQL statement but also the time needed to deal with the overhead of the procedure call itself.

I think it will help you to take decisions concerning your application's performance.

A: In a word: yes.  Just make sure that you don't embed transaction logic in the stored procedure.  Leave it all up to the JDBC driver or transaction manager.
There's nothing like trying it for yourself and seeing.  I think that's even better than asking questions here.


text:
Q: On an SSD, are there any advantages to a swap partition over a swap file? If my only "hard drive" is a smallish SSD, are there any advantages to setting up a swap partition rather than a swap file?

A: It makes no difference either way.


text:
Q: How should I reference conditional assets in a rails app? To install bootstrap and have it work correctly on legacy versions of IE, you need to place this your head:
 <!--[if lt IE 9]>
  <script src="js/html5shiv.js"></script>
  <script src="js/respond.min.js"></script>
 <![endif]-->

That's fine on a static site, but how would this work in a Rails app? Do I use sprockets to do this?
I have html5shiv.js located at
root/vendor/assets/javascripts/html5shiv.js
and respond.min.js located at
root/vendor/assets/javascripts/respond.js
How should I go about including these conditional assets?

A: In application.rb:
config.assets.precompile += %w(html5shiv.js respond.js)

Then add them in your layout:
/[if LT IE 9]
  = javascript_include_tag 'html5shiv'
  = javascript_include_tag 'respond'

By the way, what about a CDN for those resources?


text:
Q: Custom QGraphicsItem That Contains Child QGraphicsItems I am new at Qt and I want to write my custom QGraphicsItem which contains a rectangle and couple of buttons. I want to write a single custom component that could be easily added to QGraphicsScene and moved or resized with contents(buttons and rectangles) in it. In the end I want to add multiple customized QGraphicsItem to my QGraphicsScene. My question is how can I write this customized QGraphicsItem that contains buttons and rectangles which relative positions to each other are constant.
In this drawing green colored rectangles represent buttons and their relative position to each other always stays same (as if they are placed using qlayouts)

A: Thanks to @replete, from the example at http://doc.qt.io/qt-5/qtwidgets-graphicsview-dragdroprobot-example.html I was able to create a custom QGraphicsItem with clickable sub-parts in it. In code below BboxItem represents container QGraphicsItem and BboxItemContent represents childs of it. By emitting signals whith mause click events I was able to implement button like features. And I can move the BboxItem by setting its bounding rectangle.
BboxItem related source code:
BboxItemContent::BboxItemContent(QGraphicsItem *parent, int type, QColor color,QRectF *rect)
    : QGraphicsObject(parent)
{
    content_rectangle = rect;
    content_type = type;
    switch (type)
    {
    case 0:
        rectangle_color = color;
        icon = 0;
        break;
    case 1:
        icon = new  QImage(":/resource/assets/info_btn.png");
        break;
    case 2:
        icon = new  QImage(":/resource/assets/close_btn.png");
        break;
    }
}

BboxItemContent::~BboxItemContent()
{
    delete icon;
}

QRectF BboxItemContent::boundingRect() const
{
    return QRectF(content_rectangle->x(), content_rectangle->y(), content_rectangle->width(), content_rectangle->height());
}

void BboxItemContent::paint(QPainter *painter,
    const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    if (icon == 0)
    {
        QPen pen(rectangle_color, 3);
        painter->setPen(pen);
        painter->drawRect(*content_rectangle);

    }
    else
    {
        painter->drawImage(*content_rectangle, *icon);
    }
}

void BboxItemContent::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
    emit bboxContentClickedSignal();
}

void BboxItemContent::setRect(QRectF *rect)
{
    content_rectangle = rect;
    update();
}

BboxItem::BboxItem(QGraphicsItem *parent,QRectF *itemRect) : BboxItemContent(parent,0,Qt::red, itemRect)
{
    setFlag(ItemHasNoContents);
    bbox_area = new BboxItemContent(this, 0, Qt::red, itemRect);
    info_btn = new BboxItemContent(this, 1, Qt::red, new QRectF(itemRect->x() - 30, itemRect->y(), 30, 30));
    connect(info_btn, &BboxItemContent::bboxContentClickedSignal, this, &BboxItem::onInfoClickedSlot);
    delete_btn= new BboxItemContent(this, 2, Qt::red, new QRectF((itemRect->x()+itemRect->width()), itemRect->y(), 30, 30));
    connect(delete_btn, &BboxItemContent::bboxContentClickedSignal, this, &BboxItem::onDeleteClickedSlot);
}

void BboxItem::onDeleteClickedSlot()
{
    //delete clicked actions
}
void BboxItem::onInfoClickedSlot()
{
    //info clicked actions
}

void BboxItem::setRect(QRectF *rect)
{
    bbox_area->setRect(rect);
    info_btn->setRect(new QRectF(rect->x() - 30, rect->y(), 30, 30));
    delete_btn->setRect(new QRectF((rect->x() + rect->width()), rect->y(), 30, 30));
}

Related Headers:
class BboxItemContent : public QGraphicsObject
{
    Q_OBJECT
public:
    BboxItemContent(QGraphicsItem *parent = 0, int type = 0, QColor color = Qt::red, QRectF *rect=nullptr);
    ~BboxItemContent();
    // Inherited from QGraphicsItem
    QRectF boundingRect() const override;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) override;
    void setRect(QRectF *rect);
signals:
    void bboxContentClickedSignal();
protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event);
private:
    QImage *icon;
    QColor rectangle_color;
    QRectF *content_rectangle;
    int content_type;
};

class BboxItem : public BboxItemContent {
    Q_OBJECT
public:
    BboxItem(QGraphicsItem *parent = 0,QRectF *itemRect=nullptr);
    void setRect(QRectF *rect);
private slots:
    void onDeleteClickedSlot();
    void onInfoClickedSlot();
private:
    BboxItemContent *delete_btn;
    BboxItemContent *bbox_area;
    BboxItemContent *info_btn;
};


text:
Q: SCM Provider not available - Maven I was trying to materialize apache Camel project in my eclipse environment. I'm using Maven 3 with Eclipse Galileo and I'm using m2Eclipse plugin.
I'm consistently getting below error message. Is this because my Eclipse lacks the SVN plugin to download from SVN repository or there is some problem with maven repository configured for Apache Camel?
3/11/11 9:58:10 PM GMT+05:30: Downloading http://repo1.maven.org/maven2/org/apache/camel/camel-core/2.6.0/camel-core-2.6.0.pom
3/11/11 9:58:10 PM GMT+05:30: Downloaded http://repo1.maven.org/maven2/org/apache/camel/camel-core/2.6.0/camel-core-2.6.0.pom
3/11/11 9:58:13 PM GMT+05:30: Downloading http://repo1.maven.org/maven2/org/apache/camel/camel-parent/2.6.0/camel-parent-2.6.0.pom
3/11/11 9:58:14 PM GMT+05:30: Downloaded http://repo1.maven.org/maven2/org/apache/camel/camel-parent/2.6.0/camel-parent-2.6.0.pom
3/11/11 9:58:16 PM GMT+05:30: Downloading http://repo1.maven.org/maven2/org/apache/camel/camel/2.6.0/camel-2.6.0.pom
3/11/11 9:58:17 PM GMT+05:30: Downloaded http://repo1.maven.org/maven2/org/apache/camel/camel/2.6.0/camel-2.6.0.pom
3/11/11 9:58:18 PM GMT+05:30: camel-core
3/11/11 9:58:18 PM GMT+05:30: Connection: scm:svn:https://svn.apache.org/repos/asf/camel/tags/camel-2.6.0
3/11/11 9:58:18 PM GMT+05:30:        dev: scm:svn:https://svn.apache.org/repos/asf/camel/tags/camel-2.6.0
3/11/11 9:58:18 PM GMT+05:30:        url: http://svn.apache.org/viewvc/camel/tags/camel-2.6.0
3/11/11 9:58:18 PM GMT+05:30:        tag: HEAD
3/11/11 9:58:18 PM GMT+05:30: SCM provider is not available for scm:svn:https://svn.apache.org/repos/asf/camel/tags/camel-2.6.0
3/11/11 9:58:18 PM GMT+05:30: No Maven projects to import
3/11/11 9:58:18 PM GMT+05:30: Project import completed 0 sec

A: Maybe your configuration is not complete, take a look at this post.
Maybe you're missing a Subversion plugin.

A: I was able to add my existing project in Eclipse Workspace folder by doing following steps.

*

*Make sure your project folder (XYZ) is present in your Eclipse Workspace folder. E.g. C:/Eclipse/Workspace/XYZ

*Go to File -> New -> Project

*Select General -> Project and click Next

*A New Project window should appear now

*Give your project name as your existing project name (e.g. XYZ)

*Keep 'Use Default Location' checked (No changes)

*Click on Finish button

*Now you should see the XYZ project opened in Project Explorer with all project files shown under it.


text:
Q: Object reference not set to an instance of an object #7 When I tried deployment my project on server I began get follow error. It inexplicable behavior for me, because I do similar action between my local computer and server.

[NullReferenceException: Object reference not set to an instance of an object.]
         MyProject.Models.ViewModels.CashboxViewModel..ctor(Cashbox entity) +168
         MyProject.Controllers.CashboxController.Index(Nullable1 id) +194
         lambda_method(Closure , ControllerBase , Object[] ) +150
         System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +241
         System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +38
         System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +11
         System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +138
         System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3d() +111
         System.Web.Mvc.Async.<>c__DisplayClass46.b__3f() +452
         System.Web.Mvc.Async.<>c__DisplayClass33.b__32(IAsyncResult asyncResult) +15
         System.Web.Mvc.Async.<>c__DisplayClass2b.b__1c() +37
         System.Web.Mvc.Async.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult) +241
         System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
         System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +111
         System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
         System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +19
         System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
         System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
         System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
         System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

Controller
[HttpGet]
public ActionResult Index(Guid? id)
{
    Cashbox obj = null;
    if (id != null)
    {
        obj = service.GetById(id.Value);
    }

    var model = (TempData[SESSION_KEYS.Transfer] as CashboxViewModel) ?? new CashboxViewModel(obj);
    SetReferenceList(model);

    return View(model);
}

    public BaseViewModel(TEntity obj)
    {
        Set(obj);
    }

    protected void Set(TEntity obj, params string[] constrains)
    {
        if (obj != null)
        {
            foreach (var info in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => x.CanRead))
            {
                if (constrains.Contains(info.Name))
                {
                    continue;
                }

                var piDest = this.GetType().GetProperty(info.Name);
                if (piDest != null && piDest.CanWrite)
                {
                    piDest.SetValue(this, info.GetValue(obj));
                }
            }
        }
    }

public class CashboxViewModel: BaseViewModel<Cashbox>
{

    public CashboxViewModel()
        : base()
    {

    }

    public CashboxViewModel(Cashbox entity)
        : base(entity)
    {

    }
}


text:
Q: Paperclip attachment_name returns nil I have two models with attached files with using of Paperclip. Those two models are almost identical, however when I call a method '.attachment_name' on each class, for the second model, it returns nil.
I'm posting here code for both models unexpurgated because I don't know what information is important.
Here is the first model:
class DocumentationFile < ActiveRecord::Base
  belongs_to :documentation

  has_attached_file :file, styles: { large: '720x720>', medium: '300x300>', thumb: '100x100>' },
                           default_url: '/images/:style/missing.png'

  validates_attachment :file, content_type: { content_type: [/\Aimage\/.*\Z/,  'application/pdf'] },
                       size: { in: 0.megabytes..5.megabytes }

  validates :file, presence: true
end

Here is a second one:
class JobExtra < ActiveRecord::Base
  belongs_to :job

  has_attached_file :file
  validates_attachment :file, content_type: { content_type: [/\Aimage\/.*\Z/, 'application/pdf'] },
                       size: { in: 0.megabytes..5.megabytes }
end

So when in rails console I'm trying to get attachment name for both models with the second model I'm getting nil:
2.3.3 :003 > DocumentationFile.attachment_name
 => :file
2.3.3 :004 > JobExtra.attachment_name
 => nil

I can't understand why it's happening and what I'm doing wrong. I've tried to add same validations and options to has_attached_file but it didn't help.
So I've run out of ideas and this issue is driving my crazy. I will be grateful for any help!

A: Can we see your controller? I had the same problem and I solved it by writing in the create method:
def create
  @job.file = params[:job][:file]
  @job.save
end

The reason behind this is that Rails actually processes the file/image, but everything is inside the model. Something like this:
Parameters:
{"job"=>{"file"=>#<ActionDispatch::Http::UploadedFile:0x007f
f342035948 @tempfile=#<Tempfile:/var/folders/_2/....jpg>, @original_filename="....jpg", filename=\"....jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"send"}


text:
Q: How to get https certificate working on local Laravel Homestead site I'm getting this problem:

The error that I'm seeing in Windows 10 Chrome Version 65.0.3325.181 (Official Build) (64-bit) is:

Your connection is not private
Attackers might be trying to steal your
information from ((mysite)) (for example, passwords,
messages, or credit cards). Learn more NET::ERR_CERT_AUTHORITY_INVALID
This page is not secure (broken HTTPS).
Certificate - missing
This
site is missing a valid, trusted certificate
(net::ERR_CERT_AUTHORITY_INVALID).

Firefox Quantum 59.0.2 (64-bit) says:

Your connection is not secure
The owner of ((mysite)) has configured their website
improperly. To protect your information from being stolen, Firefox has
not connected to this website.
Connection is Not Secure
Could not verify this certificate because the
issuer is unknown.

I have already tried: https://stackoverflow.com/a/47755133/470749
vboxmanage --version
5.2.6r120293

vagrant -v
Vagrant 2.0.2

git branch
* (HEAD detached at v7.3.0)

vagrant box list
laravel/homestead (virtualbox, 5.2.0)

vagrant box update
==> vboxHomestead: Checking for updates to 'laravel/homestead'
    vboxHomestead: Latest installed version: 5.2.0
    vboxHomestead: Version constraints: >= 5.2.0
    vboxHomestead: Provider: virtualbox
==> vboxHomestead: Box 'laravel/homestead' (v5.2.0) is running the latest version.

I wonder if this means that I'm not yet using release 7.1.0 (which has in its changelog "sign SSL certificates with a custom root certificate"), and I wonder if that's why I have this SSL HTTPS problem.
What are the next steps I should try now to get the certificate working?

A: Apparently you have to add your cert to the Trusted CA store. I let it auto decide and that did not work. Also I added it to my personal store which also did not work.
So the steps are (if you are on windows) is to hit your windows key and type in "Internet Options" and open well your internet options. Then click the "content" tab. From here click on "certificates" which is the middle button.

Then click Import and Next. Browse to where you saved the cert.
Then click "Place all certificates in the following store" and click browse and select the "Trusted Root Certificate Authorities".

And you should get a popup asking you to confirm and warning you and all that jazz.
And then make sure you restart your browser. On chrome you can type this into the URL bar: chrome://restart. Boom I hoped this helped you!

A: Unfortunately, I don't have an easy way of checking it on Windows, so I'm going to use VirtualBox running on Linux here. Install vagrant, then:
$ vagrant box add laravel/homestead
$ git clone https://github.com/laravel/homestead.git
$ cd homestead
$ git checkout v7.3.0
$ bash init.sh

I've simplified Homestead.yaml a bit (you might prefer to stick with the defaults):
---
ip: "192.168.10.10"
provider: virtualbox
folders:
    - map: /home/yuri/_/la1
      to: /home/vagrant/code
sites:
    - map: homestead.test
      to: /home/vagrant/code/public

Then:
$ mkdir -p ~/_/la1/public
$ echo '<?php echo "it works";' > ~/_/la1/public/index.php

$ vagrant up

$ vagrant ssh -c 'ls /etc/nginx/sites-enabled'
homestead.test

$ vagrant ssh -c 'cat /etc/nginx/sites-enabled/homestead.test'
server {
    listen 80;
    listen 443 ssl http2;
    server_name .homestead.test;
    root "/home/vagrant/code/public";
    ...
    ssl_certificate     /etc/nginx/ssl/homestead.test.crt;
    ssl_certificate_key /etc/nginx/ssl/homestead.test.key;
}

As we can see it has the certificates in /etc/nginx/ssl:
$ vagrant ssh -c 'ls -1 /etc/nginx/ssl'
ca.homestead.homestead.cnf
ca.homestead.homestead.crt
ca.homestead.homestead.key
ca.srl
homestead.test.cnf
homestead.test.crt
homestead.test.csr
homestead.test.key

I tried to trust server certificate systemwide, but it didn't work out. It appeared on Servers tab in Firefox' Certificate Manager, but that didn't make Firefox trust it. I could probably have added an exception, but trusting CA certificates looks like a better option. Trusting CA certificate makes browser trust any certificate they issue (new sites running under Homestead). So we're going to go with CA certificate here:
$ vagrant ssh -c 'cat /etc/nginx/ssl/ca.homestead.homestead.crt' > ca.homestead.homestead.crt

$ sudo trust anchor ca.homestead.homestead.crt

$ trust list | head -n 5
pkcs11:id=%4c%f9%25%11%e5%8d%ad%5c%2a%f3%63%b6%9e%53%c4%70%fa%90%4d%77;type=cert
    type: certificate
    label: Homestead homestead Root CA
    trust: anchor
    category: authority

Then, I've added 192.168.10.10  homestead.test to /etc/hosts, restarted Chromium, and it worked:

P.S. I'm running Chromium 65.0.3325.162, and Firefox 59.0.
Windows
Apparently, Windows doesn't have trust utility. Under Windows one has two stores: Local Machine and Current User Certificate stores. No point in using Local Machine Certificate Store, since we're making it work just for our current user. Then, there are substores. With two predefined of them being of most interest: Trusted Root Certification Authorities and Intermediate Certification Authorities Stores. Commonly referred in command line as root and CA.
You can access Chrome's Certificate Manager by following chrome://settings/?search=Manage%20certificates, then clicking Manage certificates. Of most interest are Trusted Root Certification Authorities and Intermediate Certification Authorities tabs.
One way to manager certificates is via command line:
>rem list Current User > Trusted Root Certification Authorities store
>certutil.exe -store -user root

>rem list Local Machine > Intermediate Certification Authorities store
>certutil.exe -store -enterprise CA

>rem GUI version of -store command
>certutil.exe -viewstore -user CA

>rem add certificate to Current User > Trusted Root Certification Authorities store
>certutil.exe -addstore -user root path\to\file.crt

>rem delete certificate from Current User > Trusted Root Certification Authorities store by serial number
>certutil.exe -delstore -user root 03259fa1

>rem GUI version of -delstore command
>certutil.exe -viewdelstore -user CA

The results are as follows (for both Local Machine and Current User Certificate stores):
root
    homestead.test.crt
        error
    ca.homestead.homestead.crt
        appears in Trusted Root Certification Authorities tab
CA
    homestead.test.crt
        doesn't work, appears in Other People tab
    ca.homestead.homestead.crt
        doesn't work, appears in Intermediate Certification Authorities tab

Other options would be double-clicking on a certificate in Explorer, importing certificates from Chrome's Certificate Manager, using Certificates MMC Snap-in (run certmgr.msc), or using CertMgr.exe.
For those who have grep installed, here's how to quickly check where is the certificate:
>certutil.exe -store -user root | grep "homestead\|^root\|^CA" ^
& certutil.exe -store -user CA | grep "homestead\|^root\|^CA" ^
& certutil.exe -store -enterprise root | grep "homestead\|^root\|^CA" ^
& certutil.exe -store -enterprise CA | grep "homestead\|^root\|^CA"

So, installing CA certificate into Current User > Trusted Root Certification Authorities store seems like the best option. And make sure not to forget to restart your browser.
more in-depth explanation of how it works
In Vagrantfile it requires scripts/homestead.rb, then runs Homestead.configure. That's the method, that configures vagrant to make all the needed preparations.
There we can see:
if settings.include? 'sites'
    settings["sites"].each do |site|

        # Create SSL certificate
        config.vm.provision "shell" do |s|
            s.name = "Creating Certificate: " + site["map"]
            s.path = scriptDir + "/create-certificate.sh"
            s.args = [site["map"]]
        end

        ...

        config.vm.provision "shell" do |s|
            ...
            s.path = scriptDir + "/serve-#{type}.sh"
            ...
        end

        ...
    end
end

So, these two files create certificate and nginx config respectively.
further reading
How to make browser trust localhost SSL certificate?

A: Your issue is that the issuer is unknown. As you mentioned in the errors;
"This site is missing a valid, trusted certificate"
or
"This site is missing a valid, trusted certificate (net::ERR_CERT_AUTHORITY_INVALID)"
Lets first understand why this error occurs. The browsers have list of trusted certificate authorities. You can see this list from setting/preferences section of different browsers. If your certificate is not issued by one of these authorities, then you will get the above error.
FIXING IT ON LOCALHOST
I can think of two possible solutions;

*

*Add the certificate manually to the browser and it will start opening with https.

OR

*Sign the certificate with a already trusted authority. Install the certificates on local server. Configure host in /etc/hosts file with the same name of your domain against which you have signed the certificate.

I hope it will fix the issue.


text:
Q: Having trouble accessing a key in a map inside an []interface Example code:
package main

import "fmt"

func main() {
    example_container := []interface{}{
        map[string]string{
            "name": "bob",
            "id": "1",
        },
        map[string]string{
            "name": "jim",
            "id": "2",
        },
    }
    fmt.Printf("%v\n", example_container)
    fmt.Printf("%v\n", example_container[0])
    fmt.Printf("%v\n", example_container[0]["name"])
}

Problematic line:
fmt.Printf("%v\n", example_container[0]["name"])

Error:
invalid operation: example_container[0]["name"] (type interface {} does not support indexing)

Question:
How do I access the keys inside this interface, then?
Do I have to define a more elaborate interface with a method set to accomplish this?

A: Since your slice type is []interface{}, indexing this slice will give you elements of type interface{}. Values of type interface{} cannot be indexed.
But since you put values of type map[string]string into it, you may use type assertion to obtain a value of that map type, which you can index properly:
fmt.Printf("%v\n", example_container[0].(map[string]string)["name"])

Output (try it on the Go Playground):
[map[name:bob id:1] map[name:jim id:2]]
map[name:bob id:1]
bob

If you know you will always store values of type map[string]string in your example_container slice, best would be to define it like this:
example_container := []map[string]string{
    map[string]string{
        "name": "bob",
        "id":   "1",
    },
    map[string]string{
        "name": "jim",
        "id":   "2",
    },
}

And then you don't need type assertion to access the name:
fmt.Printf("%v\n", example_container[0]["name"])

Try this one on the Go Playground.
Also note that in the composite literal you use to initialize your example_container slice, you can even omit the map type when listing the elements:
example_container := []map[string]string{
    {
        "name": "bob",
        "id":   "1",
    },
    {
        "name": "jim",
        "id":   "2",
    },
}


text:
Q: Meaning of "contumelist" J.M. Coetzee writes this sentence in Elizabeth Costello:

He is here simply to protect her, to bar the way against the
  relic-hunters and the contumelists and the sentimental pilgrims.
  (p. 30 in the 2003 Penguin edition).

More context: 'She' is an ageing famous novelist who is flying home after receiving an important award and 'he' is her son who is accompanying her and apparently has a complicated relationship with the mother. (Bear with me, I've only finished Chapter 1 so far).
What is exactly a contumelist? My guess is that it's someone who behaves with contumely but it seems to be a rare (or even made-up) word, and googling did not help much.

EDIT
From Merriam-Webster:
Definition of contumely

plural contumelies :harsh language or treatment arising from
  haughtiness and contempt; also :an instance of such language or
  treatment

A: Contumelist is indeed a very rare noun. A Google Books search finds exactly one instance of it—in "Thomas Stukely: An Historical Memoir," in Bentley's Miscellany, volume 44 (August 1858) where it is applied to a person guilty in 1569 of the crime of slander against Queen Elizabeth I:

He [Stukely] had recently had a fray with an English officer, constable of an adjacent garrison castle, who, when confronted with him at the council-board in Dublin, charged him not only with railing against the queen, and even slandering her, but with conspiring, with certain proclaimed rebels, to "levy war against the queen's majesty and her subjects." Among the articles deposed in that, when told publicly by William Hore, knight of the shire, how her majesty had given away the office of seneschal from him, he commenced railing, and coarsely exclaimed, "He did not care a ——— for the queen or her office." The contumelist was committed to close prison in the Castle on the 8th June, 1569, on the special charge of "slander spoken of the queen's majesty." We know not the precise calumny uttered against the maiden monarch, but may well believe that this breach of the injunction "no scandal against Queen Elizabeth," was the "mere flash and outbreak of a fiery mind," the false witness of a sorely disappointed man. Probably the "slander" was more political than personal, and less heinous than the disrespectful expressions of another supposed natural son of the eighth Harry, namely, Sir John Perrott, who, in consequence, died broken-hearted in the Tower, an instance how difficult it is for a crowned head to forgive the wounds inflicted by a slanderous tongue.

Clearly, the root word for contumelist is contumely—but that word has had different meanings through the years, to judge from dictionary entries for it.
From John Bulloker, An English Expositor: Teaching the Interpretation of the Hardest Words Used in Our Language (1616):

Contumelie. Reproach ; spite, disgrace.

From Henry Cockeram, The English Dictionarie: or, An Interpreter of Hard English Words, second edition (1626):

Contumely, Disgrace, reproach.

From Edward Phillips, The New World of English Words: Or a General Dictionary (1662):

Contumely, (Lat) injury, reviling.

From Thomas Blount, Glossographia Anglicana Nova: Or, A Dictionary, Interpreting Such Hard Words of Whatever Language, as Are at Present Used in the English Tongue (1707):

Contumely, (Lat.) Reproach, Abuse, scurrilous Language.

From John Kersey, A New English Dictionary; or, A Compleat Collection of the Most Proper and Significant Words, and Terms of Art Commonly Used in the Language, second edition (1713):

A Contumely, a Reproach, an outrageous Affront.

From Nathan Bailey, An Universal Etymological English Dictionary, second edition (1717):

CONTUMELY, {Contumélie, F. of Contumelia, L.} Abuse, Affront, Reproach, scurrilous Language.

Thomas Dyche & William Pardon, A New General English Dictionary; Peculiarly Calculated for the Use and Improvement of Such as Are Acquainted with the Learned Languages (1740):

CONTUMELY (S.) an affront, abuse, or reproach.

From Samuel Johnson, A Dictionary of the English Language, volume 1 (1756):

CONTUMELY. s. {contumelia, Lat.} Rudeness ; contemptuousness; bitterness of language ; reproach. Hooker, Tillotson.

From John Ash, The New and Complete Dictionary of the English Language, volume 1 (1775):

Contumely (s. from contumelious [meaning "Contemptuous, rude, reproachful, inclined to reproach, productive of reproach"]) Rudeness, reproach, bitterness of expression.

From Noah Webster, An American Dictionary of the English Language (1828):

CONTUMELY, n. {L. contumelia, from contumeo; con and tumeo to swell.} Rudeness or reproach compounded of haughtiness and contempt; contemptuousness; insolence; contemptuous language. [Cited example:] The oppressor's wrong; the proud man's contumely. Shak.

From Webster's New International Dictionary (1909):

contumely n.; pl. -LIES. {L. contumelia, prob. akin to contumax insolent : cf. O[ld] F[rench] contumelie. Cf. CONTUMACY.} 1. Rudeness compounded of haughtiness and contempt scornful insolence; despiteful treatment; disdain; contemptuousness in act or speech. [Examples omitted.] 2. An instance or exhibition of contumely; an insult. 3. The suffering of contumely; humiliation.

From The Compact Edition of the Oxford English Dictionary (1971):

Contumely sb. {a OF. contumelie, ad. L. contumēlia abuse, insult, reproach ; in origin prob. cognate with CONTUMAX, in which the stem part tum is of disputed etymology.} 1. Insolent reproach or abuse; insulting or offensively contemptuous language or treatment; despite; scornful rudeness : now, esp. such contemptuous treatment as tends to inflict dishonour and humiliation. [Examples, from 1386 forward, omitted.] 2. (with a and pl) An instance of contumely; an insult[,] an insolent reproach, a piece of scornful or contemptuous insolence. [Examples, from 1450 forward, omitted.] 3. Contemptuous insult as it affects the sufferer : disgrace, reproach, humiliation. [Examples, from 1555 forward, omitted.]

From The American Heritage Dictionary of the English Language, fifth edition (2010):

contumely n., pl. -lies 1. Rudeness or contempt arising from arrogance; insolence. 2. An insolent or arrogant remark or act. {Middle English contumelie < Old French < Latin contumēlia; akin to to contumāx, insolent.}

None of these dictionaries—not even the OED—mentions the word contumelist, but we may infer that it describes a person swelled up with self-importance who has the insolence to criticize, reprove, demean, or otherwise insult a person who is objectively much superior to the critic.
Looking at the larger context of the quotation in Coetzee's novel, we find this language:

What is the truth of his mother? He does not know, and at the deepest level does not want to know. He is here simply to protect her, to bar the way against the relic-hunters and the contumelists and the sentimental pilgrims. He has opinions of his own, but he will not speak them. This woman, he would say if he were to speak, whose words you hang on as if she were the sybil, is the same woman who, forty years ago, hid day after day in her bedsitter in Hampstead, crying to herself, crawling out in evenings into the foggy streets to buy the fish and chips on which she lived, falling asleep in her clothes.

It thus appears that the son sees his task as being to protect his psychically delicate mother from souvenir hounds ("the relic-hunters"), fawning idolators ("the sentimental pilgrims"), and insolent iconoclasts ("the contumelists"). This last group, presumably, is inclined to view a famous person such as the mother as fair game for their aggressive rudeness and desire to humiliate. A shade of bitter jealousy may also lurk in the contumelist's impulse to disparage.


text:
Q: How to automatically change the volume after Pulse Audios starts? I am suffering from the problem described here and here, which unfortunately still hasn't been fixed. Basically after rebooting my computer my volume is at 100% until I trigger the volume. What I mean by this is that the software volume indicator is showing the setting that was set before (e.g. 20%) however the actual sound will be played at 100% until I move the slider a bit and the system "realises" what the volume setting is. I am using an external DAC (which is like a USB soundcard) which is a Schiit Audio.
As a workaround I'm trying to trigger the volume by adding the following command to the startup applications list (Session and Startup) as suggested here:
pacmd set-sink-volume 2 20000

Unfortunately this doesn't seem to work, possibly because the Pulse Audio System is not running yet when the command is executed. I've tried sleeping before executing it, but that doesn't help either; moreover I want to have a guarantee that the volume has been set properly so that I don't have to live a stressful life ;)
I've tried renaming my task so that it is at the end of the list to no avail.
Is there any other way for me to set the volume automatically after Pulse Audio loads? I don't want to get a heart attack every time I forget to retrigger the volume after login...
I am using Xubuntu 14.04.

A: The pulseaudio module responsible to restore any device's volume to values before rebooting is the module-device-restore. If restoring devices does not work as expected  we may want to check if that module was loaded with:
pacmd list-modules

If it was not there we should add the module to our default.pa settings file. This file is located in /etc/pulse by default but we can have an additinal per-user default.pa overriding this in ~/.pulse/ or in ~/.config/pulse/. When editing make sure you choose the appropriate file, and make a backup beforehand.
To load module-device-restore on starting the pulseaudio sound server the following line has to be included (or uncommented) in the default.pa:
load-module module-device-restore


text:
Q: AWK complains about number of fields when extracting variables I have a script to parse a TeamCity directory map file. The script works, but I want to know why refactoring it into using variables breaks it with a seemingly unrelated error message and how I can still have it work using variables.
MAP=/opt/TeamCity/buildAgent/work/directory.map
sed -n -e '1,3d;1,/#/{/#/!p}' $MAP | \
awk '   {
            n=split($0, array, "->");
            printf(substr(array[1], 6) substr(array[2],2,16) "\n");
        }
'

This prints
nicecorp::Master 652293808ace4eb5
nicecorp::Reset Database 652293808ace4eb5
nicecorp::test-single-steps 652293808ace4eb5
nicecorp::Develop 652293808ace4eb5
nicecorp::Pull Requests 652293808ace4eb5

Which is pretty much what I want.
The refactoring that breaks
But then I was trying to extract the sub strings into variables, and the script broke. I changed the last printf statement into this
proj=substr(array[1], 6);
tcdir=substr(array[2],2,16);
printf($proj"  " $tcdir);

That just prints this error, although I thought it was more or less the same?
awk: program limit exceeded: maximum number of fields size=32767
        FILENAME="-" FNR=1 NR=1

This error seems a bit weird, given that my total input is about 500 bytes, 60 times less than the limit they complain about with regards to fields.
AWK version: mawk (1994)
Data format ($ head -10 directory.map):
#Don't edit this file!
#Nov 5, 2019 1:49:26 PM UTC
--version=2
bt30=nicecorp::Master -> 652293808ace4eb5 |?| Oct 29, 2019 4:14:27 PM UTC |:| default
bt32=nicecorp::Reset Database -> 652293808ace4eb5 |?| Oct 30, 2019 1:01:48 PM UTC |:| default
bt33=nicecorp::test-single-steps -> b96874cc9acaf874 |?| Nov 4, 2019 4:20:13 PM UTC |:| default
bt33=nicecorp::test-single-steps -> 652293808ace4eb5 |?| Nov 5, 2019 9:00:37 AM UTC |:| default
bt28=nicecorp::Develop -> 652293808ace4eb5 |?| Nov 5, 2019 1:07:53 PM UTC |:| default
bt29=nicecorp::Pull Requests -> 652293808ace4eb5 |?| Nov 5, 2019 1:18:08 PM UTC |:| default
#

A: The source of the problem is that the print statement in the refactor is using shell notation for variable ($proj instead of proj, $tcdir instead of tcdir).
When those values are numeric (e.g., tcdir=652293808ace4eb5 for the  first line), awk (mawk in this case) will try to print 652293808-th column. Current version of gawk will not fail here - they will realize there are only few columns, and will show empty string for those field (or the full line for $0, if the value is non numeric)
Older version may attempt to extend the field list array to match the requested number, resulting in limit exceeded message.
Also note two minor issues - refactored code uses proj as format - it will get confused if '%' is included. Also, missing newlines. Did you really mean printf and not print ?
Fix:
proj=substr(array[1], 6);
tcdir=substr(array[2],2,16);
# Should consider print, instead of printf
printf(proj "  " tcdir "\n");
# print proj, tcdir

A: The problem was syntax. I was using the shell style $tcdir to insert the value of the variable instead of simply tcdir. By (some unknown to me) means the tcdir portion of $tcdir is resolved to some numeric field value, meaning I am trying to print the value of a field, not the variable tcdir.


text:
Q: How can i show information from a foreign key when creating a SQL Function? I am currently working on a school project and keep hitting a roadblock..
I would like to get the names linked to the foreign keys('geleendvan' and 'geleendaan'). these two are currently numbers that match with a ID from a person table. Before i go deeper into my question let me show you the queries:
'''
create or replace trigger lening_bri
BEFORE
insert on lening
for each row
DECLARE
 NieuweSleutel INTEGER;
 Resultaat VARCHAR2(255);
 Fout EXCEPTION;
BEGIN
 -- eerst integriteits check uitvoeren
 Resultaat := sf_check_lener_onmogelijk(:new.geleendvan,:new.geleendaan);
 IF Resultaat <> 'Normaal' THEN
  -- resultaat niet goed, fout forceren
  RAISE fout;
 END IF;
 --
 SELECT nvl(max(l.nummer),0)
 INTO NieuweSleutel
 FROM lening l;
 --
 NieuweSleutel := NieuweSleutel + 1;
 :new.nummer := NieuweSleutel;
EXCEPTION
  -- foutafhandeling
  WHEN fout THEN
    apex_error.add_error (p_message => resultaat,
                          p_additional_info => null,
                          p_display_location => apex_error.c_inline_in_notification );
    raise;
END;

'''
The above query is a trigger when a loan(lening) is created, the newkey(NieuweSleutel) part is quite irrelevant but as you can see at line 10 there is a variable Result(Resultaat) here i use the following SQLFunction:
'''
create or replace FUNCTION sf_check_lener_onmogelijk
(in_geleendvan IN VARCHAR2,
in_geleendaan IN VARCHAR2)
RETURN VARCHAR2
is
 resultaat VARCHAR2(255);

BEGIN
 IF in_geleendvan == in_geleendaan THEN
  resultaat := 'Toevoegen afgebroken. Persoon ['||in_geleendvan||' '||in_geleendaan||'] mogen niet het zelfde zijn :( .';
 ELSE
  resultaat := 'Normaal';
 END IF;
  RETURN resultaat;
END;

'''
As you can see the Function checks if the person that is loaning isnt the same as the person who is lending(in_geleendvan and in_geleendaan).
But here is the problem: The function uses the ID's to check if they are the same, which isnt a problem on itself but i would like to return the names that match with the number. Does this mean i have to alter the function or change something in my trigger? If so do you guys have any suggestion?
Thanks in advance! :)

A: Your function is invalid as you want = instead of ==. Then you can select the name from the appropriate table:
create or replace FUNCTION sf_check_lener_onmogelijk(
  in_geleendvan IN lening.geleendvan%TYPE,
  in_geleendaan IN lening.geleendaan%TYPE
)
RETURN VARCHAR2
IS
  v_name_gv people.name%TYPE;
  v_name_ga people.name%TYPE;
BEGIN
  IF in_geleendvan = in_geleendaan THEN
    SELECT name
    INTO   v_name_gv
    FROM   people
    WHERE  id = in_geleendvan;

    SELECT name
    INTO   v_name_ga
    FROM   people
    WHERE  id = in_geleendaan;

    RETURN 'Toevoegen afgebroken. Persoon ['||v_name_gv||' '||v_name_ga||'] mogen niet het zelfde zijn :( .';
  ELSE
    RETURN 'Normaal';
  END IF;
END;
/

Then you should not find the maximum nummer and add one; use a sequence or an IDENTITY column (and ignore any gaps in the sequence):
CREATE TABLE lening (
  nummer     INTEGER
             GENERATED ALWAYS AS IDENTITY
             CONSTRAINT lenng__nummer__pk PRIMARY KEY,
  geleendvan VARCHAR2(20),
  geleendaan VARCHAR2(20)
);

Then your trigger can be:
create or replace trigger lening_bri
BEFORE insert on lening
for each row
DECLARE
 Resultaat VARCHAR2(255);
 Fout EXCEPTION;
BEGIN
  -- eerst integriteits check uitvoeren
  Resultaat := sf_check_lener_onmogelijk(:new.geleendvan,:new.geleendaan);
  IF Resultaat <> 'Normaal' THEN
    RAISE fout;
  END IF;
EXCEPTION
  -- foutafhandeling
  WHEN fout THEN
    apex_error.add_error(
      p_message          => resultaat,
      p_additional_info  => null,
      p_display_location => apex_error.c_inline_in_notification
    );
    raise;
END;
/

db<>fiddle here

A: If I understood you correctly, you'd change the function. Something like this (I don't have your tables so I'm just guessing column/table names):
CREATE OR REPLACE FUNCTION sf_check_lener_onmogelijk (
   in_geleendvan  IN VARCHAR2,
   in_geleendaan  IN VARCHAR2)
   RETURN VARCHAR2
IS
   resultaat          VARCHAR2 (255);
   l_name_geleendvan  some_table.name%TYPE;
   l_name_geleendaan  some_table.name%TYPE;
BEGIN
   IF in_geleendvan = in_geleendaan
   THEN
      SELECT name
        INTO l_name_geleendvan
        FROM some_table
       WHERE id = in_geleendvan;

      SELECT name
        INTO l_name_geleendaan
        FROM some_table
       WHERE id = in_geleendaan;

      resultaat :=
            'Toevoegen afgebroken. Persoon ['
         || l_name_geleendvan
         || ' '
         || l_name_geleendaan
         || '] mogen niet het zelfde zijn :( .';
   ELSE
      resultaat := 'Normaal';
   END IF;

   RETURN resultaat;
END;


text:
Q: What SQL Server Query will set perfmon counter "Longest Transaction Running Time" > 0 I'm trying to decide whether this performance counter is worthwhile monitoring:
\\SERVER\MSSQL:Transactions\Longest Transaction Running Time.
So during testing I tried to create some long running transactions but I can't seem to get this counter to read anything greater than zero.
But I can't find a transaction or query that will do it. As a starting point, I used the example query (an insert in a transaction) in the help for DBCC OPENTRAN with no luck.
Is there a query that affects this counter?

A: This counter seems to be a little bit slow/ hit and miss on updating, and I'm not entirely convinced its doing exactly what its explanation suggests, however I seemed to get the most success by doing a select into from (a large table) in an open ended transaction.
Funnily enough issuing a rollback seemed to cause the counter stat to be updated immediately, commit was less effective and sometimes it would update without either. As I say I dont think this counter is exactly what we think, and might just be an approximation/ average.
Regards,
Mark
@retracement

A: This should give you a value in that counter.  You'll obviously have to manually stop it.
SELECT '1' AS field1 INTO #tmp
BEGIN TRANSACTION
WHILE 1=1
BEGIN
    UPDATE #tmp SET field1=1
END
COMMIT TRANSACTION
DROP TABLE #tmp

A: Little late to the party. I believe the documentation has been updated to explain the answer to this in the last six years, but per my testing it isn't completely correct.
From Books Online: "The length of time (in seconds) since the start of the transaction that has been active longer than any other current transaction. This counter only shows activity when the database is under read committed snapshot isolation level. It does not log any activity if the database is in any other isolation level."
Per my testing, this is not quite correct. If RCSI is not enabled, but you are allowing snapshot, it will show the longest running transaction time for SNAPSHOT queries.
The other tricky thing is that the counter only updates every 60 seconds.
Basically, it's very useful for monitoring if something's going to block version store cleanup when you're using snapshot or RCSI.


text:
Q: What could globally affect texture coordinate values in OpenGL? I'm writing a plugin for an application called Autodesk MotionBuilder, which has an OpenGL renderer, and I'm trying to render textured geometry into the scene. I have a window with a 3D View embedded in it, and every time my window is rendered, this is (in a nutshell) what happens:

*

*I tell the renderer that I'm about to draw into a region with a given size

*I tell the renderer to draw the MotionBuilder scene in that region

*I draw some additional stuff into and/or on top of the scene

The challenge here is that I'm inheriting some arbitrary OpenGL state from MotionBuilder's renderer, which varies depending on what it's drawing and what's present in the scene. I've been dealing with this fine so far, but there's one thing I can't figure out. The way that OpenGL interprets my UV coordinates seems to change based on whatever MotionBuilder is doing behind my back.
Here's my rendering code. If there's no textured geometry in the scene, meaning MotionBuilder hasn't yet fiddled with any texture-related attributes, it works as expected.
// Tell MotionBuilder's renderer to draw the scene
RenderScene();

// Clear whatever arbitrary state MotionBuilder left for us
InitializeAttributes(); // includes glPushAttrib(GL_ALL_ATTRIB_BITS)
InitializePerspective(); // projects into the scene / loads matrices

// Enable texturing, bind to our texture, and draw a triangle into the scene
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, mTexture);

glBegin(GL_TRIANGLES);
glColor4f(1.0, 1.0, 1.0, 0.5f);
    glTexCoord2f(1.0, 0.0); glVertex3f(128.0,   0.0, 0.0);
    glTexCoord2f(0.0, 1.0); glVertex3f(  0.0, 128.0, 0.0);
    glTexCoord2f(0.0, 0.0); glVertex3f(  0.0,   0.0, 0.0);
glEnd();

// Clean up so we don't confound MotionBuilder's initial expectations
RestoreState(); // includes glPopAttrib()

Now, if I bring in some meshes with textures, something odd happens. My texture coordinates get scaled way up. Here's a before and after:

(source: awforsythe.com)
As you can see from the close-up on the right, when MotionBuilder is asked to render a texture whose file it can't find, it instead loads this small question mark texture and tiles it across the geometry. My only hypothesis is that MotionBuilder is changing some global texture coordinate scalar so that, for example, glTexCoord2f(0.5, 1.0) will instead be interpreted as if it were (50.0, 100.0). Is there such a feature in OpenGL? Any idea what I need to modify in order to preserve my texture coordinates as I've entered them?

Since typing the above and after doing a bit of research, I have discovered that there's a GL_TEXTURE matrix that's used to this effect. Neat! And indeed, when I get the value of this matrix initially, it's the good ol' identity matrix:
 1  0  0  0
 0  1  0  0
 0  0  1  0
 0  0  0  1

When I check it again after MotionBuilder fudges up my texture coordinates:
16  0  0  0
 0 16  0  0
 0  0  1  0
 0  0  0  1

How telling! But here's a slight problem: if I try to explicitly set the texture matrix before doing my own drawing, regardless of what MotionBuilder is doing, it seems like my texture coordinates have no effect and it simply samples the lower-left corner of the texture (0.0, 0.0) for every vertex.
Here's the attempted fix, placed after RenderScene in the code posted above:
glMatrixMode(GL_TEXTURE);
glLoadIdentity();

I can verify that the value of GL_TEXTURE_MATRIX is now the identity matrix, but no matter what coordinates I specify in glTexCoord2f, it's always drawn as if the coordinates for each vertex were (0.0, 0.0):

(source: awforsythe.com)
Any idea what else could be affecting how OpenGL interprets my texture coordinates?

A: Aha! These calls:
glMatrixMode(GL_TEXTURE);
glLoadIdentity();

...have to be made after GL_TEXTURE_2D is enabled.
...should be followed up by setting the matrix mode back to GL_MODELVIEW. It turns out, apparently, that some functions I was calling immediately after resetting the texture matrix (glViewport and/or gluPerspective?) affect the current matrix stack. So those calls were affecting the texture matrix, causing my texture coordinates to be transformed in unexpected ways.
I think I've got it now.


text:
Q: DataError: invalid input syntax for integer: "active" - Odoo v8 to Odoo v10 community these methods should update the res.partner name on form view, it opens a new window, showing partners name, and a button to update it.
Originally on v8 it looked like this:
class WizUpdatename(osv.osv_memory):
_name = 'wiz.updatename'
_description = "Wizard that changes the partner name"

def set_name(self, cr, uid, ids, context):
    """ Change value of the name field
    """
    data = self.pool.get('wiz.updatename').read(cr, uid, ids)[0]
    if not data['sure']:
        raise osv.except_osv(
            _("Error!"),
            _("Please confirm that you want to do this by checking the"
              " option"))

    partner_obj = self.pool.get('res.partner')
    name_partner = data['name']

    partner_obj.write(cr, uid, context['active_id'],
                      {'name': name_partner}, context=context)
    return {}

def _get_name(self, cr, uid, context=None):
    """ Get name field value
    """
    if context is None:
        context = {}
    partner_obj = self.pool.get('res.partner')
    partner = partner_obj.search(cr, uid,
                                 [('id', '=', context['active_id'])])
    partner_o = partner_obj.browse(cr, uid, partner[0])
    return partner_o and partner_o.name or False

_columns = {
    'name': fields.char(
        string='Name', size=256, required=True,
        default=lambda s: s._get_name()),
    'sure': fields.boolean('Are you sure?'),
}

WizUpdatename()

After mirgation, it now look like this:
class WizUpdatename(models.TransientModel):
_name = 'wiz.updatename'
_description = "Wizard that changes the partner name"

name = fields.Char(
    string='Name', size=256, required=True,
    default=lambda s: s._get_name())
sure =fields.Boolean(string='Are you sure?')

@api.multi
@api.depends('res.partner')
def set_name(self): #, cr, uid, ids, context
    """ Change value of the name field
    """
    data = self.env['wiz.updatename'].read()[0]
    if not data['sure']:
        raise UserError(
            _("Error!"),
            _("Please confirm that you want to do this by checking the"
              " option"))

    partner_obj = self.env['res.partner']
    name_partner = data['name']

    partner_obj.write(context['active_id'],
                      {'name': name_partner})
    return {}

@api.depends('res.partner')
def _get_name(self): #, cr, uid, context=None
    """ Get name field value
    """
    #if context is None:
        #context = {}
    #ctx = self._context.get()
    partner_obj = self.env['res.partner']
    partner = partner_obj.search([('id', '=', 'active')])
    partner_o = partner_obj.browse(partner[0])
    return partner_o and partner_o.name or False

But everytime I click on this, it throws:
Traceback (most recent call last):
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 675, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 331, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/service/model.py", line 119, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 324, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 933, in __call__
return self.method(*args, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 504, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 862, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 854, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 679, in call_kw
return call_kw_model(method, model, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 664, in call_kw_model
result = method(recs, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 1101, in default_get
defaults[name] = field.default(self)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/wizard_update_name.py", line 37, in <lambda>
default=lambda s: s._get_name())
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/wizard_update_name.py", line 67, in _get_name
partner = partner_obj.search([('id', '=', 'active')]) #cr, uid, context['active_id'] later added ctx before active_id, now, brackets removed let's see
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 1497, in search
res = self._search(args, offset=offset, limit=limit, order=order, count=count)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/base/res/res_partner.py", line 621, in _search
count=count, access_rights_uid=access_rights_uid)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 4203, in _search
self._cr.execute(query_str, where_clause_params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/sql_db.py", line 141, in wrapper
return f(self, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/sql_db.py", line 218, in execute
res = self._obj.execute(query, params)
DataError: invalid input syntax for integer: "active"
LINE 1: ...artner"."active" = true)  AND  "res_partner".id = 'active') ...

The error is on this line partner = partner_obj.search([('id', '=', 'active')]) now, originally active was active_id, because it should browse one record based on that, but on new Odoo v10, the field active_id no longer exists, there's an active one, but I think is  used in some other way, obviously different from active_id.
I still can't find something equivalent for this field on v10 community.
Any ideas?

A: You can not search integer fields with the string.
You can get active ids from the context variable to search selected partners.
To get active_id use following code
self._context.get('active_ids')

**here is you method with correction **
@api.depends(your_field_name)
def _get_name(self):
    partner_obj = self.env['res.partner']
    partner = partner_obj.search([('id', '=',self._context.get('active_ids'))],limit=1)
    return partner and partner.name or False

This may help you.

A: The depends decorators aren't necessary here. The new API search will already return a RecordSet, so there is no need to browse again. Or since you already have the ID in context, just use browse. I would migrate both methods like:
@api.multi
def set_name(self):
    """ Change value of the name field """
    self.ensure_one()
    if not self.sure:
        raise UserError(
            _("Error!"),
            _("Please confirm that you want to do this by checking the"
            " option"))

    partner_obj = self.env['res.partner']

    partner_obj.browse(self.env.context.get('active_id', 0).write(
        {'name': self.name})
    return {}

@api.model  # default methods don't work on records
def _get_name(self):
    """ Get name field value """
    partner = self.env['res.partner'].browse(
        self.env.context.get('active_id', 0))
    return partner.name if partner else False


text:
Q: E-mail sheet preview with formatting in HTML body + attach sheet I have applied this solution to e-mail the rows of a google sheet as part of the HTML body.
Unfortunately, it errors out because there is a limit set on the HTML body. The number of rows in my data is dynamic.

Limit Exceeded: Email Body Size. (line 209, file "SideBar")

Is there a way of getting around this? I would be OK with providing a preview of the rows, let's say 10 rows with all columns, on the HTML body and then providing a link to view the rest. Because the content on the sheet changes, the link should not be to that sheet. Instead I was thinking of saving a copy of the sheet as a new file on their own drive and linking to that. Another option is attaching an HTML file that has all the rows.
Here is what I currently have:
function emailBreakdown(emailUser, bodyAdd){
  SpreadsheetApp.getActiveSpreadsheet().toast('Please wait while information is refreshed.');
  if(emailUser == null){emailUser = 'xxxxx@yyyyyy.com'}
  if(bodyAdd == null){bodyAdd = 'Testing running of function on script editor'}
  var ss = SpreadsheetApp.getActive();
  var detailsSht = ss.getSheetByName("Details");
  var dataRange = detailsSht.getDataRange();
  var curDate = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yyyy");
  var subject = 'Summary - Exported Data ' + curDate;
  var body = '
---------------------------------------------------------------
You have received an export of a dataset from the Summary dashboard. Please see below:

' //provide link to the whole dashboard.

  convSheetAndEmail(dataRange, emailUser, body, bodyAdd, subject);
}

function convSheetAndEmail(rng, emailUser, body, bodyAdd, subject){
  var HTML = SheetConverter.convertRange2html(rng);
  MailApp.sendEmail(emailUser, subject, '', {htmlBody : bodyAdd + body + HTML});
}

A: The following is code I've been able to assemble through further research. It works well and addresses my requests. Here is what it does:

*

*Attaches a sheet. In this case an xls file. Chose this over HTML. To allow user to manipulate in excel if needed.

*Provides a preview of 10 lines as HTML in the body of the e-mail.

*Preview and attached file preserves format.

What it does not address:

*

*Save file to user's personal drive.

Here it goes:
function emailBreakdown(emailUser, bodyAdd){
  SpreadsheetApp.getActiveSpreadsheet().toast('Please wait while information is refreshed.');

  //If running on script editor the variables will not be transferred. Assign values below:
  if(emailUser == null){emailUser = 'xxxxxx@yyyyyyy.com'}
  if(bodyAdd == null){bodyAdd = 'Testing running of function on script editor'}

  var ss = SpreadsheetApp.getActive();
  var detailsSht = ss.getSheetByName('Details');
  var dataRange = detailsSht.getRange('A1:FS11'); //For the preview we are only looking at the first 10 rows of data.
  var curDate = Utilities.formatDate(new Date(), 'GMT+1', 'MM/dd/yyyy');

  //Gather data to convert specific sheet to excel document so it can be attached to the e-mail
  var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
  var sheetID = detailsSht.getSheetId().toString()
  var requestData = {'method': "GET", 'headers':{'Authorization':'Bearer ' + ScriptApp.getOAuthToken()}};
  var url = 'https://docs.google.com/spreadsheets/d/' + ssID + '/export?format=xlsx&id=' + ssID + '&gid=' + sheetID;
  var result = UrlFetchApp.fetch(url , requestData);
  var contents = result.getContent();

  //Assemble E-mail components
  var subject = 'Summary - Exported Data ' + curDate;
  var body = bodyAdd +
    '

' +
    'You have received an export of a dataset from the Summary dashboard. Below is a preview of the dataset:

'
  var afterBody = '

You can view the full dataset through the attached XLS file.'

  convSheetAndEmail(ss, contents, dataRange, emailUser, body, afterBody, subject);
};

function convSheetAndEmail(ss, contents, rng, emailUser, body, afterBody, subject){
  var HTML = SheetConverter.convertRange2html(rng);

  //Send email
  MailApp.sendEmail(
    emailUser,
    subject,
    '',{
     htmlBody : body + HTML + afterBody,
     name: 'Full Data Export',
     attachments:[{fileName:'Export Data - ' + ss.getName() + '.xls', content:contents, mimeType:'application//xls'}]
    }
  );
};

Apart from the resource listed in the question, I also borrowed code from here.


text:
Q: replicating an excel solver function in python to get required output assuming I got cashflows from year 1 through year 4
cf = [30,45,52,67]
and discount rates (zero coupon)
rt = [.02,.03,.04,.05]
calculating PV is straight fwd in python
import numpy as np
import pandas as pd

cf = [30,45,52,67]
rt = [.02,.03,.04,.05]

sum([x[0]/(1+x[1])**(i+1) for i,x in enumerate(zip(cf,rt))])

gives me the output
173.1775
Now, if I want my NPV to be 180 (hypothetically), I will simply run a solve in excel and that will adjust my "rt" (by adding a spread across the board)

How do I replicate the same in python? I have seen/ used SciPy optimize for other purpose, but unsure how do I use it here (or if there is any other solution)

A: You can solve your problem using newton (an implementation of the Newton-Raphson method) from scipy.optimize.
newton needs a starting point and a function of a single parameter that evaluates to zero when you reach your target (this is not truly true, newton can accept also functions of more than one variable, but…) so we write a function that accepts your arguments and returns the function needed by newton, and at last we call newtonwith the initial value of zero
In [25]: from scipy.optimize import newton
    ...: cf = [30,45,52,67]
    ...: rt = [.02,.03,.04,.05]
    ...:
    ...: def make_fun(cf, ret, val):
    ...:     def fun(d):
    ...:         return val-sum([x[0]/(1+x[1]+d)**(i+1)for i,x in enumerate(zip(cf,rt))])
    ...:     return fun
    ...:
    ...: newton(make_fun(cf, rt, 180), 0)
Out[25]: -0.014576385759418057

Edit: of course you can choose a more descriptive name for make_fun …


text:
Q: android switch activity with CountDownTimer i am having 2 activities right now, the first one contain a "start" button, and when user press start, it will go to the second activity by
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(myIntent);
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);

and when the second activity starts, it automatically starts a CountDownTimer which i have
        countDownTimer = new MalibuCountDownTimer(startTime, interval);
    countDownTimer.start();

inside OnCreate of the second activity. Currectly startTime is 20 second, and I have it displayed onto a textview with this
 text.setText(""+String.format("%02d:%02d:%03d",
                    TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                    TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)),
                    TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished))
                    ));

However, when the second activity starts, the time would show something like

00:19:674

something like that, like it would never starts at 00:20:000, is there a way to fix this problem?
Thanks

A: You can put countDownTimer.start() and textview.setText() in onResume() instead of onCreate()


text:
Q: Is entity framework running a db query with every .Count() method called in my code I have a loop in my razor syntax that looks something like this. And in each loop I'm getting a count of the registered students for a class. Will a db query be called/executed to acquire this count? Should I keep a int value of this number so that a db call doesn't have to be made with each call to it. My loop might be 15-20 per page.
foreach (var space in Model.Spaces)
{
    // do some stuff
    @{ var studentCount = @space.RegisteredStudents.Count(); }
}

Note - registeredstudents looks like this in another entity that I'm pulling from the db when getting my results. So registeredstudents has its own table.
public virtual ICollection<Student.RegisteredStudent> RegisteredStudents { get; set; }

A: Do not use Entity Framework model classes as view-model objects in ASP.NET MVC. While often they contain the data you want to display it violates aspects of MVVM design, one example is the case you're seeing where your pages are (indirectly) executing DB queries.
Instead create a dedicated view-model class for each view which explicitly contains the data you want. These can be simple POCO classes.
I personally prefer to put read-only data in ViewData instead of the view's Model property, I also subclass ViewData to add strongly-typed properties, but this is down to personal preference.
In your case:
ViewModels
class SpacesViewModel {
    public IList<SpaceViewModel> Spaces { get; set; }
}
class SpaceViewModel {
    public Int32 StudentCount { get; set; }
}

Controller action
public ActionResult View() {

    IQueryable<Spaces> dbSpaces = ... // get `Spaces` instance from Entity Framework

    SpacesViewModel vm = new SpacesViewModel();
    vm.Spaces = dbSpaces.Select(
        dbSpace => new SpaceViewModel() {
            StudentCount = dbSpace.RegisteredStudents.Count();
        }
    ).ToList();

    return this.View( vm );
}

View
@model SpacesViewModel

@foreach(SpaceViewModel space in Model.Spaces) {
    @space.StudentCount
}

A: It all depends on what you're doing in your code. Based merely on the code you provided, yes, you're issuing a SELECT COUNT for each space. However, if in your controller you were to do something like:
var spaces = db.Spaces.Included("RegisteredStudents");

Then, the students are included in the query. When you later call Count it will merely do an in-memory count of the students. It's all in the context. After you deal with this stuff for some time, you can spot places where extra queries will get issued at a glance. In the meantime, I recommend installing some like Glimpse. It's 100% free and, among other awesome things, it will let you see every single query that's issued to render your page. If you see oddly high amounts of queries, then, that'll be your clue you're doing something inefficient, like issuing a count for each iteration in the loop.

A: i've taken a different approach. I'm keeping track of the count of registered users, by userid, inside a string (ex. "123,456,789") that is an entity property. Now I just have to get this column value with the rest of the columns from the SpaceEvent entity and split it on ',' to get each id. Originally I wanted to get each id so that I could loop through them in razor and create N slides for a bootstrap carousel. This approach seems to work great to save the N calls to the database for fetching each RegisteredStudent count(). I don't know if there is a better approach and this is a little more tedious when registering a student but it saves lots of db calls.


text:
Q: jQuery - Check if the tag's content is equal to sometext then do something Let's say I have many of these in my content div : <cite class="fn">blabla</cite>
How can I check every cite tag's content (in this case: blabla) with class fn to see if it equals to "sometext" then change it's color to red ?
Very simple.

A: $('cite.fn:contains(blabla)').css('color', 'red');

Edit: though that will match "blablablabla" as well.
$('cite.fn').each(function () {
    if ($(this).text() == 'blabla') {
        $(this).css('color', 'red');
    }
});

That should be more accurate.
Edit: Actually, I think bazmegakapa's solution is more elegant:
$('cite.fn').filter(function () {
    return $(this).text() == 'blabla';
}).css('color', 'red');;

A: You could potentially do something like:
$('cite.fn').each(function() {
  var el = $(this);
  if (el.text() === 'sometext') {
     el.css({ 'color' : 'red' });
  }
});

This fires a function against each cite that has the class fn. That function checks if the current cite's value is equal to 'sometext'.
If it is, then we change the CSS color (text-color) property to red.
Note I'm using jQuery in this example, as you've specifically tagged your question jQuery. Ignore the downvote, this was applied before I edited a typo that I'd made (el.val() rather than el.text())

A: You can make use of the amazing .filter() method. It can take a function as its parameter, which will reduce the jQuery collection's elements to those that pass its test (for which the function returns true). After that you can easily run commands on the remaining elements:
var searchText = 'blabla';

$('cite.fn').filter(function () {
    return $(this).text() === searchText;
}).css('color', 'red');

jsFiddle Demo

A: Without jQuery:
var elms = document.querySelectorAll("cite.fn"), l = elms.length, i;
for( i=0; i<l; i++) {
    if( (elms[i].innerText || elms[i].textContent) == "blabla") {
        elms[i].style.color = "red";
    }
}


text:
Q: How to properly parse json objects to array with Jackson? I would like to ask how to properly convert the next json string. I have this string:
{"response":{"meta":{"hits":1326,"time":55,"offset":0},"docs":[{"web_url":"http://www.nytimes.com/2016/04/05/fashion/china-luxury-goods-retail.html"},{"web_url":"http://www.nytimes.com/2016/04/05/fashion/luxury-goods-retail.html"},...
and I would like only the "docs" array. I am using Jackson Converter in this way:
    RestTemplate restTemplate=new RestTemplate();
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    jsonConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "json", MappingJackson2HttpMessageConverter.DEFAULT_CHARSET)));
    restTemplate.getMessageConverters().add(jsonConverter);
    ArrayList<WebUrl> topStories=restTemplate.getForObject(URL,Docs.class).getUrls();

and here is my Docs class:
@JsonIgnoreProperties(ignoreUnknown = true)

public class Docs {
  @JsonProperty("docs")
  private ArrayList<WebUrl> urls;

  public Docs(ArrayList<WebUrl> urls) {
     this.urls= urls;
  }

  public Docs(){

  }

  public ArrayList<WebUrl> getUrls() {
    return urls;
  }

  public void setUrls(ArrayList<WebUrl> urls) {
    this.urls=urls;
  }

 }

And here is my WebUrl.class
public class WebUrl {

@JsonProperty("web_url")
private String webUrl;

public WebUrl(){

}

public String getWebUrl() {
    return webUrl;
}

public void setWebUrl(String webUrl) {
    this.webUrl = webUrl;
}

public WebUrl(String webUrl) {

    this.webUrl = webUrl;
}
}

But it gives me null pointer exception on the array. How can I fix this?

A: You need to have classes Like below. as @cricket_007 mentioned you can not extract something out of middle.
Result.Java
import com.fasterxml.jackson.annotation.JsonProperty;

 public class Result {
    @JsonProperty("response")
    public Response response;
}

Response.Java
import com.fasterxml.jackson.annotation.JsonProperty;

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

public class Response {
    @JsonProperty("docs")
    public List<Doc> docs = new ArrayList<Doc>();
}

Doc.java
import com.fasterxml.jackson.annotation.JsonProperty;

public class Doc {
    @JsonProperty("web_url")
    public String webUrl;
}

Once you have these classes, you can call the service like below.
Result forObject = restTemplate.getForObject("yourURL", Result.class);

And then, from result you can extract the list of URLs.


text:
Q: can UNUserNotificationCenter add multiple requests? I can add one request. But when i tried to ad two, only the latest is fired. The first just doesn't appear. Here is my method :
            var triggerDailyEnd = DateComponents()
            triggerDailyEnd.hour = hour
            triggerDailyEnd.minute = minutes
            triggerDailyEnd.weekday = i+1
            // this repeat every day
            let triggerEnd = UNCalendarNotificationTrigger(dateMatching: triggerDailyEnd, repeats: true)

            let identifierEnd = getNotificationId(i+1, hour, minutes,true)
            let requestEnd = UNNotificationRequest(identifier: identifierEnd, content: notifEnd, trigger: triggerEnd)

            notificationCenter.add(requestEnd)

            var triggerDailyStart = DateComponents()
            triggerDailyStart.hour = hour
            // correctly remove time
            triggerDailyStart.minute = minutes-Int(ProgrammationViewController.PREHEAT_TIME)
            triggerDailyStart.weekday = i+1
            // this repeat every day
            let triggerStart = UNCalendarNotificationTrigger(dateMatching: triggerDailyStart, repeats: true)

            let identifierStart = getNotificationId(i+1, hour, minutes,false)
            let requestStart = UNNotificationRequest(identifier: identifierStart, content: notifStart, trigger: triggerStart)

            notificationCenter.add(requestStart)

the code is quite simple.When I add requestEnd after requestStart, the notification of requestEnd is fired and not requestStart.And vice versa. Strange ?

A: The identifier parameter to the request needs to be unique. If it's the same, the second request will overwrite the first.


text:
Q: docker-compose with explicit file option and exec problem I have some services defined in a custom docker-compose yaml file.
version: "3.7"

services:

 proxy:
    container_name: nginx
    hostname:       nginx
 …

 database:
   container_name: postgresql
   hostname:       PostgreSQL
 …

 backendservice:
   container_name: backendservice
   hostname:       backendservice
 …

 angular:
   container_name: angular
   hostname:       angular
 …

I can see the services running using docker-compose -f docker-compose.dev.yaml ps
when I try docker-compose -f docker-compose.dev.yaml exec <service name> bash or docker-compose -f docker-compose.dev.yaml backendservice bash I get,
ERROR: No such service: backendservice
What is the correct way to call ?


text:
Q: Probability of future success when trials are dependent: In 4 draws w/o replacement, what is the probability that draws 3 & 4 will be successful? Suppose that I have a bag with 14 marbles, 9 green and 5 red.
 Person A will first draw 2 marbles and then Person B will draw 2 marbles. Can I determine the probability that person B will draw 2 green marbles before I let person A draw?

Edit: The order of events are:

*

*Determine the probability that Person B will draw 2 green marbles.

*Person A draws 2 marbles (unknown color)

*Person B draws 2 marbles

I understand that using hypergeometric probability I can easily find the probability that person A will draw 2 green marbles
$$\frac{\binom{K}{k}\binom{N-K}{n-k}}{\binom{N}{n}}.$$
K = 9 ; k = 2 ; N = 14 ; n = 2
however if I only care about person B drawing 2 green marbles, it seems to me that now n = 4 but k could be k = 2, k = 3, or k = 4 but it doesn't matter so long as the last 2 instances of n yield k=2.
Am I thinking about this in the right way? Any help is appreciated

A: Consider that there are $9$ green marbles and $5$ red marbles in the beginning. We split cases:
Case 1: $A$ draws $2$ green marbles.
The probability of this case is
$\binom92/\binom{14}2=\frac{36}{91}$.
After $A$ draws, there would remain $7$ green marbles, $12$ marbles in total.
The probability of $B$ drawing $2$ green marbles after that is
$\binom72/\binom{12}2=\frac{21}{66}$.
So, the probability of $B$ drawing $2$ green marbles through this case is
$$\frac{36}{91}\cdot\frac{21}{66}\text.$$
Case 2: $A$ draws $1$ green marble and $1$ red marble.
The probability of this case is
$\binom91\binom51/\binom{14}2=\frac{45}{91}$.
After $A$ draws, there would remain $8$ green marbles, $12$ marbles in total.
The probability of $B$ drawing $2$ green marbles after that is
$\binom82/\binom{12}2=\frac{28}{66}$.
So, the probability of $B$ drawing $2$ green marbles through this case is
$$\frac{45}{91}\cdot\frac{28}{66}\text.$$
Case 3: $A$ draws $2$ red marbles.
The probability of this case is
$\binom52/\binom{14}2=\frac{10}{91}$.
After $A$ draws, there would remain $9$ green marbles, $12$ marbles in total.
The probability of $B$ drawing $2$ green marbles after that is
$\binom92/\binom{12}2=\frac{36}{66}$.
So, the probability of $B$ drawing $2$ green marbles through this case is
$$\frac{10}{91}\cdot\frac{36}{66}\text.$$
Total probability
So, across all cases, the probability is
$$\begin{align}
&\left(\frac{36}{91}\cdot\frac{21}{66}
+\frac{45}{91}\cdot\frac{28}{66}
+\frac{10}{91}\cdot\frac{36}{66}\right)\\
=&\frac{36\cdot21+45\cdot28+10\cdot36}{91\cdot66}\\
=&\frac{756+1260+360}{6006}\\
=&\frac{2376}{6006}\\
=&\frac{36}{91}\text.
\end{align}$$