text:
Q: Effect of Paint delayed by up to 500ms I have a Java program which displays time in deciseconds. Each digit is a separate Component, the Components are grouped in a JPanel which is located near a corner of a JFrame which occupies most of the screen. The digits are updated by a dedicated Thread which loops with a 100ms wait(). When a digit changes it is repainted.
The scheduling appears to be working: repaint() and paint() are called appropriately at 100ms intervals but the display is only updated every 500ms.
However, if I move the mouse over the JFrame, or repeatedly press a key (control and shift both work) then the display updates faster.
If I repaint the content pane of the JFrame every 100ms then the display updates correctly, but everything else in the JFrame is repainted unnecessarily. Repainting the portion of the JFrame that contains the time display has no apparent effect, but repainting a large area of the JFrame which does not include the time display does update the time.
I have tried basing the digits on a JComponent and calling paintImmediately() (from the event dispatch thread) with no apparent difference.
An explanation might be that the EDT waits with a 500ms timeout and is not being notified by paint(). Is there a way that I can explicitly notify the EDT to test this?
I could probably work around this by displaying the time in a separate heavyweight container, but I would like to understand what is causing this behaviour.
Here is a short program that produces this behaviour.
With version 1.7 the line always rotates smoothly. With version 1.8 it moves smoothly at first but within two seconds it starts to jump. Note that the angle is incremented in the paint procedure, so if paints were being combined the line would still rotate smoothly but more slowly.
I don't believe that it is necessary to call repaint from the EDT, but I have tried it and it makes no difference. The for loop does not run in the EDT, so the sleep is not blocking display updates.
    package bugs;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class DisplayRefresh {
    private class Cmpt extends Component {
        private static final int    POINTS = 16;
        int     m_ix;

        public Cmpt()
        {
            m_ix = 0;
        }

        public void paint(Graphics g)
        {
            Dimension sz = getSize();
            int rx = (sz.width - 1) / 2;
            int ry = (sz.height - 1) / 2;
            Double w = Math.PI * m_ix / POINTS;
            int x = (int)Math.floor(Math.sin(w) * rx);
            int y = (int)Math.floor(Math.cos(w) * ry);
            g.drawLine(rx - x, ry - y, rx + x, ry + y);
            m_ix = (m_ix + 1) % POINTS;
        }
    }

    JFrame      m_frame;
    Cmpt        m_cmpt;

    public static void main(String[] args) {
        (new DisplayRefresh()).exec();
    }

    private void exec()
    {
        m_frame = new JFrame();
        m_frame.setLayout(null);
        m_frame.setSize(600, 600);
        m_frame.setVisible(true);
        m_cmpt = new Cmpt();
        m_cmpt.setSize(64, 64);
        m_frame.add(m_cmpt);
        m_cmpt.setLocation(500, 100);
        if (SwingUtilities.isEventDispatchThread()) {
            System.out.println("This is the event dispatch thread");
        } else {
            System.out.println("This is NOT the event dispatch thread");
        }
        for (int i = 0; i < 100; i++) {
            m_cmpt.repaint(10);
            try {
                Thread.sleep(100);
            } catch(InterruptedException exc) {
                System.out.println(exc.toString());
            }
        }
        m_frame.dispose();
        System.exit(0);
    }
}

A: I have just recompiled using Java 1.7.0_80 instead of 1.8.0_92 and the display is now updated promptly, the answer to the question "what is causing this behaviour?" is that it is a peculiarity of that version of java.
I have now tried version 1.8.0_111. This has the same refresh delay as 1.8.0_92.


text:
Q: MYSQL + Update ID Column I have a table that looks like this
CREATE TABLE IF NOT EXISTS `language` (
   `idkey` int(10) unsigned NOT NULL AUTO_INCREMENT,
   `english_lang` text,
   `japanese_lang` text,
   PRIMARY KEY (`idkey`),
 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1587 ;

The 'idkey' is just a number that starts at 1 and increments.
The 'idkey' currently has gaps in the numbering from entries I've removed and I wanted to see if it was possible to run a MySQL command to re-write this column so there are no gaps in the numbering.
eg: rewrite it so it starts at 1 and runnings till the end (around 1400 entries).
thanks

A: It is against standard practices to try to fill in these "missing numbers". You need to consider that they were once assigned to something. Assigning them now to something else could potentially lead to problems--especially if you're not using foreign key constraints and have some bad data sitting around.
If you are in a situation where you tested some data and now want to take things live, you can reset the auto-increment by running Alter Table TABLENAME AUTO_INCREMENT=1 (or any other number) or you can drop and recreate the table. If it has been in production I would recommend against resetting or trying to "fill in the gaps".
In the interest of completeness I believe you can insert a specific number in a normally auto incrementing column by including it in your insert statement. The next auto increment number should pick up from the one you specified. If it's already taken this will cause you problems.
If you really just want to close up gaps the easiest way is to create a new table with the same structure. Then run a query like:
INSERT INTO
    newtable (column2, column3, column4,...)
VALUES
    SELECT column2, column3, column4,... FROM oldtable;

The drop the old table and rename the new table. The gaps will be filled in and your auto increment number will be at the "correct" place.
BUT REALLY YOU SHOULD LEAVE GAPS FROM DELETED RECORDS IN PLACE.

A: Yes you can do it beacuse primary key is single for each row and one thing more if your column is auto increment then you can't do this, manually you can do it. But you are asking about row entery but syntax is related to create table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Way to initialize variable by passing into a class Actually, I want to pass a Variable type and Id into a class to initialize the variable.
Like, Button myButton=new MyClass(Button, myButtonId);
Here Button is variable type, and myButtonId is a id from xml.
And the class (method) will return something like that (Button)findViewById(R.id.myButtonId);
For this  I wrote
Button myButton=new MyClass(Button, myButtonId);
And Android Studio Suggest me
private class MyClass extends Button {
        public MyClass(Object p, Button myButtonId) {
            super();
        }
    }

There is an error at super(); line.
I have no idea to do more.
Any suggestion?

A: You need to put at least one (context) parameter in the super function
Please check the public constructors for the Button class here:
Button public constructors
UPDATE
You need to pass an context to your class which is extending Button, something like this:
MyClass myButton = new MyClass(getApplicationContext());
And then in your MyClass:
public class MyClass extends Button {
    public MyClass(Context context) {
        super(context);
    }
}


text:
Q: How to create an std::function from a move-capturing lambda expression? I'm trying to create an std::function from a move-capturing lambda expression. Note that I can create a move-capturing lambda expression without problems; it's only when I try to wrap it in an std::function that I get an error.
For example:
auto pi = std::make_unique<int>(0);

// no problems here!
auto foo = [q = std::move(pi)] {
    *q = 5;
    std::cout << *q << std::endl;
};

// All of the attempts below yield:
// "Call to implicitly-deleted copy constructor of '<lambda...."

std::function<void()> bar = foo;
std::function<void()> bar{foo};
std::function<void()> bar{std::move(foo)};
std::function<void()> bar = std::move(foo);
std::function<void()> bar{std::forward<std::function<void()>>(foo)};
std::function<void()> bar = std::forward<std::function<void()>>(foo);

I'll explain why I want to write something like this. I've written a UI library which, similar to jQuery or JavaFX, allows the user to handle mouse/keyboard events by passing std::functions to methods with names like on_mouse_down(), on_mouse_drag(), push_undo_action(), etc.
Obviously, the std::function I want to pass in should ideally use a move-capturing lambda expression, otherwise I need to resort to the ugly "release/acquire-in-lambda" idiom I was using when C++11 was the standard:
std::function<void()> baz = [q = pi.release()] {
    std::unique_ptr<int> p{q};
    *p = 5;
    std::cout << *q << std::endl;
};

Note that calling baz twice would be an error in the above code. However, in my code, this closure is guaranteed to be called exactly once.
BTW, in my real code, I'm not passing an std::unique_ptr<int>, but something more interesting.
Finally, I'm using Xcode6-Beta4 which uses the following version of clang:
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix

A: Here's a simpler solution:
   auto pi = std::make_unique<int>(0);

   auto ppi = std::make_shared<std::unique_ptr<int>>(std::move(pi));

   std::function<void()> bar = [ppi] {
        **ppi = 5;
        std::cout << **ppi << std::endl;
   };

Live example here

A:
template<class F> function(F f);
template <class F, class A> function(allocator_arg_t, const A& a, F f);
Requires: F shall be CopyConstructible. f shall be Callable for argument types ArgTypes and return type R. The copy constructor and destructor of A shall not throw exceptions.
§20.9.11.2.1 [func.wrap.func.con]

Note that operator = is defined in terms of this constructor and swap, so the same restrictions apply:

template<class F> function& operator=(F&& f);
Effects: function(std::forward<F>(f)).swap(*this);
§20.9.11.2.1 [func.wrap.func.con]

So to answer your question: Yes, it is possible to construct a std::function from a move-capturing lambda (since this only specifies how the lambda captures), but it is not possible to construct a std::function from a move-only type (e.g. a move-capturing lambda which move-captures something that is not copy constructible).

A: As std::function<?> has to type-erase the copy constructor of the stored invocable object, you cannot construct it from a move-only type.  Your lambda, because it captures a move-only type by value, is a move-only type.  So... you cannot solve your problem.  std::function cannot store your lambda.
At least not directly.
This is C++, we simply route around the problem.
template<class F>
struct shared_function {
  std::shared_ptr<F> f;
  shared_function() = delete; // = default works, but I don't use it
  shared_function(F&& f_):f(std::make_shared<F>(std::move(f_))){}
  shared_function(shared_function const&)=default;
  shared_function(shared_function&&)=default;
  shared_function& operator=(shared_function const&)=default;
  shared_function& operator=(shared_function&&)=default;
  template<class...As>
  auto operator()(As&&...as) const {
    return (*f)(std::forward<As>(as)...);
  }
};
template<class F>
shared_function< std::decay_t<F> > make_shared_function( F&& f ) {
  return { std::forward<F>(f) };
}

now that the above is done, we can solve your problem.
auto pi = std::make_unique<int>(0);

auto foo = [q = std::move(pi)] {
  *q = 5;
  std::cout << *q << std::endl;
};

std::function< void() > test = make_shared_function( std::move(foo) );
test(); // prints 5

The semantics of a shared_function is slightly different than other functions, as a copy of it shares the same state (including when turned into a std::function) as the original.
We can also write a move-only fire-once function:
template<class Sig>
struct fire_once;

template<class T>
struct emplace_as {};

template<class R, class...Args>
struct fire_once<R(Args...)> {
  // can be default ctored and moved:
  fire_once() = default;
  fire_once(fire_once&&)=default;
  fire_once& operator=(fire_once&&)=default;

  // implicitly create from a type that can be compatibly invoked
  // and isn't a fire_once itself
  template<class F,
    std::enable_if_t<!std::is_same<std::decay_t<F>, fire_once>{}, int> =0,
    std::enable_if_t<
      std::is_convertible<std::result_of_t<std::decay_t<F>&(Args...)>, R>{}
      || std::is_same<R, void>{},
      int
    > =0
  >
  fire_once( F&& f ):
    fire_once( emplace_as<std::decay_t<F>>{}, std::forward<F>(f) )
  {}
  // emplacement construct using the emplace_as tag type:
  template<class F, class...FArgs>
  fire_once( emplace_as<F>, FArgs&&...fargs ) {
    rebind<F>(std::forward<FArgs>(fargs)...);
  }
  // invoke in the case where R is not void:
  template<class R2=R,
    std::enable_if_t<!std::is_same<R2, void>{}, int> = 0
  >
  R2 operator()(Args...args)&&{
    try {
      R2 ret = invoke( ptr.get(), std::forward<Args>(args)... );
      clear();
      return ret;
    } catch(...) {
      clear();
      throw;
    }
  }
  // invoke in the case where R is void:
  template<class R2=R,
    std::enable_if_t<std::is_same<R2, void>{}, int> = 0
  >
  R2 operator()(Args...args)&&{
    try {
      invoke( ptr.get(), std::forward<Args>(args)... );
      clear();
    } catch(...) {
      clear();
      throw;
    }
  }

  // empty the fire_once:
  void clear() {
    invoke = nullptr;
    ptr.reset();
  }

  // test if it is non-empty:
  explicit operator bool()const{return (bool)ptr;}

  // change what the fire_once contains:
  template<class F, class...FArgs>
  void rebind( FArgs&&... fargs ) {
    clear();
    auto pf = std::make_unique<F>(std::forward<FArgs>(fargs)...);
    invoke = +[](void* pf, Args...args)->R {
      return (*(F*)pf)(std::forward<Args>(args)...);
    };
    ptr = {
      pf.release(),
      [](void* pf){
        delete (F*)(pf);
      }
    };
  }
private:
  // storage.  A unique pointer with deleter
  // and an invoker function pointer:
  std::unique_ptr<void, void(*)(void*)> ptr{nullptr, +[](void*){}};
  void(*invoke)(void*, Args...) = nullptr;
};

which supports even non-movable types via the emplace_as<T> tag.
live example.
Note you have to evaluate () in an rvalue context (ie, after a std::move), as a silent destructive () seemed rude.
This implementation does not use SBO, for if it did it would demand that the type stored be movable, and it would be more work (for me) to boot.


text:
Q: Making a dynamic navigation menu using div class "active" and Javascript I want to create a dynamic navigation bar (using two div class filters: status private/public/etc.. and type of data audio/video/etc..).
For now, menu doesn't update according to the active filter item. I just need a JS script that selects in one of the filters the div class "active" and show the id in the other filter. For my example below, I want the prefix "audio" added to the data-filter value instead of "all", and prefix "private" added to the data-filter value instead of "all".
Thus, according to the div class "active", values in the first filter should be:
data-filter=".audioall"
data-filter=".audioprivate"
data-filter=".audiopublic"
data-filter=".audiodeleted"

and, in the second filter, should be:
data-filter=".allprivate"
data-filter=".audioprivate"
data-filter=".videoprivate"
data-filter=".photoprivate"
data-filter=".newsprivate"
data-filter=".blogprivate"
data-filter=".mailprivate"
data-filter=".socialprivate"

My current code:

all
 /

private
 /

public
 /

deleted

all
 /

audio
 /

video
 /

photo
 /

news
 /

blog
 /

mail
 /

social

Here my JS cript regarding brickwall and filters, but it doesn't concern the dynamic data-filter labels..

I hope I made myself clear enough. I can specify my question if needed.


text:
Q: The "Order and Export" tab in "Java Build Path"
What's the use of "Order and Export" tab in "Java Build Path" dialog box?
By the name 'order', I can guess that JRE System library is searched before Plug-in Dependencies, but why do we have 'Export' in Build Path ? And what's it for the button left side of the elements?
ADDED
It's the example that I borrowed from Eclipse distilled.
The orderes.webapp depends on orders, but it's likely to use the classes defined in ubl and catalog.

In such a case, orders can export catalog and ubl so that the packages that depends on it can use catalog and ubl.

And something more about "Order and Export".

*

*The check of the left side button modifies the .classpath file to add exported=true such as <classpathentry exported="true" kind="lib" path="lib/log4j-1.2.7.jar"/>.

*The src is always checked, and you can't uncheck it.

References

*

*Interpreting eclipse .classpath file. What does 'kind="con"' and 'exported="true"' mean?

*Configuring an Eclipse Java Project

*Java Build Path

A: This tab seems to pull double duty (see bottom of this help page for small amount of detail).
On one hand, it functions as the order of resolution for resources used in the building of the project in question (the "Order" part).  On the other, it also serves to define what parts of this build path are contributed to dependent projects' (those listing this project in the "projects" tab for their view of this preference panel) build paths (the "Export" part).
This latter function is why the checkboxes exist on the left hand side, as you ask (note that the '-' signs cannot be unchecked, as source files defined in this project cannot be deselected, as stated in help file).  A dependent project that expects some resource from the contributing project will not compile/run if the contributing project doesn't export that resource.
EDIT:  see this SO post for corroboration.

A: a very good example from  Coderanch  by Ilja Preuss

Say you have junit.jar in the build path of project A. Project B
  depends on project A.
Now you write a junit test in project B. If project A exports
  junit.jar, project B can use it at compile time - no more action
  necessary. If A doesn't export it, B doesn't know about it - you will
  have to explicitely put it into its build path, too.

A: Order and Export tab as your rightly guessed shows the order of libraries which will be included in your project build path.
Using the buttons up and down you can adjust your libraries order according to your project needs.

A: To answer your specific question, if this project were to be added as a dependency for another Java project, the order would be used to resolve classes and packages in this project when running the other project.  Those classes and packages are said to be exported to/for the other running project's class path.

A: There is one case where-in I found this useful. I had to use a sun.* class of an IBM jar. This class was also present in local jre, but my requirement was to use IBM's class. But by default,the compiler would refer the local jdk class only.
In the eclipse order and export tab, I moved the external jar ahead of the JRE lib. Now, the compiler would refer to the class from IBM jar instead of local JRE.


text:
Q: React-routes express-server I'm learning to work with the rect, when I try to follow the link, I get such errors:

My client.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import App from '../components/first_page/App';
import {Router, Route } from 'react-router';
import { browserHistory } from 'react-router';

class Main extends Component {
    render(){
        return (
          <Router>
            <Route history = {browserHistory}>
                <Route path="/f" component={App}/>
            </Route>
        </Router>
        );
    }
}
render (<Main />, window.document.getElementById('app'))

App.js
import React, { Component } from 'react';
import Bootstrap from 'bootstrap/dist/css/bootstrap.css';
import { Button } from 'react-bootstrap';
class App extends Component{
  render(){
      return (
        <div>
         <Button>Start!</Button>
          <Button>Login!</Button>
        </div>
      );
  }
}
export default App

Server
  var express = require('express');
var path = require('path');
var config = require('../webpack.config.js');
var webpack = require('webpack');

var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');

var app = express()
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));
app.use(webpackHotMiddleware(compiler));

app.use(express.static(path.resolve(__dirname, './dist')));

app.use('/', function (req, res) {
    res.sendFile(path.resolve('client/index.html'));
});
var port = process.env.PORT || 4000;

app.listen(port, function(error) {
  if (error) throw error;
  console.log("Express server listening on port", port);
});

I tried to pass different tutorials, but always these mistakes are obtained, I will be happy with any help, thanks


text:
Q: Visual Studio 2010 crashes Visual Studio 2010 stops working every time I am creating or adding a new project and crashes with "Microsoft Visual Studio 2010 has stopped working".
On details I get the following errors: "
Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: devenv.exe
  Application Version:  10.0.40219.1
  Application Timestamp:    4d5f2a73
  Fault Module Name:    clr.dll
  Fault Module Version: 4.6.1087.0
  Fault Module Timestamp:   583e5b8e
  Exception Code:   c0000005
  Exception Offset: 000030d0
  OS Version:   6.3.9600.2.0.0.272.7
  Locale ID:    1033
  Additional Information 1: 0e72
  Additional Information 2: 0e720e4bb45f9178e5a9d38daa53fc02
  Additional Information 3: f679
  Additional Information 4: f679a242f56e8d70edce702dbd5ef2ed

A: Try running Visual Studio 2010 in safe mode.
To do this, please take a look at this post: how to run visual studio without plugin and all third party feature


text:
Q: Choropleth Africa map doesn't show some countries and islands I'm plotting an African continent map using choropleth. However, some regions are not appearing on the map, even the respective alpha codes being correct. For example, I have data from Seychelles (sov_a3="SYC"), Mauritius (sov_a3="MUS"), and the map is missing these regions or is not filled.
There is something I'm missing? I didn't see a complete Africa map made with Plotly and I'm wondering if there is some issue with the parameter scope="africa"
Follow below the code for the map and how it looks now.
fig_map = go.Figure(px.choropleth(df_map,
                            locations='sov_a3', color=map_count_column,
                            hover_name='country', animation_frame="date_2weeks",
                            color_continuous_scale="algae",
                            range_color=[0, max(df_map['cum_counts'])],
                            labels={'cum_counts': 'Number of genomes'}
                            ))
    fig_map.update_layout(geo_scope="africa")

A: *

*it's all down to geometry / geojson.  See documentation https://plotly.com/python/map-configuration/#physical-base-maps. Natural earth is used,  which does not define these islands as part of Africa

*have simulated a data frame for your code.  To create MWE

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np

countries = 'TZA,ESH,COD,SOM,KEN,SDN,TCD,ZAF,LSO,ZWE,BWA,NAM,SEN,MLI,MRT,BEN,NER,NGA,CMR,TGO,GHA,CIV,GIN,GNB,LBR,SLE,BFA,CAF,COG,GAB,GNQ,ZMB,MWI,MOZ,SWZ,AGO,BDI,MDG,GMB,TUN,DZA,ERI,MAR,EGY,LBY,ETH,DJI,UGA,RWA,SSD'
names = "Tanzania,W. Sahara,Dem. Rep. Congo,Somalia,Kenya,Sudan,Chad,South Africa,Lesotho,Zimbabwe,Botswana,Namibia,Senegal,Mali,Mauritania,Benin,Niger,Nigeria,Cameroon,Togo,Ghana,Côte d'Ivoire,Guinea,Guinea-Bissau,Liberia,Sierra Leone,Burkina Faso,Central African Rep.,Congo,Gabon,Eq. Guinea,Zambia,Malawi,Mozambique,eSwatini,Angola,Burundi,Madagascar,Gambia,Tunisia,Algeria,Eritrea,Morocco,Egypt,Libya,Ethiopia,Djibouti,Uganda,Rwanda,S. Sudan"
# Seychelles (sov_a3="SYC"), Mauritius (sov_a3="MUS")
countries += ",SYC,MUS"
names += ",Seychelles,Mauritius"
map_count_column = "cum_counts"

# simulate implied dataframe in question
df_map = (
    pd.DataFrame({"sov_a3": countries.split(","),"country":names.split(",")})
    .merge(pd.DataFrame({"date_2weeks": list("ABC")}), how="cross")
    .assign(
        cum_counts=lambda d: np.random.randint(1, 5, len(d)),
    )
)

# go.Figure is spurious remove
fig_map = px.choropleth(
    df_map,
    locations="sov_a3",
    color=map_count_column,
    hover_name="country",
    animation_frame="date_2weeks",
    color_continuous_scale="algae",
    range_color=[0, max(df_map["cum_counts"])],
    labels={"cum_counts": "Number of genomes"},
)
fig_map.update_layout(geo_scope="africa")

*

*now I use a different geojson where the islands are defined.  However this is imperfect as I have not ensured names map correctly to geojson

*this does show Mauritius

import requests
res = requests.get("https://raw.githubusercontent.com/codeforgermany/click_that_hood/main/public/data/africa.geojson")

# use out own geometry
fig_map = px.choropleth(
    df_map,
    geojson=res.json(),
    locations="country",
    featureidkey="properties.name",
    color=map_count_column,
    hover_name="country",
    animation_frame="date_2weeks",
    color_continuous_scale="algae",
    range_color=[0, max(df_map["cum_counts"])],
    labels={"cum_counts": "Number of genomes"},
)

fig_map.update_geos(fitbounds="locations")


text:
Q: Trouble with complex multi-line regular expression I am trying to parse large log in python using complex regular expression.
The sequence I am looking for is on multiple consecutive lines and can have positive or negative outcome. Here is the regex with test data:
Here is my problem: https://regex101.com/r/pF3eM6/1
The regex does what it should, pulling Start and end date, source and target format, job ID and completion time or "Time out". However when the sequence is not complete (like end of file), the expression ends up in error (try to delete the last line). I would like the expression simply ignore such sequence (no match).
And for completeness, here the same regex with "Time Out" variant of the log file - and the same problem as above.
https://regex101.com/r/pF3eM6/2
Can someone help me understand what and why is happening?

A: Had to rewrite it completely, I read the articles at http://regular-expressions.info and I finally understand how regex does work :)
For posterity, here is the commented solution:
https://regex101.com/r/pF3eM6/8


text:
Q: Backbone.js with Rails - handling duplicated logic in models I have several years of Rails development and few days Backbone.js experience. After these few days, I think I came into the flavor of Backbone.js. I was wondering about the kind of duplication which appears developing Backbone.js rich client scripts with Rails on the back. Lot of the models gets partly reimplemented on the Backbone side (model structure and validations).
Do you know tool, gem which would handle this duplication? Or generally does it make sense to tackle this?
Sorry for a potential speculative question. I am wondering whether someone tried to tackle question of Rails/Backbone model duplication.

A: You don't have to create a duplicate model architecture for Backbone, although that is usually the simplest way to go.  (There are js extensions to backbone that add has_many and whatnot, if you are going that route: https://github.com/dbrady/ligament.js, and https://github.com/PaulUithol/Backbone-relational)
DISCLAIMER: Don't do the following, it sucks.
But you can pass whatever JSON to backbone that you like, and call that a "model", and make a separate controller to handle saving whatever you put in there.  That can be much more messy, but more succinct if you want to send a glob of JSON to backbone and keep it in one model.
Example:
# controller
def index
  @json = User.first.to_json(:include => {:address => {}, :contacts => {})
end

Send that JSON to backbone, and you have an object with nested relations, although it's virtually meaningless to Backbone without some way to maintain relations, so you'd have to extract the bits you want to deal with in JavaScript, put them back together, and make your create/update actions in Rails quite fancy to handle that...
But the point is that you can arbitrarily create whatever type of JSON object you want--because Backbone knows nothing about what Rails will do with it.  Backbone just gets a URL to manage its HTTP requests, and trusts that the server is set up to handle whatever it throws at it.  So, feel free to send and receive exactly the type of JSON objects you want--just be aware that you're going to have to figure out how to deal with them in Rails if they cross models.
Really, it's much cleaner just to tough it out and duplicate a lot of the model architecture in Backbone, unfortunately.
I think the most magical Backbone thing I've seen so far is those js-association-making libraries listed above.  Backbone is still fairly clunky.
There is a gem called 'backbone-rails' or 'rails-backbone' (there was a weird project conflict that made it nebulous) by "codebrew" https://github.com/codebrew/backbone-rails, that will generate some nice coffeescript for you to work with.  It's probably the easiest way to go, but not as succinct as you might like, since it is a code generator.
If anyone can illuminate more about this, or completely refute me, please do!  I'm in the middle of my Backbone knowledge as well.
P.S. You might not want to rely on Backbone to do validations... : )  Easily hackable.  If you're adding them in JS to reduce on the number of bad submits, then you're just going to have to live with duplicating the validations.


text:
Q: How to set a default return value if a row doesn't exist Say I have two tables:

Users - UserID, UserName
Actions - UserID

The database doesn't have referential integrity, and so If a user has been deleted, the Actions table can still contain the User ID.
I am running a query like:
SELECT DISTINCT UserName FROM USERS u WHERE u.UserId IN (SELECT DISTINCT UserID FROM Actions)
what I want is to be able to adjust the query to say "but, if the user ID doesn't exist in the users table, default to --- instead".
If there was just one value I was searching for, I could do it with a UNION SELECT '---' FROM DUAL WHERE NOT EXISTS (value), but if I try that here they would have to all be missing in order for it to work.
How can I change the query to get the results I want?

A: I think this is what you're looking for and what you want can be achieved with table aliases:
SELECT DISTINCT U.USERNAME
  FROM USERS U
 WHERE U.USERID IN (SELECT DISTINCT USERID
                      FROM ACTIONS)
 UNION
SELECT '---'
  FROM ACTIONS A
 WHERE NOT EXISTS (SELECT 1
                     FROM USERS
                    WHERE USERID = A.USERID);

A: If you are trying to display a default value when no users/actions are matched then, from Oracle 12, you can use:
SELECT username
FROM   (
  SELECT DISTINCT
         1 AS priority,
         UserName
  FROM   USERS
  WHERE  UserId IN (SELECT DISTINCT UserID FROM Actions)
  UNION ALL
  SELECT 2, '---' FROM DUAL
  ORDER BY Priority
  FETCH FIRST ROW WITH TIES
);

In earlier versions, you can use:
SELECT username
FROM   (
  SELECT username,
         RANK() OVER (ORDER BY priority) AS rnk
  FROM   (
    SELECT DISTINCT
           1 AS priority,
           UserName
    FROM   USERS
    WHERE  UserId IN (SELECT DISTINCT UserID FROM Actions)
    UNION ALL
    SELECT 2, '---' FROM DUAL
  )
)
WHERE  rnk = 1;

If you are just trying to JOIN the two tables and fill in the blanks then:
SELECT DISTINCT
       COALESCE(u.username, '---') AS username
FROM   actions a
       LEFT OUTER JOIN users u
       ON (a.userid = u.userid)


text:
Q: C# Loop inside a loop : Index was outside the bounds of the array I am getting the error "Index was outside the bounds of the array."
This is what I want to have :

*

*check if the log line contain "ERROR" then check if the bottom line
contain " at "

*if true check if the bottom line contain " at "

*While the state is true increment the string variable called checkDescr with the line

*do this again and again  until the state is false.

Here is my code :
foreach (string log in logs)
{
    if (log.Contains("ERROR"))
    {

        nextLine = index + 1;
        descriptionLine = index + 2;

        string checkDescr = "";
        int descNb = descriptionLine + 1;
        checkDescr = logs[descNb];

        if (checkDescr.Contains(" at "))
        {

            while (logs[descNb].Contains(" at "))
            {
                descNb++;
                checkDescr = checkDescr + logs[descNb];

            }

        }
    }
}

A: Just replace:
while (logs[descNb].Contains(" at "))

... by:
while ((logs.Length < descNb) && (logs[descNb].Contains(" at ")))

Keep out: there's a catch: in case logs.Length == descNb, then logs[descNb] generates the IndexOutOfRangeException, but the C# compiler stops the while-condition when the first condition is not met. In case you're dealing with an older compiler, you might still encounter a problem (but it's very unlikely).


text:
Q: Passport local temporary password (change on first login) For security reasons we create users and send them a temporary generated password. At their first login the user should change it's password before continuing navigating protected pages.
I'm using an express/node website running a passport-local module. Registering, login in users all work. But I'm kind of lost on best practices for users to change their password on the first login.
My idea was to do the following :
/* POST login page. */
router.post('/login', function(req, res, next) {
  passport.authenticate('local', { successRedirect: '/dashboard/users',
    failureRedirect: 'pages/login'}, function(err, user, info) {
    if(err) {
      console.log('')
      return res.render('pages/login', {title: 'Login', error: err.message});
    }

    if(!user) {
      return res.render('pages/login', {title: 'Login', error: info.message});
    }
    return req.logIn(user, function(err) {
      if(err) {
        return res.render('pages/login', {title: 'Login', error: err.message});
      } else if (user.firstLogin) {
        return res.redirect('/change-password'); // <- First login
      } else {
        return res.redirect('/dashboard/users');
      }
    });
  })(req, res, next);
});

As you can see I have a simple boolean (tinyInt 0-1) set in my database (defaults to 1). Afterwards I'll set a post method which after a successful change, the boolean would be set to 0.
Is this a correct way ('a' not 'the' :p )? How about the security?

A: It definitely is a correct way. I'd say it perfectly suits your needs. I personally like how the usage of your database field directly reflects the business logic behind it.
Alternatives, though I'm fan of your solution, could be:
1
Adding a lastLogin date field to your database which defaults to NULL. This would store a datetime stamp whenever the user logs on. You could use it as an implicit check if the user has ever logged on before. I personally prefer having explicit columns for their purposes (like you're doing with your firstLogin column) because the purpose of the column and business logic of the application is very clear from it.
2
Another alternative would be to store when a user has last updated his password i.e. lastPasswordChange defaulting to NULL for new users. Same reasoning as above. Could be useful if you'd want your users to change their passwords every n days.
Security speaking I'd say this'd be solid. As long as your firstLogin field defaults to 1 then there'd be no way a new user could skip the password change upon first login.
However, when a user updates his password, be sure to either update the firstLogin field in the same query or perform both queries inside a transaction. This way you'll always be sure both the password and the firstLogin field are changed. If for some reason either query would fail you'd have a user who already changed their password and is asked/forced to change it again or a user who has a randomly generated password without being asked to change it.
Doing it inside the same query would make sure both, or neither are updated at the same time. Doing it inside a transaction leaves you with the option to fail/rollback the transaction when either query fails.
On another note, your code could be written like this (both your way and this is correct, it's just a matter of preference and visual):
/* POST login page. */
router.post('/login', function(req, res, next) {
    passport.authenticate('local', {
        successRedirect: '/dashboard/users',
        failureRedirect: 'pages/login'
    }, function(err, user, info) {
        if(err) {
            console.log('')
            return res.render('pages/login', {title: 'Login', error: err.message});
        }

        if(!user) {
            return res.render('pages/login', {title: 'Login', error: info.message});
        }
        return req.logIn(user, function(err) {
            if(err) {
                return res.render('pages/login', {title: 'Login', error: err.message});
            }

            // Using if/else if/else makes no difference since if the first if is executed
            // in both cases nothing else will execute due to if/else or the return.
            // In case the above statement resolves to `false` the effect wills till be the same

            if (user.firstLogin) {
                return res.redirect('/change-password'); // <- First login
            }
            // The else is not necessary due to the return in the line above.
            return res.redirect('/dashboard/users');
        });
    })(req, res, next);
});

If you'd like a more specific answer to either question, I'd need a more specific question.

A: It's probably a good thing to move the "check first time login" logic into a separate middleware which executes for all "logged in routes".
With your suggestion above the user can simply navigate away from /change-password after redirection?


text:
Q: Difference between Native debugging and managed debugging? Im looking to try and set up remote debugging for a VB project in Visual Studio 2010. On the MSDN page it mentions both Native debugging and managed debugging (http://msdn.microsoft.com/en-us/library/vstudio/bt727f1t(v=vs.100).aspx), but I dont know what they mean. Can someone enlighten me?
Thanks

A: Managed is for .NET languages like C# and VB.NET.
Native is for compiled-to-machine-code languages like C and C++.


text:
Q: Security of GET vs. POST when using Ajax I used ajax to send the data. I was successful in implementing it using two different approaches:
1) Using method 'POST' and sending data in send() method by setting requestheader.
var xmlHttp = getXMLHttpRequest();
var url="login.do";
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4) {
            // Done. Do nothing.
        }
    }
xmlHttp.send("userName=xyz&password=abc");

2) Using method "POST" and appending parameter values in the URL as:
var xmlHttp = getXMLHttpRequest();
var url="login.do?userName=xyz&password=abc";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4) {
            // Done. Do nothing.
        }
    }
xmlHttp.send();

Since this is an ajax call, URL will not be visible in the browser window, so I wanted to know which approach is better and why?
Thanks in advance

A: Putting data into the URL's query parameters doesn't make it a GET request. A POST request is a POST request; the difference is between sending data in the URL or sending it as POST body. There's no fundamental difference between both in this case, the data is equally (non) visible for anyone who cares to look.
The only arguable difference in security is that the URL will likely be logged by the server and/or proxies, while body data usually isn't. But then again, you're already sending the data to the server you presumably trust, so even that doesn't make much of a difference. And the server(s) could be logging the body as well if they wanted to.
Semantically I'd send the data in the POST body, but that's not because of security.

A: Here is W3 recommendation for you.
That pretty much says what exactly you need to do.

Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead.

Though it is saying post, internal meaning of it is to keep the URL clean.

Apart from the given two ways, if I were you, I prefer clean codes (imagine 10 query param).
var data = new FormData();
data.append('userName', 'xyz');
data.append('password', 'abc');

var xmlHttp = getXMLHttpRequest();
var url="login.do";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4) {
            // Done. Do nothing.
        }
    }
xmlHttp.send(data);


text:
Q: How to add details from column to form title - SharePoint 2010 Is it possible to add additional column info to the form title.  For example, when we open a list item to view it's content along the top in the title is the SharePoint List + item Title. I'd like to also include the item's reference number (which is in a separate column).  This is so when reviewing it I don't have to keep scrolling back to this info.
I am using SharePoint 2010

A: If you are using Sharepoint Designer
Open your form in advanced mode
Goto below section .You will get this in first 1-2 lines .
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
<SharePoint:listformpagetitle runat="server"/>
</asp:Content>

Remove
 <SharePoint:listformpagetitle runat="server"/>

Add whatever you want like below
If you want a value of a column, set the column name in the Property attribute
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
<SharePoint:ListItemProperty runat="server" Property="Status"/>
</asp:Content>

If you want a constant text
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
Welcome Page
</asp:Content>

Note: As a safety measure please try this on a test form first


text:
Q: How do you protect your commercial HTML/CSS and JavaScript codes on their demos? What are the fundamentals to protect the source codes of commercial HTML/CSS and JavaScript files on their demos in a market?
Come on, please don't mark this question as off-topic as I know I can try to:

*

*Disable the right click.

*Disable the [Ctrl + Shift + i].

*Disable the [Ctrl + u].

*Learn and use a JavaScript obfuscator.

I want to know all the fundamentals to protect my commercial codes as we all need to know.
Is an obfuscator enough for JScript? How about for CSS3 animations and effects?
Any right way to do this? Is there a standard open source or any other tricks for this?

A: Obfuscating your JS/CSS will be your best bet. If the demo has to work, then those files have to be downloaded to the client's machine.
From then onward, your files are in possession of the client and you can't but just obfuscate those to give the client a hard time to figure your code out.
How can you disable F12 which launches Developer Console? And what about Context Menu key on the keyboard, which can be easily used to circumvent the disabled right click?
If you want fail-proof method, then just don't have a demo at all or have limited options available in it.


text:
Q: Sql query to find high of individual days I have a table like this.
date           value
2015-06-27     8088.15
2015-06-27     8083.25
2015-06-27     8068.25
2015-06-24     8246.45
2015-06-24     8343.55
2015-06-24     8232.35
2015-06-24     8564.65
2015-06-23     8354.75
2015-06-23     8455.25
2015-06-23     8451.45
2015-06-22     8343.55
2015-06-22     8345.75
2015-06-21     8023.75
2015-06-21     8029.85
2015-06-20     8023.95

I need to find individual max(value) for latest 3 dates. I need output like this.
date           max(value)
2015-06-27       8088.15
2015-06-24       8564.65
2015-06-23       8455.25

I tried this query
SELECT MAX( value )
FROM table_name
WHERE DATE
IN (SELECT *
FROM (
SELECT DISTINCT DATE
FROM table_name
ORDER BY DATE DESC
LIMIT 3
) AS t
)

But this is actually giving overall max(value) for latest 3 dates. How can I achieve this?

A: Simply use:
SELECT date, MAX( value )
FROM table_name
GROUP BY date
ORDER BY DATE desc
LIMIT 3

Explanation: It will select the grouped date along with maximum VALUE which is ORDERED BY date and will return 3 rows due to LIMIT 3

A: In order for the query to work, your desired max value should be grouped according to days so therefore you should add GROUP BY clause
in your query to limit only the result of the max value based on the grouped date.
SELECT date, MAX(value) FROM table_name
GROUP BY date
ORDER BY DATE desc
LIMIT 3;


text:
Q: Can I customize Carousel-indicators in react-bootstrap I'm using http://react-bootstrap.github.io/ Carousel component. I am trying to customize the carousel-indicators including some texts, and make it look like a button with text, but react render 'ol' tag into a new CarouseItem and no redirect function
    return (
       <Carousel id="sampleSlide" indicators={false}>

          <CarouselItem>

               Hello World

          </CarouselItem>
          <CarouselItem>

               Hello World

          </CarouselItem>
      </Carousel>
    );

Is there any way to customize it or any other method to do so?

A: You can change your Bootstrap carousel Indicator with customized CSS/SCSS
Reactjs code:

          <Carousel>
              <Carousel.Item>

                <Carousel.Caption>

First slide label

Nulla vitae elit libero, a pharetra augue mollis interdum.

                </Carousel.Caption>
              </Carousel.Item>
        </Carousel>

CSS/SCSS code:
    .my__carousel_main {
            div{
                ol{
                    li{
                        background-color: red;
                        border-radius: 50%;
                        height: 10px;
                        width: 10px;
                    }
                }
            }
        }

Thank You ;)

A: This is how I customized it:
.carousel-indicators li {
border-top: unset;
width: 10px;
border-bottom: unset;
border: 1px solid transparent;
border-left-width: 0;
border-right-width: 0;
border-radius: 10px;
background-color: rgba(169, 29, 42, 0.4);
height: 10px;
width: 20px;}

.carousel-indicators .active {
border-top: unset;
border-bottom: unset;
border: 1px solid transparent;
border-left-width: 0;
border-right-width: 0;
border-radius: 10px;
background-color: #A91D2A;
height: 10px;
width: 50px}

A: I customized them this way:
.carousel-indicators [data-bs-target] {
  width: 10px !important;
  height: 10px !important;
  border: 1px solid transparent !important;
  border-radius: 10px;
}

.carousel-control-prev-icon {

    background-image: url("./../../images/play.svg") !important;
    transform: scaleX(-1);

}

.carousel-control-next-icon {

    background-image: url("./../../images/play.svg") !important;

}

Add !important otherwise it won't override the default styling.

A: This is how I manage to customize:
.carousel-indicators button {
  width: 0.4rem !important;
  height: 0.4rem !important;
  border-radius: 50%;
}

.carousel-indicators button:not(:first-child) {
  margin-left: 0.5rem;
}

.carousel-indicators .active {
  background-color: #ff7a54;
}

A: Simply make use of the "indicatorLabels" name and add values to the array to represent each indicator. This adds an aria-label property to the individual indicators, i.e. indicatorLabels = {[ "btn1", "btn2" ]}. In this case, I'm assuming the carousel has two slides.
Visit https://react-bootstrap.github.io/components/carousel/ to read up on names, their types, and default values.
Then in CSS:
[aria-label] {
  width: 15px !important;
  height: 15px !important;
  border-radius: 50%;
}


text:
Q: How to add a state value to an Object? I would like to add the value from the description Text-field to the value prop of the Object. The value={description} is stored in a state [description, setDescription].
Can someone help how to implement it correctly into the handleCreate function??
export const Dialog: React.FC<DialogProps> = ({allTasks, setAllTasks}) =>{

    const queryClient = useQueryClient();
    const [open, setOpen] = useState(false);
    const [description, setDescription] = useState("");

    const handleClickOpen = () => {
        setOpen(true);
      };

      const handleClose = () => {
        setOpen(false);
      };

     const handleCreate =(description: any)=>{
      const addObjectToArray = (task: any) => {
        setAllTasks ((allTasks: any) => [...allTasks, task]);
      };

      addObjectToArray({
        description: description,
      })
       setOpen(false);
       };

return (
    <div>

      <Dialog  open={open} onClose={handleClose}>
        <DialogTitle>Add New Task</DialogTitle>
        <DialogContent>
         <Box sx={{width: 500}}>

          <TextField
            id="description-text-field"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />
         </Box>
        </DialogContent>
        <DialogActions>
           <Button onClick={handleClose}>Cancel</Button>
           <Button onClick={handleCreate}>Create</Button>
        </DialogActions>
      </Dialog>
    </div>

)}

A: Try this code:

const handleCreate = (description: any) => {
    const addObjectToArray = (task: any) => {
      setAllTasks([...allTasks, task]);
    };


text:
Q: Why is F# member not found when used in subclass I have a base type that I want to inherit from, for all my DAO objects, but this member gets the error further down about not being defined:
type BaseDAO() =
    member v.ExecNonQuery2(conn)(sqlStr) =
        let comm = new MySqlCommand(sqlStr, conn, CommandTimeout = 10)
        comm.ExecuteNonQuery |> ignore
        comm.Dispose |> ignore

I inherit in this type:
type CreateDatabase() =
    inherit BaseDAO()

    member private self.createDatabase(conn) =
        self.ExecNonQuery2 conn "DROP DATABASE IF EXISTS restaurant"

This is what I see when my script runs in the interactive shell:
--> Referenced 'C:\Program Files\MySQL\MySQL Connector Net 6.2.3\Assemblies\MySql.Data.dll'

[Loading C:\Users\jblack\Documents\Visual Studio 2010\Projects\RestaurantService\RestaurantDAO\BaseDAO.fs]

namespace FSI_0106.RestaurantServiceDAO
  type BaseDAO =
    class
      new : unit -> BaseDAO
      member
        ExecNonQuery2 : conn:MySql.Data.MySqlClient.MySqlConnection ->
                          sqlStr:string -> unit
      member execNonQuery : sqlStr:string -> unit
      member
        execQuery : sqlStr:string *
                    selectFunc:(MySql.Data.MySqlClient.MySqlDataReader ->
                                  'a list) -> 'a list
      member f : x:obj -> string
      member Conn : MySql.Data.MySqlClient.MySqlConnection
    end

[Loading C:\Users\jblack\Documents\Visual Studio 2010\Projects\RestaurantService\RestaurantDAO\CreateDatabase.fs]

C:\Users\jblack\Documents\Visual Studio 2010\Projects\RestaurantService\RestaurantDAO\CreateDatabase.fs(56,14): error FS0039: The field, constructor or member 'ExecNonQuery2' is not defined

I am curious what I am doing wrong.
I have tried not inheriting, and just instantiating the BaseDAO type in the function, but I get the same error.
I started on this path because I had a property that had the same error, so it seems there may be a problem with how I am defining my BaseDAO type, but it compiles with no error, which further confuses me about this problem.

A: It looks like maybe you are #loading individual files, and maybe you have a bit of stuff in your history, and the class you're inheriting is in another namespace/module and you're inheriting some older version without that member?
Reset your fsi session and start over, or put it in .fs files to diagnose if anything is really wrong, but I think the code is ok and the issue is something with how you're interacting with FSI.


text:
Q: Deleting rows where all elements are missing value from list-R Let I have a list(list1) which consists data frames(df1, df2, ..dfn) where each data frame has different number of columns.
Let list1[[1]]:
df1:

indx  v1  v2
1     23  45
2     NA  34
3     NA  NA
4     NA  NA
5     56  NA

and
df2:

indx  v9  v6
1     5   15
2     11  78
3     16  NA
4     NA  NA
5     NA  8

I want to delete rows where all elemetns of rows(except the indx row) are NA.
So the ouput should be(list2)
list2[[1]]:
df1:

indx  v1  v2
1     23  45
2     NA  34
5     56  NA

and
df2:

indx  v9  v6
1     5   15
2     11  78
3     16  NA
5     NA  8

How can I do this using R? I will be very glad fotr any help. Thanks a lot.

A: We can loop over the list with lapply, get the rowSums on the logical matrix (!is.na(x[-1])), convert to logical vector by checking the elements are not equal to 0 and use that to subset the rows.
lapply(list1, function(x) x[!!rowSums(!is.na(x[-1])),])
#$df1
#  indx v1 v2
#1    1 23 45
#2    2 NA 34
#5    5 56 NA

#$df2
#  indx v9 v6
#1    1  5 15
#2    2 11 78
#3    3 16 NA
#5    5 NA  8


text:
Q: PHP database connection code no longer working on host site I have a PHP site with a mySQL database that I'm working on. I'm running Apache, PHP, and mySQL on my development machine, and my code all works just fine. A week ago, I uploaded my code and database to my organization's web host (it's a non-profit group, so the host is not a dedicated in-house server, but rented space.) At that point, the code worked perfectly on the host site.
I added a few new pages this past week, so uploaded them today and went to test. And lo and behold, my code (existing code, not the new stuff) returns a database connection error.
The host company insists that the issue is on my end. How is that possible, if the code was working perfectly just last week and no changes have been made to the existing code? It seems to me the only possible explanation is that there was a change in the host's environment.
I'm pretty new to PHP, so I'm hoping someone can help me out here and explain whether it is possible or whether the host company's tech support is clueless.

A: Check your php error_log file. The database error will probably be listed there.


text:
Q: Java : GroovyClassLoader : cannot find symbol for method in Groovy Class I am trying to use GroovyClassLoader in java to execute a method in Groovy Class.
I have created a Java Class, pubic method which creates a instance of GroovyClassLoader , parseClass and then creates a new Instance of the class, Calls a method in the class.

public class Gtest{

   public static void main(String args[])throws IOException , InstantiationException ,IllegalAccessException {

       GroovyClassLoader gcl = new GroovyClassLoader();

       Class cls =  gcl.parseClass("class Foo { void doIt() { println \"ok\" } }");
       Object obj = cls.newInstance();
       if(obj == null){
           System.out.println("null");
       }
       obj.doIt();

   }
}

Error : Gtest.java:22: error: cannot find symbol
       obj.doIt();
          ^
  symbol:   method doIt()
  location: variable obj of type Object
1 error

A: Its because object class doesn't have doIt() method.
You have to use below syntax to invoke your method.
Method sumInstanceMethod
  = Operations.class.getMethod("doIt");
 Object result
      =  sumInstanceMethod.invoke(obj, null);

A: System.out.println(cls.getDeclaredMethod( "doIt", new Class[] {}).invoke( obj,  new Object[] {} ));


text:
Q: Rails3 CookieOverflow I am getting this error:
ActionDispatch::Cookies::CookieOverflow

In config/application.rb I have:
config.session_store :active_record_store

There is no data being stored in the sessions table.
I am using RubyCAS-client with this code:
https://github.com/zuk/rubycas-client-rails
Am I doing something wrong to have the code stored in the database or is this code not setup to use active record store?

A: I figured it out, I was doing it in config/application.rb.  When I changed it in config/initializers/session_store.rb it worked.
I don't know if this is completely right because I assume config/application.rb is the place it should be?


text:
Q: Odd output by an Array I am learning about Arrays in the book 'Programming in C' by Stephen G. Kochan. I have reached a point where I am getting really confused by the output, despite long time trying to find syntax errors.
Here is my code:
#include <stdio.h>

int main (void)
{
    int values[10];
    int index;

    values[0] = 197;
    values[2] = -100;
    values[5] = 350;
    values[3] = values[0] + values[5];
    values[9] =
    values[5] / 10;
    --values[2];

    for ( index = 0; index < 10; ++index )
        printf("values[%i] = %i\n", index, values[index]);

    return 0;
}

How the output is supposed to look according to the book:
values[0] = 197
values[1] = 0
values[2] = -101
values[3] = 547
values[4] = 0
values[5] = 350
values[6] = 0
values[7] = 0
values[8] = 0
values[9] = 35

How my output looks like:
values[0] = 197
values[1] = -2
values[2] = -101
values[3] = 547
values[4] = 4200832
values[5] = 350
values[6] = 4200926
values[7] = 4200832
values[8] = 7680288
values[9] = 35

It is like all the zeros (uninitialized values) have been replaced with these big numbers. What is going on, what how can I change it?
UPDATE
Peter Griffiths mentions this, which is a quote from the book "Programming in C 3rd edition" by Stephen G. Kochan:

Because you never assigned values to five of the elements in the array
  - elements 1, 4, and 6 through 8 - the values that are displayed for them are meaningless. Even though the program's output shows these
  values as zero, the value of any uninitialized variable or array
  element is not defined. For this reason, no assumption should ever be
  made as to the value of an uninitialized variable or array element.

This clearly state that there is nothing wrong with the book. SO IT IS NOT A BAD BOOK! ONLY GOOD EXPERIENCES SO FAR!
I am using Windows 7 Home Premium 64-bit and I am using the gcc (GCC) 4.7.2 compiler. The reason for the different output is probably different OS and Compiler.

A: Here's a quote from that book, from the paragraph immediately following the output you quote:

Because you never assigned values to five of the elements in the
  array - elements 1, 4, and 6 through 8 - the values that are
  displayed for them are meaningless. Even though the program's output
  shows these values as zero, the value of any uninitialized variable or
  array element is not defined. For this reason, no assumption should
  ever be made as to the value of an uninitialized variable or array
  element.

Moral: you get a lot more out of programming books when you actually read them.

A: In C the elements of an array are not initialized by default.
Just try :
int values[10] = {0};

In Programming, it is a good practice to assume that every non initialised pointers and non-pointer variables contain garbage.
EDIT :
If this book don't explain you that... I will do like others and suggest you to find a new book....
It seems that this book actually talk about the garbage values you may find with uninitialise variables...

A: C does not zero the elements of an array. That's why those elements are not initialized to zero; you're just seeing garbage values from whatever was already in those memory locations.
If your book says that C does zero the elements of an array, get a new book.

A: You don't appear to have any errors in your syntax.  Memory is reused by the system very quickly, so quickly that the system doesn't bother resetting all values to 0 prior to handing the memory over to a process to be used.
It is good programming practice to always assume that your variables contain garbage until you have assigned a value to them.  This applies to pointers just as much as non-pointer variables.  An array variable in C/C++ is really a pointer to a continuous block of memory, and as such the system allocates that memory by an internal process that is primarily tuned for speed.  Taking the time to set all values in memory blocks to 0 would reduce the speed at which the system returns memory to you; further, it is assumed that in almost all cases you really won't want a big block of zero values to carry around, instead you will be putting your own data in.
Check the book you are reading to see if there is a note later on about this behavior.  If such a note does not exist in the book, you might consider reading alternate sources to make sure that you don't run into other assumptions made by the writer(s) that may be inaccurate.

A: you are getting garbage values at index 4, 6, 7, 8.., default values of array elements are garbage( if you do not initialize), you should declare your array and initialized you array with 0 value, just to like:
int values[10] = {0};

This will set all value[i] to zero. (remember incomplete initialization set uninitialized values with 0).

A: You don't initialize elements 1, 4, 6, 7, and 8. To set the entire array to zeros, initialize it like so:
int values[10] = {0};

A: Initialize the array. You haven't initialized the array so it's filled with garbage values. Do it like:
int values[10] = {0};

Good practice is to always initialize the variables.
And i suggest you changing your book as well.
Try "C -How to Program by Dietel & Dietel"

A: Like what everyone else said.  The uninitialized values are not guaranteed to be 0.  This is true for all variables, not just ints.  A good practice is to initialize all variables to some default value just to make sure it doesn't have garbage values that could mess you up later.


text:
Q: Flex paragraph takes up more space on its right edge when it has multiple lines or longer words rather than one line The application I'm working with has a piece of HTML code styled using flex that is present in multiple places to visualize several pop-up messages. The messages have a closing icon in the upper right corner.
However, depending on the length of the message within the
 element, the distance between the text and the closing icon changes. For instance, if the text has multiple lines or longer words, the
 element takes up more space, the distance between the text and the closing icon increases, and I can't figure out why.
Short text example
Long text example
How do I ensure a uniform distance between them?

      "Editing the product draft continues from the last altered step.
       Editing the product draft continues from the last altered step."

      ::before

A: You could use position: absolute to place the close icon and add paddind to the right of the alert box. Here is an example:

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.alert {
  position: relative;
  background: #ffffb7;
  padding: 5px 50px 5px 10px;
  z-index: 1;
  margin-bottom: -10px;
  box-shadow: 0px 5px 5px 0px rgba(0,0,0,0.25);
  display: flex;
  align-items: center;
}

.alert i {
  position: absolute;
  right: 20px;
}

.container {
  width: 100%;
  height: 60px;
  background: #fff;
  box-shadow: 0px 5px 5px 0px rgba(0,0,0,0.25);
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam luctus dolor magna, a consequat enim fringilla vitae.


text:
Q: why is 10 * (7/10) = 7 in JavaScript? 7 and 10 in the expression (7/10) are integers, so the result 0.7 should be integer as well, which is 0, and the result for the entire expression should be 0 too. However, it's giving me the result of 7, why? Is it ignoring the parentheses or converts to double automatically?

A: There is no int and double in JavaScript
In JavaScript, both int, flot, and double are normalized to work together. They are treated as 1 (They're treated as as Number, which is an IEEE 754 float. Thanks @Elias Van Ootegem). Equality, Liberty and Fraternity. and thus;
10*0.7 = 7
JavaScript is not like C.

A: JavaScript doesn't have an integer type, or a double, or a float... it just has 1 type for all numbers: the helpfuly called Number type (try var foo = new Number(7);, or var foo = Number('123string');
Now, I know I said that JS doesn't know of floats, but that's not entirely true. All Number type vars/values are, essentially 64 bit floats, as defined by the IEEE 754 standard (which are, indeed, as Jan Dvorak kindly pointed out to me, double's in most staticly typed languages), with all the caveats that brings with it:
(.1 + .2);//0.30000000000000004

But that's not the point. The point is that, in JS you can perform float + int arithmatic without there ever being a need for internal casts, or conversions. That's why 10*(7/10) will always be 7

A: Javascript doesn't have integers, and even if it did, there's nothing that says that / needs to return an integer (just because another language may do that doesn't mean every language has to). The operation results in a float/Number, just like all Javascript numbers are, period.

A: JavaScript doesn't distinguish between integers and floating point numbers, everything I believe is considered a double so that is just why you get the result.
Take a look at the details on the Number property on MDN.

A: JavaScript uses dynamic types. That means that a variable like this:
var str = "hi";

Can later become:
str = 123; //now we have an 'int'
str += 0.35; //now str is 123.35, a 'float'

So JavaScript doesn't cast floats to ints for example.
If you want to force a "cast" then you have to do:
var integer = parseInt( 3.14*9.0291+23, 10 ); //the second parameter (10) is the 'base'

But remember, Javascript will not take care of types, that's your problem.

A: try this
10*parseInt(7/10)

hope this will help you

A: If you try to follow the rules, then
10 * (7/10) --> 10 * .7 --> 7

You cannot change the way its gonna result into.

so the result 0.7 should be integer as well, which is 0

If you want this, then try using
Math.Floor();

This would change the decimals to the nearest int! Or try out parse()


text:
Q: Flash syntax error I'm a newbie with flash, what I'm trying to do is make the background scroll with my mouse...but this is giving me a syntax error...where is the error coming from?
var movieWidth:Number = stage.stageWidth;

menuWidth = nav1.width;

nav2.x = nav1.x + menuWidth;

addEventListener("enterFrame",frame_handler);

function frame_handler(e:Event) {
var a:Number = mouseX;
var b:Number = movieWidth/2;
var c:Number = 20;
var pos:Number= 0-((a-b)/20);

nav1.x += pos;
nav2.x += pos;

if (nav1.x >= 0 && nav1.x <= menuWidth)
{ nav2.x = nav1.x – menuWidth }
else if (nav1.x <= movieWidthmenuWidth)
{ nav2.x = nav1.x + menuWidth }

if (nav2.x <=movieWidth-menuWidth)
{ nav1.x = nav2.x + menuWidth }
else if (nav2.x>=0)
{ nav1.x = nav2.x- menuWidth }

}

A: Note this statement
{ nav2.x = nav1.x – menuWidth }

I think that your minus character is wrong one in this statement
wrong one (ASCII 8211)  –

correct one (ASCII 45) -

Please replace. Check other statements also.
See this : http://www.cs.sfu.ca/~ggbaker/reference/characters/

A: Is menuWidth ever declared? same for nav1 and nav2 - what is it?
Besides, you would be on the safe side, if you put a semicolon after a statement. It is not mandatory as per the compiler rules, but it may put you in a confusing situation, where you would misinterpret the code.
As an aside: unary - operator does the same as binary - operator when the first operand is 0. That is the expression:
0 - x

is equivalent to:
-x


text:
Q: send_mail is clearly sending email but no email is showing up in inbox I have these email settings in my settings.py
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'email@myemail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587

and am using this function to send email to recipients.
def send_email(subject, body, recipients, agent_email, bcc=[], attachments=[]):
    recipient_list = []
    if isinstance(recipients, (str, unicode,)):
        recipient_list.append(recipients)
    else:
        recipient_list = recipients

    recipient_list = recipient_list + bcc

    send_mail(subject, body, settings.EMAIL_FROM, recipient_list)

while it looks quite clear when I go to the django-admin site that the email was indeed sent and no error messages show in the log files whatsoever, when I go to check the email that it was sent to, nothing shows in the inbox. I would expect to see the email there, especially given that it shows as sent in django-admin. Have I misunderstood something about how email is sent from the system?
EDIT
I also checked my spam folder and added
EMAIL_FROM = 'email@myemail.com'

because I noticed it wasn't there before. Same results, though. Email appears sent according to django-admin but no email in my inbox.

A: Try to add the following in settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER


text:
Q: Operation Failed when installing a Nuget Package I have a "new" windows xp sp3 machine with VS2010 SP 1 and Nuget 1.8
Every time a try to add a Nuget Package a receive the following error:
The specified cryptographic algorithm is not supported on this platform.
Does anyone know what does that means?

A: There's a known issue with NuGet 1.8 : NuGet issue#2240. The Nuget team will soon (crossing fingers) release a hot fix.
In the meanwhile, I'd suggest installing NuGet 1.7.
EDIT: NuGet released the hotfix (1.8.30524.9000)


text:
Q: Eclipse could not resolve Maven paths I have my local m2 repo set to /Users/ratha/.m2/repository.
I built maven projects using mvn eclipse:eclipse and imported to my eclipse workspace. To resolve build paths, i set the build path by setting Libraries/M2_REPO variable. But, all my java files could not locate the jars which are in my local maven repository.
How can i resolve this issue?


text:
Q: Why does the same header file have to be included twice? I've just finished building a program in which I have a main.cpp file and my own static library, let's call it myLib and it's made from myLib.h and a myLib.cpp files.
myLib.h and myLib.cpp make a static library.
In my static library, I make use of some boost functions and classes so as my own classes and functions in myLib.cpp can do some things: so in myLib.cpp I add the lines
#include <boost/math/distributions/binomial.hpp>
#include <boost/math/tools/roots.hpp>

to myLib.cpp
Now myLib.h contains function declarations, and some class definitions, myLib.cpp has the implementation of those functions and class definitions, and since some of the functions, require the classes declared in myLib.h, #include "myLib.h" must also be added to the myLib.cpp file (I suspect that if those functions did not, then myLib.cpp could be compiled as an object file without the myLib.h file needing to be included so long as whatever uses the object file does include myLib.h - but since some functions use the classes, myLib.cpp also includes myLib.h). Is it acceptable for the implementation file to require the header file for compilation as an object file (and then inclusion into a .a file)? I can't quite fathom if this is bad or not - I thought the idea was they are supposed to be separate?

A: This is totally normal and the way things are done in C/C++.  The header file contains all the declarations needed to use the library, the source file contains the definitions needed to build the library.  This source file includes the header file as classs, functions, etc need to be declared before they can be defined.

A: In C++ it is totally acceptable to include the header file which contains the class declaration in the source file which contains the implementation. If you think more this is normal because the implementation (cpp file) will have no other way how to know about the fields (variables) in the class.

A: If you are implementing your class in 2 different (head and source) files (which is normally the case), then yes, you absolutely HAVE to include header file in your source file. If your class is really light, then you can just implement your function within the header file. This is bad practice and not really recommended, so I would not recommend that either. Especially in the case of a static library, where you are supposed to give out the header files to other modules in order to make use of it. You do not want the library consumer to see any source code.


text:
Q: Embed youtube video inside page hosted on amazon ec2 I want to embed a youtube video on a page hosted inside a Amazon EC2 instance running apache.
If I try to access that page using the Public DNS address, everything works ok and the video plays.
If I try to access that page using the Elasic IP address, I get a message saying that the content of the video is owned by some company and it's restricted on certain sites.
Why does it work with the public DNS address but not with the Elastic IP? It also works ok when running the site in localhost.
Will the videos work after I link a domain to the elasic IP address?
Regards,
Timo

A: It seems that the videos work after linking the elastic ip address to a domain.


text:
Q: Dual boot windows 8.1 and Ubuntu 14.04.1 LTS on sony vaio I managed to install Ubuntu in a sony vaio laptop with Windows 8 pre-installed and updated to Windows 8.1. After I finished the process, I experienced the same behavior than "landroni" (How to fix dual-booting Windows 8 and Ubuntu 14.04 on a Sony Vaio?). However, I do not need to enable External device boot, as he says at the final of his post.
The boot-repair tool generated this url (http://paste.ubuntu.com/8048145/). I understand that boot-repair tries to modify the boot order in the machine by pointing to GRUB.
In this site (http://www.zdnet.com/my-experiments-with-multi-boot-selection-with-uefi-boot-manager-7000013627/), the author explains how to manually change the bootloader, however, by looking into the report generated by boot-repair, I saw there are three bootmgfw.efi files in three different partitions (sda1, sda2 and sda3). I am afraid to mess things up by chosing the wrong file. Can anyone help?
Thanks,


text:
Q: MVC razor how do align text-box's? I am using MVC 4 and razor and have placed label for and textbox for in the view. All the textbox's are sitting right against the labels, how do i move them a tab space away or so and keep them aligned?
Razor:
    @Html.LabelFor(m => m.Date)
    @Html.TextBoxFor(m => m.Date)

    @Html.LabelFor(m => m.QuoteNumber)
    @Html.TextBoxFor(m => m.QuoteNumber)

    @Html.LabelFor(m => m.ClaimNumber)
    @Html.TextBoxFor(m => m.ClaimNumber)

    @Html.LabelFor(m => m.MotorBodyRepairer)
    @Html.TextBoxFor(m => m.MotorBodyRepairer)

Currently it looks like this:

A: Model
Add display attributes:
        [Display(Name="Date")]
        public DateTime Date { get; set; }
        [Display(Name="Quote Number")]
        public string QuoteNumber { get; set; }
        [Display(Name="Claim Number")]
        public string ClaimNumber { get; set; }
        [Display(Name="Motor Body Repairer")]
        public string MotorBodyRepairer { get; set; }

View
Use an editor for template
@Html.EditorFor(m => m)

CSS
Add this to your style sheet, changing the values to suite.
.editor-label > label
{
    float: left;
    width: 150px;
}

Screen grab

Update
Replace this:

    @Html.EditorFor(m => m.Date)

    @Html.EditorFor(m => m.QuoteNumber)

    @Html.EditorFor(m => m.ClaimNumber)

    @Html.EditorFor(m => m.MotorBodyRepairer)

With this:

    @Html.EditorFor(m => m)


text:
Q: How can I unit test an AuthorizeWhereIn attribute with Ninject I'm using a custom authorisation attribute (blatantly plagiarised from another SO answer) but have hit a hurdle where I can't find a way to unit test it. Unfortunately I do need to unit test is at the same time as I invoke my controller action so I'm trying to find a way to do the Ninject dependency injection in the unit test.
The AuthorizeWhereIn attribute is:
public class AuthorizeWhereIn : AuthorizeAttribute
{
    /// <summary>
    /// Add the allowed roles to this property.
    /// </summary>
    public new HCIRoles Roles;

    /// <summary>
    /// Checks to see if the user is authenticated and has the
    /// correct role to access a particular view.
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");

        // Make sure the user is authenticated.
        if (!httpContext.User.Identity.IsAuthenticated)
            return false;

        // Get user's current roles
        var roles = System.Web.Security.Roles.GetRolesForUser();
        HCIRoles currentRoles = (HCIRoles)Enum.Parse(typeof(HCIRoles), string.Join(",", roles));

        // Perform a bitwise operation to see if the user's role
        // is in the passed in role values.
        if (Roles != 0 && ((Roles & currentRoles) == 0))
            return false;

        return true;
    }
}

The problem is the System.Web.Security.Roles.GetRolesForUser() call which isn't available in my unit test and which I want to mock any way. I can abstract that call into a separate interface and use Ninject to inject it for the web application but I can't find a way to do the same in a unit test.
So if I change the attribute to something like the below
public class AuthorizeWhereIn : AuthorizeAttribute
{
     [Inject]
     IRoleService RoleService { get; set; }

     ...
 }

and my unit test code is along the lines of:
 [TestMethod()]
 public void IndexTest()
 {
      var builder = new TestControllerBuilder();
      var controller = builder.CreateController<UserController>(dataLayer.Object);
  var invoker = new ActionInvoker<UserController>();

      var mockMembershipService = new Mock<IMembershipService>();
      mockMembershipService.Setup(x => x.GetAllUsers(It.IsAny<int>(), It.IsAny<int>(), out       total)).Returns(new MembershipUserCollection());
      controller.MembershipService = mockMembershipService.Object;
      builder.InitializeController(controller);

      invoker.InvokeAction(controller.ControllerContext, x => x.Index());
 }

And the controller being tested is:
[AuthorizeWhereIn(Roles = HCIRoles.Admin)]
public class UserController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }
}

My question is how can I inject the RolseService depdency in the unit test given that I can't directly access the AuthroizeWhereIn attribute?
I've read and re-read the Ninject Filter extension for MVC3 http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/ but can't seem to apply it to this case.

A:
given that I can't directly access the AuthroizeWhereIn attribute

Why not accessing it directly? That's what you are trying to test after all.
private class TestController : Controller { }

[TestMethod]
public void Test()
{
    // arrange
    var builder = new TestControllerBuilder();
    var controller = new TestController();
    builder.InitializeController(controller);
    controller.ControllerContext = new ControllerContext(builder.HttpContext, new RouteData(), controller);
    var httpContext = builder.HttpContext;
    httpContext.Stub(x => x.Items).Return(new Hashtable());

    var identity = new GenericIdentity("foo");
    var roles = new string[0];
    httpContext.User = new GenericPrincipal(identity, roles);
    var ad = MockRepository.GeneratePartialMock<ActionDescriptor>();
    var context = new AuthorizationContext(controller.ControllerContext, ad);

    var sut = new AuthorizeWhereIn();

    var service = MockRepository.GenerayeStub<IRoleService>();
    sut.RoleService = service;
    // TODO: set expectations on the service

    // act
    sut.OnAuthorization(context);

    // assert
    // TODO: assert on the type of context.Result
    // If it is HttpUnauthorizedResult the authorization has failed
    // (i.e. your custom AuthorizeCore method returned false)
}

A: A colleague ended up finding a clever solution using an extension method on IPrincipal. That way there's no need for dependency injection in the attribute since the HttpContext can be mocked with the Mvccontrib library.
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    if (httpContext == null)
        throw new ArgumentNullException("httpContext");

    // Make sure the user is authenticated.
    if (!httpContext.User.Identity.IsAuthenticated)
        return false;

    // Get user's current roles
    //var roles = System.Web.Security.Roles.GetRolesForUser();
HCIRoles currentRoles = httpContext.User.GetRoles();

    // Perform a bitwise operation to see if the user's role
    // is in the passed in role values.
    if (Roles != 0 && ((Roles & currentRoles) == 0))
        return false;

    return true;
}

public static HCIRoles GetRoles(this IPrincipal user)
{
HCIRoles roles = 0;

foreach (HCIRoles r in Enum.GetValues(typeof(HCIRoles)))
    {
         if (user.IsInRole(r.ToString()))
    roles |= r;
}

return roles;
}


text:
Q: Solving a complicated inequality I have got the following inequality
$|(a_{12}+a_{21}) x_1 - i (a_{12}-a_{21}) x_2 + (a_{11}-a_{22}) x_3 + (a_{11}+a_{21}) X| \le \sqrt{a_{11}^2 + |a_{21}|^2} + \sqrt{a_{22}^2 + |a_{12}|^2}$,
where $a_{12}=a_{21}^*$ are complex conjugates; and $a_{11}$ and $a_{22}$ are real coefficients. Also, $|\vec{x}| + |X|\le 1$. Here $\vec{x}=(x_1,x_2,x_3)$.
Problem: I need to solve for $x_1,x_2,x_3$ and $X$.
This is my first question on StackExchange. So please don't mind if you find something wrong in the way I am asking.
Edit: I have rewritten my question in a more simplified form which I just got.


text:
Q: How to install applications by default to another drive I'm building a computer, with a 120GB SSD, and a 2TB Hard drive. I am planning to install the Ubuntu Operating System(14.04) to the 120GB ssd, But I would like to have my applications install by default to another hard drive.
I have seen this link: Installation -- Install apps to another disk
But that covers how to move an existing application to another disk.
Is there any way to have all applications install, by default to another disk? Is it as simple as partitioning /usr, /lib, and /bin to another disk? or is that not possible? Any help would be appreciated.
One thing to point out: I am asking this, because I know you are able to do this on Windows 10 by changing the default installation drive via settings, But I do not want to use windows 10, as the licence terms are too strict in my opinion.

A:
Is it as simple as partitioning /usr/, /lib/, and /bin/ to another disk?

Yes. And maybe /var/, /etc/ and /opt/ too (depending on usage).
I would not bother. The only 3 things I would leave of the SSD are tmp filesystems, swap and the directories inside your users /home/. The 1st 2 you do during mounting. The 3rd you can do by editing /home/$USER/.config/user-dirs.dirs.

A: Yes you can do that.
You have several choices - like mount /dev/sdb(b is for the second drive generally) so let's say your ubuntu partition on second hard drive is at /dev/sdb2 - then mount that into /etc/fstab
But better approach is LVM as you can change the partition sizes later and it's flexible. But it's not as straight forward as the previous method i mentioned above.
At the time of installation make use of LVM for your second drive(2TB hard drive). You can make some logical volumes like /opt, /usr, /home, /var into that and work accordingly.
I tried to do it after the install(as i added the additional hard drive into my working Ubuntu). I got success to have my /var into the second drive and others - i have some problem. But i will say do it at the time of installation itself.
You can refer to my detailed thread and it has got a lot of pointers to help others.
After going thru the LVM route /opt is on second drive where i install all the applications.
This is how my second drive looks like - it has Windows partion as well as Linux. Using gparted I just changed the flag to lvm

You can get gparted
sudo apt-get install gparted

Hope this helps


text:
Q: MongoDB Atlas Search Stage for newsfeed with GoogleRating, CurrentDate, LikeCount & CommentCount I'm working on social media platform and I need to fetch posts for newsfeed with mongodb search query.
currently I'm using dynamic index on my post collection, Let say this my post collection
{
 _id : ObjectId('123'),
 GoogleRating : 4.5,
 LikeCount : 20,
 CommentCount : 10,
 CreatedDate : "2022-04-21T00:00:00.000+00:00"
},
{
 _id : ObjectId('456'),
 GoogleRating : 1,
 LikeCount : 0,
 CommentCount : 5,
 CreatedDate : "2021-12-01T00:00:00.000+00:00"
}

And this is my current search stage
"$search":{
   "compound":{
      "should":[
         {
            "near":{
               "path":"GoogleRating",
               "origin":5,
               "pivot":2,
               "score":{
                  "boost":{
                     "value":2
                  }
               }
            }
         },
         {
            "near":{
               "path":"CreatedDate",
               "origin":ISODate("2022-04-21T00:00:00.000Z"),
               "pivot":7776000000,
               "score":{
                  "boost":{
                     "value":3
                  }
               }
            }
         },
         {
            "near":{
               "path":"LikeCount",
               "origin":1000,
               "pivot":2,
               "score":{
                  "boost":{
                     "value":3
                  }
               }
            }
         },
         {
            "near":{
               "path":"CommentCount",
               "origin":1000,
               "pivot":2,
               "score":{
                  "boost":{
                     "value":3
                  }
               }
            }
         }
      ]
   }
}

I've three criteria to boost document score.

*

*Boost score on the basis of GoogleRating.

*Boost score on the basis of Current date.

*Boost score on the basis of LikeCount and CommentCount.

I need to improve my search result Because it's not giving me desired output please suggest me what should i need to change in my search stage.

A: There are a few issues here. Normally, there would be an input that represents the query that you want to be relevant, but it's not required. For that reason, I will use a wildcard query on a wildcard path (IOW, everything matches).
We do, however, expose functionality for surfacing documents based on field values as you have expressed a desire for in your question. It's called function scores. Using the query you supplied, I made one modification to date and things seem to be working just fine and returning in the order listed above. Let me know if the below works for you. Here's the NodeJS:
[
  {
    '$search': {
      'compound': {
        'should': [
          {
            'near': {
              'path': 'GoogleRating',
              'origin': 5,
              'pivot': 2,
              'score': {
                'boost': {
                  'value': 2
                }
              }
            }
          }, {
            'near': {
              'path': 'CreatedDate',
              'origin': new Date('Thu, 21 Apr 2022 00:00:00 GMT'),
              'pivot': 7776000000,
              'score': {
                'boost': {
                  'value': 3
                }
              }
            }
          }, {
            'near': {
              'path': 'LikeCount',
              'origin': 1000,
              'pivot': 2,
              'score': {
                'boost': {
                  'value': 9
                }
              }
            }
          }, {
            'near': {
              'path': 'CommentCount',
              'origin': 1000,
              'pivot': 2,
              'score': {
                'boost': {
                  'value': 10
                }
              }
            }
          }
        ]
      }
    }
  }
]


text:
Q: How to get Auth0 working for mobile apps using the Vue SDK? For my mobile app i'm using Auth0 with Vue to let users login to the app so that they can see protected pages. However, when the user logs in through the external Auth0-loginpage it redirects the user to the redirect_uri. When testing locally in the browser everything seems to be working fine but when I deploy the app to either a simulator or the app/play store this callback/redirect flow seems to be broken.
import { createAuth0 } from '@auth0/auth0-vue';
const authorization = createAuth0({
      domain: "domain.auth0.com",
      client_id: "XXXXXXYYYYYYZZZZZ",
      redirect_uri: window.location.origin,
      audience: "https://xxx.yz"
    })
app.use(authorization)

I've searched for the correct way to use the redirect_uri but haven't found the right solution for it. And right now I'm doubting if this is the right way of using Auth0 for mobile apps.
Is there anybody with some experience using Auth0 in combination with mobile apps that can help me solve this issue?


text:
Q: QQ plot of sigma2 from an MCMC regression? I've been using R's lm to do some linear regression, but decided to give MCMCregress a try to get a feel for how it works. As expected, I got basically the same coefficients, but the extra sigma2 value puzzles me.
When I do a qqmath plot of the coefficients, I get the following graph, and I'm puzzled by the sigma2 plot. It's obviously not linear, but I'm not sure if that's meaningful in this context. I assume it's sigma squared, and when I took the square root and plotted it, the line was straighter, but still curved.
I guess my question boils down to: what is sigma2 telling me about the MCMC regression fit, and is a graph of it useful or should I ignore the graph and focus on something else? (All of the diagnostics and graphs I've done on my original lm fit seem to indicate that the fit is good, so I'm also wondering if the MCMC regression gives me more information or not.)

(If I need to provide the actual data, I can. I'm hoping that an answer depends more on what sigma2 is rather than on specific values.)

A: From the documentation for qqmath it seems that the default behavior is to compare the empirical quantiles to those of a normal distribution. So what the QQ plot for $\sigma^2$ (which is the error variance) is telling you is that its marginal posterior distribution is not normal, which you would fully expect. So it's not really informative or meaningful.
The remaining panels are telling you that the marginal posterior distributions of the regression coefficients are basically normal, perhaps with slightly heavier tails because they are marginalized over $\sigma^2$.
The MCMC regression does give you more information in that you have a full posterior distribution over all the parameters, so you can answer questions like "Given the data I've seen and my prior information, what is the probability that the tempwarmer coefficient is positve". You can also look at joint distributions of two or more parameters, or functions of the coefficients, and on and on.
I should mention that these QQ plots aren't really giving you an indication of goodness of fit. For that you would want to look at some other measures - posterior predictive distributions, for example, or MCMCregress may be able to do formal Bayesian model comparisons for you too. I'm not familiar with that particular function but a cursory Googling turned up some potential leads.
All that said, if the lm() fit is good I wouldn't loose much sleep over it. But I would most wholeheartedly encourage any forays into Bayesian analysis :)


text:
Q: MailChimp Api v1.3 how to set subscriber to pending anyone out there still knows if its possible to set the new subscriber status to pending with Mailchimp Api v1.3?  the documentation is disabled/deprecated.
the payload for a new subscriber actually is:
$payload = array('email_address' => $this->email,
                'merge_vars' => $this->merge,
                'email_type' => $this->emailType,
                'double_optin' => $this->doubleOptin,
                'update_existing' => $this->updateExisting,
                'replace_interests' => $this->replaceInterests,
                'send_welcome' => $this->sendWelcome,);

i tried to just add
"status" => "pending"

like with the Api v3, but this did not work.
i would like to check the docs if the naming was different back then but yeah...
thanks for reading by, help is much appreciated, have a nice one

A: these is no solution to this. the only way was to actually upgrade to a package supporting MailChimp Api v3 (or doing the implementation yourself)
have a nice one.


text:
Q: MongoDB sort using a custom function Let's say I have a collection that looks like:

{
  _id: 'aaaaaaaaaaaaaaaaaaaaaaaaa',
  score: 10
  hours: 50
},
{
  _id: 'aaaaaaaaaaaaaaaaaaaaaaaab',
  score: 5
  hours: 55
},
{
  _id: 'aaaaaaaaaaaaaaaaaaaaaaaac',
  score: 15
  hours: 60
}

I want to sort this list by a custom order, namely

value = (score - 1) / (T + 2) ^ G

score: score
T: current_hours - hours
G: some constant

How do I do this? I assume this is going to require writing a custom sorting function that compares the score and hours fields in addition to taking a current_hours as an input, performs that comparison and returns the sorted list. Note that hours and current_hours is simply the number of hours that have elapsed since some arbitrary starting point. So if I'm running this query 80 hours after the application started, current_hours takes the value of 80.
Creating an additional field value and keeping it constantly updated is probably too expensive for millions of documents.
I know that if this is possible, this is going to look something like

db.items.aggregate([
    { "$project" : {
            "_id" :  1,
            "score" : 1,
            "hours" : 1,
            "value" : { SOMETHING HERE, ALSO REQUIRES PASSING current_hours }
        }
    },
    { "$sort" : { "value" : 1 } }
])

but I don't know what goes into value

A: I think value will look something like this:
      "value": {
        $let: {
          vars: {
            score: "$score",
            t: {
              "$subtract": [
                80,
                "$hours"
              ]
            },
            g: 3
          },
          in: {
            "$divide": [
              {
                "$subtract": [
                  "$$score",
                  1
                ]
              },
              {
                "$pow": [
                  {
                    "$add": [
                      "$$t",
                      2
                    ]
                  },
                  "$$g"
                ]
              }
            ]
          }
        }
      }

Playground example here
Although it's verbose, it should be reasonably straightforward to follow. It uses the arithmetic expression operators to build the calculation that you are requesting. A few specific notes:

*

*We use $let here to set some vars for usage. This includes the "runtime" value for current_hours (80 in the example per the description) and 3 as an example for G. We also "reuse" score here which is not strictly necessary, but done for consistency of the next point.

*$ refers to fields in the document where $$ refer to variables. That's why everything in the vars definition uses $ and everything for the actual calculation in in uses $$. The reference to score inside of in could have been done via just the field name ($), but I personally prefer the consistency of this approach.


text:
Q: How to delete all existing edge and re-insert them from a CSV file Currently I am using Neptune's bulk loader to load data from CSV to Neptune database using Python. I was getting only modified records. So I was only inserting the data.
Now the file contains full/historical records and the requirement is to delete all existing edges for a given record in the CSV file and reload all the edges from CSV file. I was thinking of deleting all edges based on certain property from the DB and then call the Neptune's bulk loader method.
I have multiple (different labels) edges which are loaded from CSV files (kept in a s3 bucket). So I might have to delete multiple edges before I can start loading CSV files.
However if I delete the edges and then CSV bulk load fails, I will have no way to get back the deleted data.
How do I make sure my delete and bulk insert happens within a transaction block? Do we have such option in Neptune? I am using Python Gremlin.

A: TLDR; No, You can not do this in Neptune.
Though you can achieve this through series of steps.

*

*Take snapshot of the database.

*Initiate edge deletion.

*Initiate bulk load.

If the bulk load finishes successfully then you are good.
However, if the bulk load fails then, you can use snapshot taken in step 1 to spawn a new cluster which has same data as before.
Obviously, this solution assumes you are fine with downtime introduced while spawning a new cluster and your application getting updates about this new cluster endpoint.


text:
Q: output in html rails passed value i have the fallowing code :
<%= link_to 'Get started now !',play_path ,:alert => 'Eroare bla bla bla',:notice => 'E ok'  %>

How can i output in html on the 'play_path' page the :alert value ?
my controller looks like this
  def index
    @alert = flash[:alert]
    @notice = flash[:notice]

    end

and in my view i have
<%=@alert %>

It just doesn't display anything , but if in my controller i modify @alert = :blablabla , it displays in my view "blablabla"

A: In your link:
<%= link_to 'Get started now !',play_redirect_path ,:alert => 'Eroare bla bla bla',:notice => 'E ok'  %>

In your controller
def redirect
   redirect_to play_path, :alert => params[:alert]
end

def show
   @alert = flash[:alert]
end

In your view
<%= @alert %>

You will also need to set up a route in your config routes.rb
match "play/redirect" => "plays#redirect"