text:
Q: How to close all other submenus? I have a navbar with a fullscreen dropdown menu. onClick I want to open a dropdown menu and if another dropdown is already open I want to close the other menu's.
Here is a bit of my code:
Javascript:
$(".sub-link").click(function(){
   $(this).children(".navigation-container, a, .navigation-overlay").toggleClass("active");
   $(this).children(".navigation-container, .navigation-overlay").fadeToggle(250);
});

Html:

Home

Voor de kinderen

Voor de ouders

Over de school

Over de school

 Onze school in beeld

 Teamfoto

 Even voorstellen

 Onze school in beeld

 Teamfoto

 Even voorstellen

 Onze school in beeld

 Teamfoto

 Even voorstellen

Fotogalerij

Nieuws

Contact

I already tried some thing with siblings() and .not(this) but I can't get it to work.
Thanks!

A: Did you tried remove all .active before toggleClass?
$(".sub-link").click(function(){
   $(this).children(".navigation-container.active,
                      a.active,
                     .navigation-overlay.active").removeClass("active");
   $(this).children(".navigation-container, a, .navigation-overlay").toggleClass("active");
   $(this).children(".navigation-container, .navigation-overlay").fadeToggle(250);
});

A: You only need to toggle .navigation-container and use css to set .navigation-container{display:none} but .navigation-container.active{display:inline}
$(".sub-link").click(function(){
       $(this).children(".navigation-container").toggleClass("active");

    });

See fiddle here: https://jsfiddle.net/xn0t4b9f/1/
To do the fading just change the JQuery a bit:
$(".sub-link").click(function(){
$(".navigation-container").removeClass("active");
$(this).children(".navigation-container").fadeToggle("active");
});


text:
Q: Prove concavity without testing the second derivative.. Consider a function $F(L)=(L-L^2a)T^{L-1}$, where $0<L<\frac{1}{a}$.
The constants $a$ and $T$ may take values over $]0,1[$ and $[0.01,0.1]$, respectively.
The first derivative of $F$: $\frac{dF}{dL}=(L^2+L(\frac{2}{\log(T)}-\frac{1}{a})-\frac{1}{a\log(T)}) T^{L-1}$.
$\frac{dF}{dL}=0$ $\implies$ $L_1=\frac{   (\frac{1}{a}-\frac{2}{\log(T)})- \sqrt{ (\frac{2}{\log(T)}-\frac{1}{a})^2+\frac{4}{a\log(T)} }    }{ 2  }$,
$L_2=\frac{   (\frac{1}{a}-\frac{2}{\log(T)})+ \sqrt{ (\frac{2}{\log(T)}-\frac{1}{a})^2+\frac{4}{a\log(T)} }    }{ 2  }$.
$L_2>\frac{1}{a}$, so $L_2$ is rejected.
Is it possible to prove that $F(L)$ is concave by just saying that $F(L)$ is an increasing function for $L<L_1$ and a decreasing one for $L>L_1$?

A: What you state shows that $L_1$ is the maximum, but it does not imply that $F$ is concave.
In fact, $F$ is not concave on the entire interval $(0,1/a)$. Note that
$$F''(1/a) = -2 \log(T) - 2a > 0,$$
since $T < e^{-a}$. So there is a point of inflection between $L_1$ and $1/a$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Save reference to Lua's userdata #1 Lua:
local test = Test();

#2 C:
//creating "lua's test"
luaL_newmetatable(L, "someTable");
lua_userdata *userData = (lua_userdata *)lua_newuserdata(L, sizeof(lua_userdata));

luaL_getmetatable(L, "someTable");
lua_setmetatable(L, -2);

#3 Lua:
function test.newMethod()
end

#4 C:
//this part is not executed from Lua
//what i have to have here from #2 to call "test.newMethod" and how to call it?
//if userdata would be on stack i guess i could:
luaL_getmetafield (L, 1, "newMethod");
lua_call(L, 0, 0);
//but because this part is not executed by Lua call its not on stack.

Edited:
will try to explain simpler in pseudo code:
Lua:
local test = Object();

C:
int Object(){
    ...
    somePointer = luaL_newmetatable(...); //how to get this "somePointer"? maybe luaL_ref?
    push ...
}

Lua: makes new method
function test.newMethod()
    ...
end

In C some event (lets say timer) triggers C method
void triggeredCMethod(){
    //here i need to call test.newMethod
    //if i would have here 'somePointer' and could push it to Lua stack i could find and call newMethod
}

so question is: how in C store pointer to some Lua object (hope i need that), get Lua object by that pointer and call method in it

A: I'm assuming you want to be able to call dynamically added functions. This code should explain it relatively simply. Note I don't do much error checking and make a few assumptions, don't copy paste this as a solution.
typedef struct
{
    int number;
    int reference;
    lua_State *L;
} TestUserdata;

static int m_newindex( lua_State *L )
{
    /* This is passed three values, first ( at -3 ) is the object, bring this to the front */
    lua_getfenv( L, -3 );
    /* Now bring the second arg forward, the key */
    lua_pushvalue( L, -3 );
    /* And the third arg, the value */
    lua_pushvalue( L, -3 );
    /* And we're done */
    lua_rawset( L, -3 );

    return 0;
}

static int m_tostring( lua_State *L )
{
    lua_pushstring( L, "TestUserdata" );
    return 1;
}

static int callobject( lua_State *L )
{
    /* Grab the object passed, check it's the right type */
    TestUserdata *data = luaL_checkudata( L, 1, "TestUserdata" );

    /* Grab the function environment we gave it in createobject, and look in there for newmethod */
    lua_getfenv( L, -1 );
    lua_pushstring( L, "newmethod" );
    lua_rawget( L, -2 );

    /* Call the function */
    lua_pushinteger( L, data->number );
    lua_call( L, 1, 0 );

    return 0;
}

static const struct luaL_reg userdata_m[] = {
    { "__newindex", m_newindex },
    { "__tostring", m_tostring },
    { NULL, NULL }
};

int main (int argc, char *argv[])
{
    lua_State *L = luaL_newstate();
    luaL_openlibs( L );

    /* Let's create us a userdatum metatable, and fill it up with goodies */
    luaL_newmetatable( L, "TestUserdata" );
    /* Use luaL_register to fill up the metatable for us */
    luaL_register( L, NULL, userdata_m );
    lua_pop( L, 1 ); /* Clean up the stack, we won't need the metatable left here */

    TestUserdata *data = lua_newuserdata( L, sizeof( TestUserdata ) );
    lua_pushvalue( L, -1 ); /* Copy for luaL_ref */
    int ref = luaL_ref( L, LUA_REGISTRYINDEX );
    data->reference = ref;
    data->number = 42;
    data->L = L;

    /* Load the metatable from before and 'give' it to this userdatum */
    luaL_getmetatable( L, "TestUserdata" );
    lua_setmetatable( L, -2 );

    /* Give this object an empty function environment */
    lua_newtable( L );
    lua_setfenv( L, -2 );

    lua_setglobal( L, "test" );

    luaL_dostring( L, "function test.newmethod( num ) print( num ) end" );

    /* Now provided we have the object, we can call any method defined anywhere */
    lua_rawgeti( data->L, LUA_REGISTRYINDEX, data->reference );
    lua_getfenv( data->L, -1 );
    lua_pushstring( data->L, "newmethod" );
    lua_rawget( data->L, -2 );
    lua_remove( data->L, -2 );

    if( lua_isfunction( data->L, -1 ) == 1 )
    {
        lua_pushinteger( data->L, data->number );

        lua_pcall( data->L, 1, 0, 0 );
    }

    lua_close( L );

    return 0;
}

Check that, I think that's what you're after.

A: If all you want is to call the Lua function `test.newMethod()', then I think you want something on the order of this:
lua_getglobal(L, "test");
lua_getfield(L, -1, "newMethod");
lua_call(L, 0, 0);

I don't think you need to mess with a metatable or a userdata.
However the force of your question is not entirely clear to me...


text:
Q: why raster doesn't always print all information of a brickRaster? [r] I am using the package raster to read ncdf files, everything works fine aside from the behavior that I get when I just type the brickRaster name.
#load a .nc file
temp=brick(temp.nc)

temp
class       : RasterBrick
dimensions  : 180, 360, 64800, 2928  (nrow, ncol, ncell, nlayers)
resolution  : 1, 1  (x, y)
extent      : 0, 360, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84
data source : /fhgfs/data/work/crct/bfb16057/pgf/1.0deg/3hourly/tas_3hourly_1948-1948.nc
names       : X1948.01.01.00.00.00, X1948.01.01.03.00.00, X1948.01.01.06.00.00, X1948.01.01.09.00.00, X1948.01.01.12.00.00, X1948.01.01.15.00.00, X1948.01.01.18.00.00, X1948.01.01.21.00.00, X1948.01.02.00.00.00, X1948.01.02.03.00.00, X1948.01.02.06.00.00, X1948.01.02.09.00.00, X1948.01.02.12.00.00, X1948.01.02.15.00.00, X1948.01.02.18.00.00, ...
Date/time   : 1948-01-01 00:00:00, 1948-12-31 21:00:00 (min, max)
varname     : tas
level       : 1

but when I reload the workspace and just directly type temp and let R load the libraries, I only get these info
temp
Loading required package: raster
Loading required package: sp
class       : RasterBrick
dimensions  : 180, 360, 64800  (nrow, ncol, ncell)
resolution  : 1, 1  (x, y)
extent      : 0, 360, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84

and there is no way to get it to display the other information, I have to restart the session and load first library(raster). Another issue is that sometimes it displays min/max, and sometimes it doesn't, and sometimes the formatting it's all wacky (here it shows fine but in my R). Here is a brick I create using the setValues function when I lost all layer names.
>temp
class       : RasterBrick
dimensions  : 180, 360, 64800, 2928  (nrow, ncol, ncell, nlayers)
resolution  : 1, 1  (x, y)
extent      : 0, 360, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84
data source : /tmp3/RtmpHJiJol/raster/r_tmp_2016-08-18_123238_52879_95962.grd
names       :      layer.1,      layer.2,      layer.3,      layer.4,      layer.5,      layer.6,      layer.7,      layer.8,      layer.9,     layer.10,     layer.11,     layer.12,     layer.13,     layer.14,     layer.15, ...
min values  : 1.786824e-09, 1.786824e-09, 1.786253e-09, 1.785112e-09, 1.773258e-09, 1.377443e-09, 1.369023e-09, 2.394694e-09, 2.461454e-09, 2.507693e-09, 2.537011e-09, 2.585615e-09, 2.623897e-09, 2.651393e-09, 2.654030e-09, ...
max values  :     1.000675,     1.000675,     1.000675,     1.000675,     1.000671,     1.000674,     1.000672,     1.000668,     1.000675,     1.000675,     1.000672,     1.000675,     1.000655,     1.000675,     1.000671, ...

A: Saving and reloading a workspace is bad practice. It creates a lot of problems, and it is unfortunate that R suggests you to do that. Instead, in each session you should start from scratch using a script to reproduce what you need. If that takes a lot of time, then save intermediate files to disk.
min and max values are shown if they are known (provided by the file). Standard ncdf files do not provide this information.
The loss of layer names after setValues is not a display issue (and it could be considered a feature, not a bug). Here is houw that works:
library(raster)
r <- raster(ncol=10, nrow=10)
vals <- 1:ncell(r)
r[] <- vals
s <- stack(r,r)
names(s) <- c('a', 'b')

setValues sets new layernames based on the matrix it gets.
x <- setValues(s, cbind(vals, vals))
names(x)
#[1] "vals.1" "vals.2"

You can of course change them
names(x) <- names(s)
#[1] "a" "b"
names(x)

Or alternatively, provide them by naming the columns of the matrix:
x <- setValues(s, cbind(a=vals, b=vals))
names(x)
#[1] "a" "b"

I cannot comment on wacky formatting if you do not show it.


text:
Q: Hua Wei matebook e 2022 with Ubuntu 20.04 only works with nomodeset I have to use the nomodeset parameter to use Ubuntu 20.04; if I do not use the parameter, my screen will be blank white and twinkle.
My graphics device is an Intel Iris Xe, Cpu is i5-1130G7.
Using nomodeset causes the backlight controller to not work and graphics drivers not use Intel graphics drivers, How can I fix this?
I used all the solutions I can google, but it still does not work. Could it be a kernel error or BIOS drivers error?

A: Similar problem here, with a Matebook E 2022 with I7 CPU and also with Iris XE graphics. Booting Linux (Deepin, which is Debian-derived) with modesetting is not possible. I have to use either "nomodeset" or "i915.modeset=0" kernel parametter.
I have tried several kernel versions, some provided by the Deepin distro (5.15.24, 5.15.34) as well as some newer ones that I built from kernel.org sources (5.17.11, 5.18.6).
The newest kernel version I tested was 5.18.6.
The result is always the same. Enabling modesetting crashes the kernel. The screen goes black (probably the result of an unsupported mode being applied) and then the computer freezes and does not react to anything any more, also no more HDD activity. There may be (or not) a "kernel panic", but it's not visible because the screen is black. No reboot happens. The only way out is by long-pressing the power key to force a power-off.
With either "nomodeset" or "i915.modeset=0", the kernel boots and the rest of the Deepin system appears functional. However, the internal display panel brightness cannot be changed (always at maximum, which is eye-unhealthily bright) and external monitors are not recognized at all.
Something seems to be broken in the i915 driver (or in some configuration table from the BIOS that the i915 driver attempts to use) which causes the driver to crash and lock up the kernel during boot.

A: I have Matebook x pro 2022 with ubuntu then causing flicking, I used to fix this with:
sudo vim /etc/default/grub
add GRUB_CMDLINE_LINUX="i915.enable_psr=0"
sudo update-grub

Hope this can help. Btw I am doing research about installing ubuntu in Matebook E 2022 too. :)
Update:
Seems some of Chinese users have solved this Iris issue by upgrading kernel to 6.0.X, but there is still issue when moving mouse.


text:
Q: How to add a NOT NULLABLE column with a foreign key to an existing table that already contains data? An example for this problem:

Imagine you have a table projects. The table projects already
  contains data. Now you want to add a project_type_id column to the
  table, that can't be NULL and has a foreign key to the project_types
  table.
The database sees the project_type_id can't be NULL, so it inserts a
  0 in the column for all the existing rows. The 0 does not exist in
  the project_types table, so the foreign key constraint fails. This
  means you can't add the foreign key.

I thought about adding a first "default" row to the project_types table and link all the projects to that type. This isn't a good solution, because the user has to change all the types from "default" to the correct type.
What is your solution for this problem?

A: I think the best way to solve this issue is:

*

*Create a new migration in order to add project_type_id column to projects table:

php artisan make:migration add_project_type_column_to_projects_table --table=projects

 public function up()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->integer("project_type_id")->unsigned();
    });
}

public function down()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->dropColumn("project_type_id");
    });
}

It's going to add 0 value as default in each column but no problem because it's not foreign key yet.

2.Define the relationship between Project and ProjectType models

//Your Project class

class Project extends Model
{
 protected $fillable=["your columns..."];

 public function type()
  {
    return $this->belongsTo(ProjectType::class);
  }
}

//Your ProjectType class

class ProjectType extends Model
{
  protected $fillable=["Your columns..."];

  public function projects()
  {
    return $this->hasMany(Project::class);
  }
}

*Now you must go and set the correct values for project_type_id either manually or from your admin panel.

*Now your column is ready to be set as foreign key, so go ahead and make a new migration to set the project_type_id as foreign key.

php artisan make:migration set_project_type_id_column_as_foreign_key --table=projects

public function up()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->foreign("project_type_id")
            ->references("id")
            ->on("project_types")
            ->onDelete("cascade")//is up to you
            ->onUpdate("cascade");// is up to you
    });
}
 public function down()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->dropForeign("projects_project_type_id_foreign"); //This one could be different
    });
}

Now your table has a new (NOT NULLABLE) foreign key with correct values.

A: You should have a valid foreign key that exists in DB, for example: 1
Then Create a new migration :
$table->integer('project_type_id')->unsigned()->default(1);
$table->foreignkey('project_type_id')->references('id')->on('project_types');

Then user has to manually change every one of them or change them randomly (random valid ids) with foreach.

A: I think one workaround here would be to first add the new column without a foreign key reference.  Then update the values of that column, and afterwards add the foreign key constraint.  Something like this:
ALTER TABLE projects ADD COLUMN project_type_id INT;

-- now update with correct values

ALTER TABLE projects ADD CONSTRAINT fk_pt_id FOREIGN KEY (project_type_id)
REFERENCES yourTable(parent_id);

A: If you have to deploy to different environments, you could add a default value to the project_type_id (as @Ahmad Mobaraki suggested). Of course, you must have that value in the project_type table.
Then, create an Artisan command that fetches all rows and that updates the project_type_id to the right value, according to your business logic.
Finally, after running the migration, run that Artisan custom command.
At this point, you have a non-nullable foreign key with the right values.
I had the same issue (yes, I know, 2019) and solved that way. After deployment in other environments, just run the update script.
I use to create Artisan commands that are run manually after the automated deployment. Most of the time, automated deployments are just fine, but when there are some tasks like this, the best solution I have found is to have a custom Artisan command that handles that extra work.
Other solution I have explored in the past is to handle that updating in the same migration file, but that mixes things up. Database structure and data, and, on top of that, it assumes the database has data. With this approach, even when it is not fully automated, you have a clear separation between structure and data.


text:
Q: Razor, partials and slow performance I have some complex pages that make use of many RenderPartial (from 13 up to 20).
I've found that those pages are taking from 400 - 800ms to render (that's just for the view rendering time. Action time is not included and it is not an issue).
There are no queries/anything else on the pages, they just render a pre-loaded model. If I "glue" all the partials on each page, I can cut those times to 1/4. That's a lot of time.
Precompiling the pages do not solve anything, as that only impacts the startup time of the page. But the generated code it's the same.
My question then is: Is there a way I can, via some external tool, to "replace" those RenderPartials with the actual code from the partial? Maybe I can even run that tool on deploy only. After all, those partials are only used on specific pages and they do not need to be accessed from other actions as standalone views...


text:
Q: Active slider only in small resolution i'm building a responsive website, whith a couple of 'prices & plans' of the service. But, in small resolutions, there is a lot of information to show. So i want to use a slider and show each 'prices & plans' in a single slider. The problem is, because of the way slider works (insert other divs on the window load) the slider is not activating. Does anyone knows another way to do this?
This is what i was trying to do with Jquery:
$(document).ready(function() {

    $(window).load(function() {
        getWidthAndHeight();
    });
    $(window).resize(function() {
        getWidthAndHeight();
    });

   if ($(window).width() < 768) {
        $('.e-price-sh').addClass('slider');
    } else {
        $('.e-price-sh').removeClass('slider');
    };

)};

Ps.: I was able to get the result i want, but i have to blocks of code in my html, one of them is with a class hidden for res. bigger than 768 and the other with class hidden for res. smaller than 768
This is the html, i want to append the slider with the  e-price-sh class:

Prices & Plans

        ...

        ...

        ...

        ...

        ...

A: Use media query to Achieve:
.e-price-sh{display:none;}

 @media screen and (max-width:768px) {
    .e-price-sh{display:block;}
}

What's more:
if you use Foundation. There is a class named: .show-fow-small-only to resolve it quickly.


text:
Q: Submitting same URL (with different content) to Google in different languages I've submitted my web page to Google using the webmaster tools and after a few weeks I've correctly seen it in search results. Now the question: my page uses language detection via Apache wizardry so that the page is served in the relevant language based on the browser settings (via AddLanguage and LanguagePriority for those who want to know...) and it can be retrieved by simply using host/folder/page while the actual page sits at host/folder/page.<lang>.html and I obviously want to index the simpler URL instead of the actual html one because that way it's "independent" of language.
How do I submit the same URL to different Google countries or is the "generic" (English) crawler smart enough to index it by automatically using multiple language settings when retrieving the page?
You can test the page at:
http://www.nicealias.com/articles/focus_on_renewables.en.html
by replacing .en with .fr and by optionally removing .html and the language extension too
(as in http://www.nicealias.com/articles/focus_on_renewables)


text:
Q: Server TCP provider has stopped listening on port [ 1433 ] due to a failure. Error: 0x2726 Recently on one of our SQL Server we have faced below issue

Log Name:      Application
  Source:        MSSQLSERVER
  Date:          6/28/2017 12:33:51 AM
  Event ID:      26040
  Task Category: Server
  Level:         Error
  Keywords:      Classic
  User:          N/A
  Computer:      Host1
Description:
  Server TCP provider has stopped listening on port [ 1433 ] due to a failure. Error: 0x2726, state: 1. The server will automatically attempt to reestablish listening.

Various links https://social.msdn.microsoft.com/Forums/sqlserver/en-US/44a4b4b2-f418-460e-805d-85e445db982f/how-to-resolve-this?forum=sqlgetstarted
Related to this error suggests that the most probable cause for this issue is Higher Disk I/O. but in our case, we have verified that Disk I/O which remains always normal on this server, we have reviewed the data from New relic as well when this incident was occurred.
Is there anyone having any idea about what should we investigate beside Disk I/O? as this is not being cause in our case


text:
Q: Assign default value to first dropdown element I have dropdown in my view
Here is code of dropdown

    {{l("LandlordType")}}

Here is how I populate it
I send request to server and get all landlord types
getLandlordTypes(): void {
    this._landlordTypesService.getLandlordTypesDropdownValues().subscribe(result => {
        result.items.forEach(value => {
            this.landlordTypes.push({ label: value.name, value: value.id });
        });
        this.landlord.landlordTypeId = result.items[0].id;
    });
}

and call this method in ngOnInit
ngOnInit(): void {
    this.getLandlordTypes();
}

But when I open modal with this dropdown my first element got id = 0, instead of 11 for example. As I understood I need to push default value somehow to it. How I can do this?

A: Hmm.. Looks like you got your bindings wrong. Your dropdown options values should be binded entire object.
You should replace
this.landlord.landlordTypeId = result.items[0].id;

With
this.landlord = result.items[0];

This is how getLandlordTypes() method should look like:
getLandlordTypes(): void {
  this._landlordTypesService.getLandlordTypesDropdownValues().subscribe(result => {
    result.items.forEach(value => {
      this.landlordTypes.push({ label: value.name, value: value.id });
    });
    this.landlord = result.items[0];
  });
}

And on your HTML, use set your 2-way data bindings to [(ngModel)]="landlord instead.

  {{l("LandlordType")}}


text:
Q: How can I edit a file on a GPT partition, SLAX linux I have installed ESXi v5.5 on a white box and need to insert a particular parameter into the boot.cfg file. I created a bootable USB drive (SLAX Linux) and can see the device /dev/sda, but can't mount it.
Using parted I can list the partitions on the disk - and can see the partition I want to access, but can't figure out how to gain access at the file level so I can edit the boot.cfg file.
Any suggestions?

A: You need to mount a filesystem to access files on it, same as always.
Does the kernel recognize the partitions, e.g. have partition device files like /dev/sda1 been created?  If so, the fact that it's GPT is irrelevant; just mount the partitions as usual.  If not, your kernel may lack GPT support.


text:
Q: Plotly Express borders/outlines on map (Python) I am trying to remove the borders in a plotly choropleth map, but I can't find the property to do this.
fig = px.choropleth(df, geojson=counties, locations='fips', color=d2, template="ggplot2", scope="usa")

Results in a map that looks like the image below. I'm trying to remove the hard black borders. How can I do this?


text:
Q: Dataclass not inheriting __eq__() method from its parent I have a parent dataclass and a sub-dataclass inherits the first class. I've redefined __eq__() method in parent dataclass. But when I compare objects sub-dataclass, it doesn't use the __eq__() method defined in parent dataclass. Why is this happening? How can I fix this?
MWE:
from dataclasses import dataclass

@dataclass
class A:
    name: str
    field1: str = None

    def __eq__(self, other):
        print('A class eq')
        return self.name == other.name

@dataclass
class B(A):
    field2: str = None

b1 = B('b', 'b1')
b2 = B('b', 'b2')
print(b1 == b2)

A: By default, the dataclass decorator generates an __eq__ method for the decorated class. To disable this (allowing B to inherit A.__eq__), you need to adjust the decorator.
@dataclass(eq=False)
class B(A):
    field2: str = None

A: The @dataclass decorator adds a default __eq__ implementation.
If you use
@dataclass(eq=False)

on class B, it will avoid doing that.
See https://docs.python.org/3/library/dataclasses.html


text:
Q: How to get element value using c# XML file:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<content>
      <FingerPrintUserDetails>
        <UserID>e57645</UserID>
        <UserName>Jill</UserName>
        <FPData>AQAAABQAAAD0AAAAAQASAAEAWgAAAAAA8AAAAHfrWpB6BHZBL10voxpdxu2Km5XVNh*oUNC80Rvpql3RhlqOiBPeet6iRPwb/BdN1fCF4Y/WHbQ40*mqoUKqilgN7bUqNuXP7M299HUWtoAGEO3nDKXXAnHd7dgytZbmHVv*mRBPJDSRw9VY/R1yOIu2cCDlLM*F8Q1lvTfMFDdfwNZynI0e2ZauCF58f0UX56XLFBallaAauxP5mvvhUmcmc6ITg7RhH9wc4181kgPjCuZg38pQepE5U07XIa3hQP8fwxPzdprifXECgB1Z3pTXWQP0q4ZD0Inlbq6Gszo1ucPrhQA0jYQRXtJUVuyBeg</FPData>
        <Address>Pune</Address>
        <ContactNo>848488484884</ContactNo>
      </FingerPrintUserDetails>

      <FingerPrintUserDetails>
        <UserID>444</UserID>
        <UserName>John</UserName>
        <FPData>AQAAABQAAADkAAAAAQASAAEAZAAAAAAA4AAAAPLnmQ8FymAAHWYutR5pdtYvfDVmjsqLeli8tOSTFAtw6AkfA0r8XwrMzp9jFZJI7DlBk4G94BMq55gPEG7uBLZUNYrvhv0jDlDFMOjWGJ9RoWekFveTC*oZ7Tq/xmxuvY6FzLHVo*xzdKQI73Y0f9/eeMC0OgqnbQ3I0IP6cTkkKnTUZJOXKr7IFPHkjJAvCDmU7ec4vG50JHdBJIObmbzVcO0huTUQyE7CR1qYkUjmNFKgVKWPLRupEk4l/Ek0BuAba*9JlhBVUHzZuKbDQLc9lTFwevAgDuuAwxfZaLS*</FPData>
        <Address>nagpur</Address>
        <ContactNo>464645763</ContactNo>
      </FingerPrintUserDetails>

      <FingerPrintUserDetails>
        <UserID>5555</UserID>
        <UserName>Jack</UserName>
        <FPData>AQAAABQAAAAEAQAAAQASAAEAZAAAAAAA9AAAAPz5mQO3uTeXLfU5Mb74XbCX5rERGZFPQMVG1vPpX87306O5oURlYiIe5dasJ2S8NlBZu2UU3zaUpNnB7viYDB6*wfFlgtopn/WdbXW0Yhik3hj8nDreEmaK12To8qfAJx2ooq43i0wBIL*0Jkba*QpHIprSajrhnCg1PjOLMP37sEauJUwXJaoDR/PPQYIxTFE5kf8xzGlJmqiGejD*Y8R3ewU9yIrxkdQ0S//LCdacULt2QvS/I3APo/j0FAgSCOU3SBLdDL6UBPD4fLeEzo7uUIW8gUMThzZX*u2iUuNwJdqWC2NsFtWkUWt03sz3xYQpR8pLA4vrsUmldzUMWe8</FPData>
        <Address>beed</Address>
        <ContactNo>5745745747</ContactNo>
      </FingerPrintUserDetails>

    </content>

C#:
XmlDocument doc = new XmlDocument();
doc.Load("E://BioEnable_Project//fp_project_using_xml//fp_project_using_xml//Capture_Data.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("FPData");
foreach(XmlElement node in nodes)
{
    MessageBox.Show(node.Value);
}

I have to check FPData value on each node..i use above code but not  getting..

A: In your XPath, provide the full path to the node.
XmlNodeList nodes = root.SelectNodes("/content/FingerPrintUserDetails/FPData");

What is happening is that there is no direct FPData node under the document root.

A: XmlNodeList nodes = root.SelectNodes("content/FingerPrintUserDetails");

it will return array of FingerPrintUserDetails, then find FPData in them
XmlNodeList res = nodes[index].SelectNodes("FPData");

A: Using LINQ to XML:
 XDocument doc = XDocument.Load("XmlFilePath");
 var selectors = from elements in doc.Elements("content").Elements("FingerPrintUserDetails")
                 select elements;

foreach (var element in selectors)
 {
    MessageBox.Show(element.Element("FPData").Value);
 }

A: XmlDocument doc = new XmlDocument();
doc.Load("E://BioEnable_Project//fp_project_using_xml//fp_project_using_xml//Capture_Data.xml");
XmlNodeList lst =  doc.GetElementsByTagName("FingerPrintUserDetails");

foreach (XmlElement elem in lst)
{
    XmlNode pfData = doc.GetElementsByTagName("FPData")[0];
    MessageBox.Show(pfData.Value);
}


text:
Q: JSON from Snowflake 2 This is a modification of my question in JSON from Snowflake.  I couldn't find a way to edit that question or add to it.  I apologize for it if it is there.
Here is the new data that I am replacing the original data with:
insert into test
values ('{"value":
     {"evaluation_forms":
      [ {"evaluations":
       [ {"channel_meta":
          {"after_call_work_time": ["XXXX"],
           "agent_first_name": ["KATRINA"],
           "agent_hung_up": ["XXXXX"],
           "agent_last_name": ["COX"],
           "agent_unique_id": ["LO_00130604"],
           "agent_username": ["X"],
           "alternate_call_id": ["XX"],
           "total_time": ["XXX"]
          }

        } ]
    } ]
}
}'
);

Here is the query:
SELECT
--  v.value:make::string as make,
--  v.value:model::string as model,
--  v.value::string as "Extras Purchased",
    cm.value:channel_meta.agent_first_name,
    cm.value:channel_meta.agent_last_name,
    cm.value:agent_hung_up,
    cm.value:agent_unique_id,
    cm.value:agent_username,
    cm.value:alternate_call_id,
  cm.*
  FROM
  --  (select parse_json(src) src from stage.intuit_quality_raw_table) t
    (select parse_json(src) src from test) t
    , LATERAL FLATTEN(INPUT => SRC:value) v
    , LATERAL FLATTEN(INPUT => v.value) vv
    , LATERAL FLATTEN(INPUT => vv.value) ev
    , LATERAL FLATTEN(INPUT => ev.value) cm

I get the first and last name of the user (in the form of [" KATRINA"] and [" COX"]...why the spurious space?"), but everything else is null.
Why?
Thanks

A: Never mind, I found it.  I'm an idiot.  I say that all the time.  :)


text:
Q: RecyclerView getChildCount() and getItemCount() returns same value RecyclerView has an InfiniteScrollListener and inside that listener, in OnScrolled() method I calculate visible and total item count to check if new items should be loaded. When totalItemCount and visibleItemCount are the same, it causes an infinite loop of loading. The listener works flawlessly with my other RecyclerViews which does NOT have CoordinatorLayout or NestedScrollView as a parent.
I want to keep this structure because the customer won't accept a change.
I've got a fragment inside an activity that has a layout like this
CoordinatorLayout{
 NestedScrollView{
    RecyclerView{
    }
 }
}

sdk versions
compileSdkVersion 24
buildToolsVersion "23.0.3"
...
minSdkVersion 21
targetSdkVersion 24

fragment_profile.xml as parent layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:layout_behavior="com.paxotic.paxira.util.behavior.AppBarFlingBehavior">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="@dimen/app_bar_height_small"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#000000"
                app:layout_collapseMode="parallax">

                <ImageView
                    android:id="@+id/img_background"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:alpha="0.5"
                    android:scaleType="centerCrop"
                    tools:src="@drawable/bg_greeting_activity" />

            </RelativeLayout>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <include
        layout="@layout/activity_profile_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
       ... />

</android.support.design.widget.CoordinatorLayout>

fragment_profile.xml as child layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    ...

    <android.support.v7.widget.RecyclerView
        android:id="@+id/feedRecycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingBottom="@dimen/spacing_normal"
        tools:listitem="@layout/list_item_activity" />

    ...

</android.support.v4.widget.NestedScrollView>

ProfileFragment.java: relative function
private void init() {

    feedAdapter = new FeedAdapter(host);
    feedAdapter.setHasStableIds(true);

    LinearLayoutManager layoutManager = new LinearLayoutManager(host);
    feedRecycler.setLayoutManager(layoutManager);
    feedRecycler.setNestedScrollingEnabled(false);
    feedRecycler.setHasFixedSize(true);
    feedRecycler.setAdapter(feedAdapter);

    infiniteScrollListener = new InfiniteScrollListener(host, layoutManager) {
        @Override
        public void onLoadMore(int pageIndex) {
            if (!feedAdapter.isLoading) {
                loadFeed(pageIndex);
            }
        }
    };
    feedRecycler.addOnScrollListener(infiniteScrollListener);
}

InfiniteScrollListener.java
public abstract class InfiniteScrollListener extends RecyclerView.OnScrollListener {
    private int previousTotal = 0; // The total number of items in the dataset after the last load
    private boolean loading = false; // True if we are still waiting for the last set of data to load.
    private static final int VISIBLE_THRESHOLD = 5; // The minimum amount of items to have below your current scroll position before loading more.
    int firstVisibleItem, visibleItemCount, totalItemCount;

    private int current_page = 0;
    private int loadingItemCount;

    private LinearLayoutManager mLinearLayoutManager;

    public InfiniteScrollListener(Context context, LinearLayoutManager linearLayoutManager) {
        this.mLinearLayoutManager = linearLayoutManager;
        loadingItemCount = context.getResources().getInteger(R.integer.feed_pull_item_count);
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        if (dy < 0) return;        // check for scroll down

        visibleItemCount = mLinearLayoutManager.getChildCount();
        totalItemCount = mLinearLayoutManager.getItemCount();
        firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();

        synchronized (this) {

            if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + VISIBLE_THRESHOLD)) {
                // End has been reached, Do something
                current_page++;
                onLoadMore(current_page);
                loading = true;
            }
        }
    }

    public abstract void onLoadMore(int current_page);

    public void setLoading(boolean loading) {
        this.loading = loading;
    }

    @Override
    public void onScrollStateChanged(RecyclerView view, int scrollState) {
        // Don't take any action on changed
    }
}

A: you are getting the same values from getChildCount() getItemCount(), because the recyclerview will returns the total number of items/child.
you must override one of the method, as per your usage, to get the value you want.
Do this in your custom recyclerview adapter.
To do this, add this to your recyclerview adapter:
@Overide
public int getChildCount() {
//return your desired value here after obtaining it
}

A: You get the real count of views. If adapter has 15  items and ((LinearLayoutManager) myRecyclerView.getLayoutManager()).getChildCount() returns you 7, there is two items visible in view due to max height or static height value after you update new item its till persists same height.
The count of items in the model (adapter) and the count of views are not the same thing.
RecyclerView doesn't hold views for all 15 items in memory, it only has 7 in your case. When you scroll, it reuses those 7 views for displaying different items. The purpose of this is improving the rendering performance.
If you want to get 15, then you should use mAdapter.getItemCount() instead.

A: You shouldn't use recyclerView vertical in nestedScrollview.
For finding wich item to show on RecyclerView and start getting a new item
you can use your adapter. In the RecyclerView.Adapter<> you can override onViewAttachedToWindow():
@Override
public void onViewAttachedToWindow(@NonNull RecyclerView.ViewHolder holder) {
    super.onViewAttachedToWindow(holder);
    if ((getItemCount() - 1) == holder.getAdapterPosition()){
        Log.d(TAG,"list done");
        onLoadMore(current_page);
    } else {
        Log.d(TAG,"remain item : " + (getItemCount() - holder.getAdapterPosition() - 1));
    }
}


text:
Q: Unir arrays php alocando valores combinados entre as duas Tenho os seguintes arrays:
$corretor = array(
  'Carlos',
  'Andre',
  'Rosinei',
  'Vinicius',
  'Thales'
);
$comissao = array(
   5,
   3,
   3,
   3,
   2
);

Como faço para unir ambos, imprimindo resultado da seguinte forma:

Carlos - 5% | Andre  - 3% | Rosinei - 3% | Vinicius - 3% | Thales   - 2%

A: Partindo do principio que ambas as arrays têm o mesmo numero de elementos tens de criar uma maneira de iterar essas arrays e usar o index da iteração para usar dados de cada uma.
Se usares o array_map nem precisas de saber o index de iteração e podes misturar as duas diretamente assim:
function misturar($nome, $perc){
    return $nome.' - '.$perc.'%';
}

$c = array_map("misturar", $corretor, $comissao);
echo implode($c, ' | ');

Exemplo: https://ideone.com/ck4nFA
Apesar de neste caso achar mais simples com array_map, também podes fazer assim:
$res = '';
for ($i = 0; $i < count($corretor); $i++){
    $res.= $corretor[$i].' - '.$comissao[$i].'% | ';
}

echo substr($res, 0, -3);

Exemplo: https://ideone.com/TyoYzm


text:
Q: Converting pandas series timestamp to list of unique dates I have a column in pandas dataframe in timestamp format and want to extract unique dates (no time) into a list. I tried following ways doesn't really work,
1. dates =  datetime.datetime(df['EventTime'].tolist()).date()
2. dates =  pd.to_datetime(df['EventTime']).date().tolist()
3. dates =  pd.to_datetime(df['EventTime']).tolist().date()

can anyone help?

A: You can use dt to access the date time object in a Series, try this:
pd.to_datetime(df['EventTime']).dt.date.unique().tolist()
# [datetime.date(2014, 1, 1), datetime.date(2014, 1, 2)]

df = pd.DataFrame({"EventTime": ["2014-01-01", "2014-01-01", "2014-01-02 10:12:00", "2014-01-02 09:12:00"]})


text:
Q: Is there a JavaScript library that does Rijndael 256bit encryption like PHP? I've been extensively using Rijndael 256bit encryption in PHP for my API and would like to use it for my API wrapper that is written in JavaScript as well, but I've been unable to find a solution that gets the same result as in PHP.
By what PHP does I mean the following:
base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,$password,$secretInformation,MCRYPT_MODE_CBC,$iv));

and
base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,$password,$secretInformation,MCRYPT_MODE_EBC));

.. as well as the decryption variants.
I know that the many 256bit AES libraries don't get the same result that PHP does with its Rijndael 256bit encryption, thus I'm wondering if there is a library that is able to do what PHP does in the examples above?
Thanks!

A: MCRYPT_RIJNDAEL_256 is not AES with a 256 bit key, its basically "AES" with a 256 bit block size( AES normally has a 128 bit block size). Rinjdael had a bunch of options and was standardized into AES by reduces those options to just the 128 or 256 bit key size. As such, must libraries support the standard (AES) and not the prototype.
If you want AES 256 or 128 , which is what almost all libraries actually support, use MCRYPT_RIJNDAEL_128 with a 128 bit or 256 bit key. The difference in block size doesn't really make much of a difference security wise .
Also, using a raw password as a key is a really really bad idea. You get keys from a password by using a password based key derivation function like PBKDF2.


text:
Q: Memoization of functions with optional arguments Consider the following function that generates a sparse diagonal matrix:
W[n_] := W[n] = Exp[(2 Pi I)/n]//N;

Clear[X];

X[n_, L_, power_ : 1][i_, chain_] :=
  X[n, L, power][i, chain] =
    DiagonalMatrix@
     SparseArray@
       Table[
         W[n]^(-IntegerDigits[a, n, 2 L][[chain*L - i + 1]] power),
         {a, 0, n^(2 L) - 1}
       ]

Due to the f[x_] := f[x] = SlowFunction definition, I expect this code to be much faster on a second run. Indeed, if I evaluate the following on my laptop several times
X[3, 7][1, 1] // Timing

I get $12$ seconds on the first run then around $2.8$ seconds on any evaluation after that. Clearly the memoization trick seems to have made this faster, but it is still much slower than it should be. For example if I run
a = X[3, 7][1, 1]
a // Timing

I get $10^{-6}$ seconds. Running X[3, 7][1, 1] the second time should also be this fast, since the matrix is already computed and saved. But it seems that instead it is still doing some computation.
Why does this happen, and how could I avoid it so I can take full advantage of memoization to speed up my repeated calculations?

A: One way is to use multiple dispatch instead of optional arguments:
X[n_, L_, power_][i_, chain_] := X[n, L, power][i, chain] =
  DiagonalMatrix@SparseArray@
    Table[W[n]^(-IntegerDigits[a, n, 2 L][[chain*L-i+1]]*power), {a, 0, n^(2L)-1}]
X[n_, L_][i_, chain_] := X[n, L, 1][i, chain]

Here the memoization always happens in the full-argument form. Missing arguments are filled in by the multiple dispatch and forwarded to the full-argument form via delayed assignment.


text:
Q: Does $\log_a b = \log_\sqrt a \sqrt b$ can be a basic logarithm law? Does the following equation is true for all $ a,b\in{\mathbb R}$?
$$\log_a b = \log_\sqrt a \sqrt b$$
I have tried to proove this, and I didnt find any contradiction. Is it true?
EDIT
Thanks guys for the answers. I've just found a different proof without using $\ln$, for the record, here it is :
$$\log_\sqrt{a} \sqrt{b} = \frac{ \log_a \sqrt{b}}{\log_a \sqrt{a}} = \frac{\frac{1}{2} \log_a b}{\frac{1}{2} \log_a a} = \frac{\log_a b}{1} = \log_a b$$
Second EDIT
Is it true to generelize this rule, like this?
$$\log_{a^n} {b^n} = \frac{ \log_a {b^n}}{\log_a {a^n}} = \frac{n \log_a b}{n \log_a a} = \frac{n\log_a b}{n} = \log_a b$$

A: It's true for all positive $b$, $a \neq 1$ as
$$\log_\sqrt{a} \sqrt{b} = \frac{ \ln \sqrt{b}}{\ln \sqrt{a}} = \frac{\frac{1}{2} \ln b}{\frac{1}{2} \ln a} = \frac{\ln b}{\ln a} = \log_a b$$


text:
Q: How to determine the exact solution of a differential equation using variation of parameters? $$ \mathbf x'=\begin{pmatrix}
-3 & 1 \\
1 & -3 \\
\end{pmatrix}\mathbf x +
\begin{pmatrix}
1 \\
4t \\
\end{pmatrix}\\
\mathbf x_1= e^{-2t}\begin{pmatrix}
1 \\
1 \\
\end{pmatrix} \\
\mathbf x_2=e^{-4t}\begin{pmatrix}
1 \\
-1 \\
\end{pmatrix} \\
$$
I know that $\mathbf x_p(t)=\mathbf X(t)\int\mathbf X^{-1}\mathbf g(t)dt\\$
$$\mathbf X=[\mathbf x_1, \mathbf x_2]$$
By applying this formula I produced the following.
$$
\mathbf X=\begin{pmatrix}
1 & 1\\
1 & -1\\
\end{pmatrix}\\
\mathbf X^{-1}=\begin{pmatrix}
1/2 & 1/2\\
1/2 & -1/2\\
\end{pmatrix}\\
\begin{pmatrix}
1 & 1\\
1 & -1\\
\end{pmatrix}\int \begin{pmatrix}
1/2 & 1/2\\
1/2 & -1/2\\
\end{pmatrix}
*
\begin{pmatrix}
1 \\
4t \\
\end{pmatrix}dt=
\begin{pmatrix}
1 & 1\\
1 & -1\\
\end{pmatrix}\begin{pmatrix}
(t/2+t^2)+(t/2+t^2) \\
(t/2-t^2)+(-t/2+t^2) \\
\end{pmatrix}=\begin{pmatrix}
t+2t^2 \\
0 \\
\end{pmatrix}
$$
This answer is not correct, but I do not know where I am going wrong. Please help.

A: For:
$$ \mathbf x'=\begin{pmatrix}
-3 & 1 \\
1 & -3 \\
\end{pmatrix}\mathbf x +
\begin{pmatrix}
1 \\
4t \\
\end{pmatrix}\\$$
We have the homogeneous components:
$$\mathbf x_1(t) = e^{-2t}\begin{pmatrix}
1 \\
1 \\
\end{pmatrix} , \mathbf x_2(t) = e^{-4t}\begin{pmatrix}
1 \\
-1 \\
\end{pmatrix}$$
This gives us:
$$\mathbf X(t) =[\mathbf x_1(t), \mathbf x_2(t)] = \begin{pmatrix}
 e^{-2 t} & e^{-4 t} \\
 e^{-2 t} & -e^{-4 t} \\
\end{pmatrix}$$
$$
\mathbf X^{-1}(t)=\begin{pmatrix}
 \frac{e^{2 t}}{2} & \frac{e^{2 t}}{2} \\
 \frac{e^{4 t}}{2} & -\frac{e^{4 t}}{2} \\
\end{pmatrix}$$
$$\displaystyle \mathbf X_p(t)=\mathbf X(t)\int\mathbf X^{-1}(t)\mathbf g(t)dt = \begin{pmatrix}
 e^{-2 t} & e^{-4 t} \\
 e^{-2 t} & -e^{-4 t} \\
\end{pmatrix} \int \left(\begin{pmatrix}
 \frac{e^{2 t}}{2} & \frac{e^{2 t}}{2} \\
 \frac{e^{4 t}}{2} & -\frac{e^{4 t}}{2} \\
\end{pmatrix}.\begin{pmatrix}
1 \\
4t \\
\end{pmatrix}\right)dt$$
$$\mathbf X_p(t) = \begin{pmatrix}
 e^{-2 t} & e^{-4 t} \\
 e^{-2 t} & -e^{-4 t} \\
\end{pmatrix} .\displaystyle \int
\begin{pmatrix}
 2 e^{2 t} t+\frac{e^{2 t}}{2} \\
 \frac{e^{4 t}}{2}-2 e^{4 t} t \\
\end{pmatrix}dt = \begin{pmatrix}
 e^{-2 t} & e^{-4 t} \\
 e^{-2 t} & -e^{-4 t} \\
\end{pmatrix} .
\begin{pmatrix}
 \frac{1}{2} e^{2 t} \left(2 t-\frac{1}{2}\right) \\
 \frac{1}{2} e^{4 t} \left(\frac{1}{2}-t\right) \\
\end{pmatrix}$$
Hence:
$$\mathbf X_p(t) =
\begin{pmatrix}
 \frac{t}{2} \\
 \frac{1}{2} (3 t-1) \\
\end{pmatrix}$$
Recall:
$$\mathbf X(t) = \mathbf X_h(t) + \mathbf X_p(t) = c_1\mathbf e^{-2t}\begin{pmatrix}
1 \\
1 \\
\end{pmatrix} + c_2 e^{-4t}\begin{pmatrix}
1 \\
-1 \\
\end{pmatrix} + \begin{pmatrix}
 \frac{t}{2} \\
 \frac{1}{2} (3 t-1) \\
\end{pmatrix}$$


text:
Q: Can we use owasp zap for mobile application I'm trying to build a react native application,(mobile app). Can I use owasp zap for security testing. Or owasp zap only for website and web application.

A: Yes, see this FAQ which includes a video :) https://www.zaproxy.org/faq/can-zap-be-used-to-test-mobile-apps/


text:
Q: Does a query plan always give the same result order? For a query that has no order by clause, will a given query plan always return results in the same order? I understand that a different plan may be chosen, but if the same plan is chosen, will that give the same result order? Essentially, what freedom does the query executor have to reorder the rows when executing a given plan?

A: No, results won't be returned in the same order, even without a plan change.
The query executor does not have to reorder the rows, it doesn't even order them in the first place.
For example, when rows come in disk order:
CREATE TABLE o(id int);
INSERT INTO o VALUES (1),(2),(3);
ANALYZE o;
EXPLAIN SELECT * FROM o;
                   QUERY PLAN
-------------------------------------------------
 Seq Scan on o  (cost=0.00..1.03 rows=3 width=4)

SELECT * FROM o;

Result:

 id
----
  1
  2
  3

Let's update a row (without even changing the value):
UPDATE o SET id=2 WHERE id=2;

and rerun the same select:
SELECT * FROM o;

 id
----
  1
  3
  2

Notice how the order has changed. Of course the plan is still the same:
EXPLAIN SELECT * FROM o;
                   QUERY PLAN
-------------------------------------------------
 Seq Scan on o  (cost=0.00..1.03 rows=3 width=4)

Conclusion: the execution plan doesn't imply any order without order by.


text:
Q: Formulating an Linear Programming Assignment in pulp So, here's the context of what I am trying to solve:
I want to divide cost units into two or more companies. Now, I have it solved for two companies with the following objective function:
20*x1 + 30*x2 + 100*x3 + 20*x4 + 30*x5

with the variables being Binary type.
Suppose I get the optimized solution as:
x1 = 1
x2 = 0
x3 = 0
x4 = 1
x5 = 0

this means that Company A would be responsible for unit costs x1 and x4 and Company B with the rest of the costs.
This is working fine, and I have all coded on pulp correctly. I can also use constraints to limit the maximum cost for a particular company, which is the point of all this to begin with. The coefficients's sum represent the total cost of a given project. So I use that amount as constraint to the objective function to limit the cost of Company A
Now, what I want to do is the same thing with 3 or more companies. I have no idea how to formulate the objective function or functions, as I think that it might fall into a multi objective function problem, but I'm actually not sure.
I am not very experienced in Linear Programming, so I'm sorry if I have misplaced the question. I haven't found anything that could help me accomplish this.
I would put the code, but I have way more variables and some basic data preparation before creating the function, so I created a hypothetical example to make it easier to understand.
Thanks very much for any help.

A: You can define a binary variable as follows:
x_{i,j} = 1 if Company i is responsible for Unit Cost j

and add a constraint for each unit cost j telling that exactly one company must be responsible for that cost.
Consider the following example.
# data
companies = ["company1", "company2", ...]
products = ["prod1", "prod2", ...]
cost = {"prod1": cost1, "prod2": cost2, ...}

x = pulp.LpVariable.dicts("responsability",[(company, product) for company in companies for product in products], cat=pulp.LpBinary)
prob = pulp.LpProblem("ilp", pulp.LpMinimize)

# objective function - assuming the cost is the same for all the companies
prob += pulp.LpSum(cost[product] * sum(x[(company, product)] for company in companies) for product in products)

# each product assigned to one company
for product in products:
   prob+= pulp.LpSum(x[(company, product)] for company in companies) == 1

# additional constraints
...


text:
Q: How to declare field of type that extends some class? Consider following:
class Base{
}

class A extends Base{
}

class B {
}

now I want to have implementation (type) of Base wrapped into object
interface MyImpl{
   name:string;
   impl:any;
}

How to delcare impl instead of any so that following {name:"Aname", impl: A} will be valid while {name:"Bname",impl:B} will be invalid?

A: interface MyImpl {
   name: string;
   impl: typeof Base;
}

This way, Base and any class that extends it will be assignable to impl.


text:
Q: Why is my north arrow pixelated when being imported as emf? I've tried to import my own North Arrow with the Style Manager (ArcGIS 10.1) both as .emf and .bmp but the North Arrow is pixelated although the resolution of the picture should not cause this problem (i've saved the Arrow in a DinA3 file) and although the vetor format of the picture.
Has anyone an idea how to solve this problem?

A: Unfortunately, ArcMap's anti-aliasing capabilities are very limited. (See also the similar GIS.SE question about marker symbols being low-quality after .emf import.) Even if your high-quality symbol still exists, it is displayed crudely on screen.
This problem only arises during low-resolution display (in most cases during display of maps on a screen, but also if you export to low-resolution graphics). It should not occur if your map is printed in high resolution, exported as pdf file, or exported as high-resolution raster image.

*

*The most advanced way to avoid pixelated display of your north arrow / symbols is to use a custom font. (To render TrueType fonts, ArcGIS uses the anti-aliasing settings of your display, which can be configured in Windows.) This is probably tedious if you need to display a single symbol only. There is a question addressing common font editing tools if you want to dig deeper.
Note that fonts are monochrome by design; simple multi-color symbols are possible by stacking different layers within the Style Editor, but symbols with more sophisticated coloring may not be possible.

*If you are preparing a map for print or pdf export only, you may probably ignore the pixelated view which misses missing anti-aliasing because it occurs during map display within ArcMap only, but not after print or export to pdf - your full-quality vector symbol is preserved there.

*If your final product is a map for low-resolution display only, you can achieve quite good results by embedding your symbol (north arrow) as a raster graphic which has been designed for that particular low resolution. (You could export the custom vector symbol to a low-resolution raster, utilizing the anti-aliasing capabilities of your vector editing software.)
There are lots of cons to all of these methods, particularly (1) the high effort using ttf, (2) the coarse screen display by ignoring the issue, or (3) the coarse display of low-res raster graphics if viewed in higher resolution.
I would recommend the universal method using a ttf (see 1) if ignoring the issue (see 2) is not an option.
Probably you can also optimize the overall display of your .emf vector file. Note that the page size you mentioned is not relevant in order to determine the quality of a vector graphic. Avoid unnecessary vertices, make use of curved paths and choose appropriate line widths depending on the final display size. You may also consider to generalize high-level details in order to improve small-sized display of your symbol.
Note that there is a feature request on ArcGIS ideas and a support forum thread that both address the general (poor) anti-aliasing capabilities of ArcMap.


text:
Q: CheckBoxList Value gets overwritten by Text on DataBind ASP.NET web forms I have a CheckBoxList that I want to populate using a collection of ListItems with Text and Values defined.
var temp = types.Select(x => new ListItem(x["Description"].ToString(), x["TypeCode"].ToString()));
chbox.DataSource = temp;
chbox.DataBind();

The ListItems in temp have the correct Text and Value property values, but after chbox.DataBind(), all of the Value properties are populated with the Text property value.
So if the ListItems in temp look like
Text    Value
LetterA A
LetterB B

The ListItems in chbox.Items look like
Text    Value
LetterA LetterA
LetterB LetterB

A: You may want to define
 DataTextField="TextField" DataValueField="ValueField"

as shown below:
 <asp:CheckBoxList ID="CheckBoxList1" runat="server" DataTextField="TextField" DataValueField="ValueField">
        </asp:CheckBoxList>

Please check out DataTextField and DataValueField


text:
Q: Swift - encrypted realm db can still be accessed without key I probably do not understand the encryption of Realm propably and hope someone can help.
I created a Realm database with encryption according to this example: https://github.com/realm/realm-cocoa/blob/master/examples/ios/swift-2.0/Encryption/ViewController.swift
 let configuration = Realm.Configuration(encryptionKey: "31234567890123456789012345678901234567890123456789012345678901234".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false))
 let realm = try! Realm(configuration: configuration)

However after I run my script I can still access & change the Realm file in Realm browser. I expected that the Realm file is encrypted and users cannot read the realm file without decrypting it with the correct password.
I already read question "SWIFT - Realm db encryption not working" but it did not answer my question.
How can I protect my realm file that nobody can read/write Objects from and to it without knowing the encryption key ?
Thanks,
Tim


text:
Q: PayPal Access/Bearer token How to get Access/Bearer Token from PayPal https://api-m.paypal.com/v1/oauth2/token API call using Live PayPal ClientID and Secret Key.
I have used below setup before callling API in Postman
Basic Auth type.
Body tab = x-www-form-urlencoded.
grant_type = client_credentials
I am getting below response when calling above API with Live ClientID and Secret Key using Postman
{
"error": "invalid_client",
"error_description": "Client Authentication failed"
}
And When using SandBox api https://api-m.sandbox.paypal.com/v1/oauth2/token with Live CliendID and Secret Key it generates token but not authenticated when calling with other Live PayPal APIs to get records.

A:
When using SandBox api https://api-m.sandbox.paypal.com/v1/oauth2/token with Live CliendID and Secret Key it generates token

The only way to receive a token from api-m.sandbox.paypal.com is if you are actually using a sandbox Client ID and secret. There is no other possible way, the sandbox environment is completely separate from live.
Since your question is about how to obtain a live token from api-m.paypal.com , you must instead use a Client ID and secret from the "Live" tab of a REST API app in developer.paypal.com. (Clearly you are not using the correct credentials if you think the same ones work for sandbox.)
If you still think you are, what is the actual live Client ID you are using? Update your question with this information, and test it at https://developer.paypal.com/demo/checkout/#/pattern/client -- a live Client ID will necessarily lead to a live paypal.com checkout.


text:
Q: some media queries in my css are ignored I have the following css. The first '4 columns' media queries work, the rest is ignored. If I put '5-columns' before '1-column' that one works but '1, 6 and 7 are ignored. If I put 6 above that one works, but 1 and 5 are ignored. 2, 3 and 4 columns keep working no matter where I put them. I don't see the problem. I hope anyone can help me out.
#header-wrap {
    border-bottom: 1px solid #EFEFEF;
    margin: 32px 32px 16px;
    padding: 0 0 32px;
}

/* 1 column */
@media all and (max-width: 607px) {
    #header-wrap {
    width: 256px;
    }
}

/* 2 columns */
@media all and (min-width:607px) and (max-width:895px) {
    #header-wrap {
    width: 544px;
    }
}

/* 3 columns */
@media all and (min-width:895px) and (max-width:1183px) {
    #header-wrap {
    width: 832px;
    }
}

/* 4 columns */
@media all and (min-width:1183px) and (max-width:1471px) {
    #header-wrap {
    width: 1120px;
    }
}

/* 5 columns */
@media all and (min-width:1471px) and (max-width:1759px) {
    #header-wrap {
    width: 1408px;
    }
}

/* 6 columns */
@media all and (min-width:1759px) and (max-width:2062px) {
    #header-wrap {
    width: 1696px;
    }
}

/* 7 columns */
@media all and (min-width:2062px) {
    #header-wrap {
    width: 1696px;
    }
}

A: Got it working here
For some reason, there were dots following some of your closing square brackets. Not sure where they came from.
I also trimmed down your media queries for the same effect with less code. Loosely speaking, there are 3 main methods of targeting a screen. You can let your styles:

*

*style down e.g. (min-width:320px), so everything down to that size

*style up (max-width:480px), everything up to that size

*bracket (min-width:320px) and (max-width:480px)
What you had there is bracketing, where rather than allowing the styles within the media queries to cascade i.e. a 1200px wide screen meets (min-width:600px) and (min-width:1000px) so you only need apply a style to the lower value query, you have to re-apply styles based on a specific bracketed resolution, such as (min-width:600px) and (max-width:800px).
This is a totally legit technique, but you'll find you end up with a lot more code to maintain if any changes are ever needed. I learnt this one the hard way. CSS is designed to cascade, and media queries are the same.
Lastly, if you are going to use the bracket approach, try to avoid specifying the same resolution twice
i.e. (min-width:320px) and (max-width:500px) then (min-width:500px) and (max-width:900px)
as this may confuse some browsers or cause flickering when resizing a screen, because there is a single pixel that meets both conditions. The safe way to write it would be:
 `(min-width:320px) and (max-width:500px)`

then (min-width:501px) and (max-width:900px)
Failing that, styling up or down eliminates this possibility altogether :)


text:
Q: Posting to website using curl This may be another dumb question but anyway. I am trying to post into a search box of the University online public access catalogue and here is what I came up with:
<?php
date_default_timezone_set('Asia/Manila');
$today = date('m-d-Y');
echo $today;

$keyWord=database;
$urltopost = "http://opac.usls.edu.ph/TLCScripts/interpac.dll?SearchForm?   Directions=1&Config=pac&Branch=0";
$datatopost = array ('SearchData' => "c++");

$ch = curl_init ($urltopost);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$returndata = curl_exec ($ch);
echo $returndata;

?>

I get this:
09-19-2013
Configuration has been deleted.
I really need help. What did I do wrong?
Thanks in advance good people of this world.

A: If you look at how a search is done in that site, you can see that your post url should be
http://opac.usls.edu.ph/TLCScripts/interpac.dll?Search
and data should be something like
FormId=0&Config=pac&LimitsId=0&StartIndex=0&SearchField=7&SearchType=1&ItemsPerPage=10&SearchData=yoursearchtermhere
Since in your example you're not posting the "config" parameter in post data, you get the error message you specified.


text:
Q: What's the distribution function I have a random variable $1_{\{az_1+bz_i<L\}}$, where $1_{\{.\}}$ is the indicator function, $z_1,z_i$ are $N(0,1)$, i.e., i.i.d standard normal and $L$ is a constant. If $X = \frac{\sum_{i=1}^n1_{\{az_1+bz_i<L\}}}{n}$, How do I determine the distribution function of $\widetilde{X}:=X|z_1 = z$, i.e., $X$ conditional on $z_1$. In other words, evaluate P$(\widetilde{X} \leq x)$.

A: Introducing $L(z)=L-az$ and, for every $x$, $x(z)=x-\mathbf 1_{\{(a+b)z\leqslant L\}}$, the independence of $Z_1$ and $(Z_i)_{i\geqslant 2}$ yields
$$P(X=x\mid Z_1=z)=P\left(\sum\limits_{i=2}^n\mathbf 1_{\{bZ_i\leqslant L(z)\}}=x(z)\right).
$$
Since $(Z_i)_{i\geqslant 2}$ is i.i.d., this is the weight at $x(z)$ of the binomial distribution with parameters $n-1$ and $p(z)$, where
$$
p(z)=P(bZ_i\leqslant L(z))=\Phi(L(z)/b).
$$
To sum up, if $(a+b)z\gt L$, then for every integer $0\leqslant x\leqslant n-1$,
$$P(X=x\mid Z_1=z)={n-1\choose x}p(z)^x(1-p(z))^{n-1-x},
$$
while, if $(a+b)z\leqslant L$,  then for every integer $1\leqslant x\leqslant n$,
$$P(X=x\mid Z_1=z)={n-1\choose x-1}p(z)^{x-1}(1-p(z))^{n-x},
$$


text:
Q: How to set default field value from xml code in odoo? In sales order module I have created a new customised form view, in sale.py file I have created a new field 'is_sample'
'is_sample': fields.boolean("Specimen Order", store=False),

I want to set its default value from xml code so that it doesn't get affected in default form view. I have tried in four ways,
1)<field name="is_sample" eval="True"/>
2)<field name="is_sample" domain="[('is_sample','=',True)]"/>
3)<record id="action_specimen_orders" model="ir.actions.act_window">
        <field name="type">ir.actions.act_window</field>
        <field name="context">{'is_sample': 'True'}</field>
       ...
4)<record id="action_specimen_orders" model="ir.actions.act_window">
        <field name="type">ir.actions.act_window</field>
        <field name="domain">[('is_sample','=','True')]</field>
       ...

A: There is an easiest way to set default value from the xml, generally you can it for all those fields of the model. For that you need to add dictionary key/value pair to set default value for any field.
General syntax
default_field_name : default_value

To set default value you need to pass context with window action in which you need to set one key/value pair in context as shown in syntax. default_ is the prefix which needs to be set with field name as key.
Try following:
<record id="action_specimen_orders" model="ir.actions.act_window">
        <field name="type">ir.actions.act_window</field>
        <field name="view_type">form</field>
        <field name="view_mode">tree,form</field>
        <field name="context">{'default_is_sample': True}</field>
</record>

A: If you want your product must be available in POS, you have to do like:
<record id="module_name.action_name" model="ir.actions.act_window">
    <field name="name">My Menu</field>
    <field name="res_model">object.name</field>
    <field name="context">{'default_available_in_pos':1}
    </field>
</record>


text:
Q: Spring Security basic auth for sign in I am new to springboot security.And i just find that it is quite hard to follow the latest version since some of the method has already outdated.So i just follow on some of the tutorials to work on the jwt and authentication with mysql.I have problem on the use of the basic auth for generating the token when it is integrated to my own model.Here are my code.
Tokenservice:
@Service
public class TokenService {
    private final JwtEncoder encoder;

    private PasswordEncoder passwordEncoder;

    public TokenService(JwtEncoder jwtEncoder, PasswordEncoder passwordEncoder) {
        this.encoder = jwtEncoder;
        this.passwordEncoder = passwordEncoder;
    }

    @Autowired
    private JpaUserrepository jpaUserrepository;

    private Authentication auth;

    public String generateToken (Authentication authentication){
        Instant now=Instant.now();
        String scope=authentication.getAuthorities().stream() //Stream<capture of ? extends GrantedAuthority >
        .map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(" "));
        JwtClaimsSet claims = JwtClaimsSet.builder()
                .issuer(authentication.getName())
                .issuedAt(now)
                .expiresAt(now.plus(1, ChronoUnit.HOURS))
                .claim("scope",scope).build();
                return this.encoder.encode(JwtEncoderParameters.from((claims))).getTokenValue();
    }
    public String signup(JpaUser jpaUser) {
        System.out.println(jpaUserrepository.findByUsername(jpaUser.getUsername()));
       if(jpaUserrepository.findByUsername(jpaUser.getUsername()).isPresent())
        {return "repeated username";}
        jpaUserrepository.save(new JpaUser(jpaUser.getUsername(),passwordEncoder.encode(jpaUser.getPassword()),jpaUser.getEmail(),jpaUser.getRoles()));
        return "sign up success";

    }
}

I want to sign up which can return the token,but the required type of generatedtoken method is  authentication (Basic Auth) but i have no idea to convert my Jpauser model to authentication interphase.
Here is Jpauser model:
@Entity
@Table(name = "JpaUser")
public class JpaUser {

    @Id @GeneratedValue
    private Long id;
    private String username;
    private String password;

    private String email;
    private String roles;

    public JpaUser() {}

    public JpaUser(String username, String password,String email, String roles) {
        this.username = username;
        this.password = password;
        this.email=email;
        this.roles = roles;

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRoles() {
        return roles;
    }

    public void setRoles(String roles) {
        this.roles = roles;
    }

    @Override
    public String toString() {
        return "SecurityUser{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", roles='" + roles + '\'' +
                '}';
    }
}

My securityconfig:
 @Bean
    public SecurityFilterChain securityfilterchain(HttpSecurity http) throws Exception {
        return http
                //if used csrf.ignoringAntMatchers -->prevent the attack from cross-origin
                //.csrf(csrf -> csrf.disable())
                .csrf(csrf -> csrf.ignoringAntMatchers("/shownews/**","/getnews/**","/token","/signup"))

                .authorizeRequests(auth-> auth
                        .antMatchers("/shownews/**").permitAll()
                        .antMatchers("/getnews/**").permitAll()
                        .anyRequest().authenticated())

                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                //Link to the jpauserservice to check whether the authentication valid (similar to authentication manager)
                .userDetailsService(myUserDetailsService)
                .headers(headers -> headers.frameOptions().sameOrigin())
                .httpBasic(Customizer.withDefaults())
                .formLogin().and()
                .build();
    }
    @Bean
    JwtDecoder jwtDecoder(){
        return NimbusJwtDecoder.withPublicKey(rsakeys.publicKey()).build();
    }

In fact, i am quite loss when i learn this topic since i think the doc is quite hard to understand .I am just wondering if there any materials that are more easy to understand amd modifymy code?


text:
Q: Change Toggle Switch status dynamically I am trying to figure out how to set toggle switch button base on a value. I am using bootstrap for the button. Anyone please tell me what is wrong?
*user.isActive only have two value either true or false.
<input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" style="font-size:38px" type="checkbox">
<input type="hidden" id="activeStatus" value='${user.isActive}'/>

A: I found the answer so wanted to share with people who need help too. For people using bootstrap use:
$(document).ready(function() {

              if ($('#activeStatus').val().trim() == 'true') {
                  $("#activeSwitch").bootstrapToggle('on');
              } else if ($('#activeStatus').val().trim() == 'false') {
                  $("#activeSwitch").bootstrapToggle('off');
              }
            });

Use .bootstrap('on') instead of prop or attr if they are not working.

A: Try like this prop() instead of attr => prop('checked',true). use Boolean value instead of string
updated
Do with trim() its remove the unwanted space

$(document).ready(function() {

  if ($('#activeStatus').val().trim() == 'true') {
    $("#activeSwitch").prop("checked", true);
  } else if ($('#activeStatus').val().trim() == 'false') {
        $("#activeSwitch").prop("checked", false);
  }
});

<input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" style="font-size:38px" type="checkbox">
  <input type="hidden" id="activeStatus" value='true' />

or single line code
$(document).ready(function() {
 $("#activeSwitch").prop("checked" , $('#activeStatus').val().trim() == 'true')
 })


text:
Q: SQL. How to insert one select into another select with the ignoring of duplicates and the with changing of Foreign Key in a copy Original task: Copy lines from one document to another with ignoring duplicates.
Copy from the document with the minimum number to the document with the maximum number.
Assume that there is at least one entry in the header.
When adding, skip (do not add) rows for products that already exist.
Here's the whole code:
CREATE TABLE TOV
(
    KTOV INT PRIMARY KEY NOT NULL,
    NTOV VARCHAR(MAX) NOT NULL,
    SORT VARCHAR(MAX) NOT NULL
);
GO

CREATE TABLE DMZ
(
    DDM DATE NOT NULL,
    NDM INT PRIMARY KEY NOT NULL,
    PR INT NOT NULL
);
GO

CREATE TABLE DMS
(
    KTOV INT NOT NULL
        FOREIGN KEY REFERENCES TOV(KTOV),
    NDM INT NOT NULL
        FOREIGN KEY REFERENCES DMZ(NDM),
    KOL INT NOT NULL,
    CENA DECIMAL(13,2) NOT NULL,
    SORT VARCHAR(MAX) NOT NULL
);
GO

INSERT TOV
VALUES
(101, 'Beer', 'Light'),
(102, 'Beer', 'Dark'),
(103, 'Chips', 'With paprika');
go

INSERT DMZ
VALUES
('01.05.2014', 2, 1),
('01.05.2104', 3, 2),
('02.05.2014', 5, 2);
GO

INSERT DMS
VALUES
(101, 2, 100, 8.00, 'Light'),
(102, 3, 80, 9.50, 'Dark'),
(103, 5, 50, 6.50, 'With paprika'),
(101, 2, 1, 10.00, 'Light'),
(103, 3, 1, 8.50, 'With paprika'),
(101, 5, 2, 10, 'Light'),
(102, 3, 1, 11.50, 'Dark'),
(101, 2, 2, 10.50, 'Light'),
(103, 5, 1, 8.60, 'With paprika');
GO

I'm stuck and I can not find a solution.
There is such a pseudo-query:
INSERT INTO (select * from DMS WHERE NDM = (SELECT MIN(NDM) FROM DMS))
FROM (select * from DMS WHERE NDM = (SELECT MAX(NDM) FROM DMS))
ON DUPLICATE KEY UPDATE

There is also such a variant of the query:
CREATE VIEW MINDMS1
AS SELECT * FROM DMS1 WHERE NDM = (SELECT MIN(NDM) FROM DMS1);

CREATE VIEW MAXDMS1
AS SELECT * FROM DMS1 WHERE NDM = (SELECT MAX(NDM) FROM DMS1);

 MERGE  MAXDMS1 AS MAXD
    USING MINDMS1 AS MIND
    ON (MAXD.KTOV = MIND.KTOV AND MAXD.NDM > MIND.NDM)
        WHEN NOT MATCHED THEN
            INSERT (KTOV, NDM, KOL, CENA, SORT)
            VALUES (MIND.KTOV, MIND.NDM, MIND.KOL, MIND.CENA, MIND.SORT);

But it works wrong. The data coped to the MINDMS1. But it is need to copy into MAXDMS1. And I don't know how to change ndm in copy(it is foreign key) to MAXDMS1.NDM

A: No need for merge if this operation is insert only:
Depending on which columns would determine a duplicate, compare them in the where of a not exists() clause. For the example, I am comparing ktov and kol (ktov alone results in no rows inserted)
declare @min_ndm int, @max_ndm int;
select @min_ndm = min(ndm), @max_ndm = max(ndm) from DMS;

insert into dms (ktov, ndm, kol, cena, sort)
output inserted.*
select o.ktov, ndm=@max_ndm, o.kol, o.cena, o.sort
from dms o
where o.ndm = @min_ndm
  and not exists (
    select 1
    from dms i
    where i.ndm = @max_ndm
      and i.ktov = o.ktov
      and i.kol  = o.kol
    )

dbfiddle.uk demo
inserts the following rows:
+------+-----+-----+-------+-------+
| KTOV | NDM | KOL | CENA  | SORT  |
+------+-----+-----+-------+-------+
|  101 |   5 | 100 | 8.00  | Light |
|  101 |   5 |   1 | 10.00 | Light |
+------+-----+-----+-------+-------+

If you really want to use merge, then you can use common table expressions for your target and source:
declare @min_ndm int, @max_ndm int;
select @min_ndm = min(ndm), @max_ndm = max(ndm) from DMS;

;with mindms as (select * from dms where ndm = @min_ndm)
    , maxdms as (select * from dms where ndm = @max_ndm)
merge into maxdms as t
  using mindms as s
    on (t.ktov = s.ktov and t.kol = s.kol)
  when not matched then
    insert values (s.ktov, @max_ndm, s.kol, s.cena, s.sort)
output $action, inserted.*;

dbfiddle.uk demo
returns:
+---------+------+-----+-----+-------+-------+
| $action | KTOV | NDM | KOL | CENA  | SORT  |
+---------+------+-----+-----+-------+-------+
| INSERT  |  101 |   5 | 100 | 8.00  | Light |
| INSERT  |  101 |   5 |   1 | 10.00 | Light |
+---------+------+-----+-----+-------+-------+

Some merge issues to be aware of:

*

*Use Caution with SQL Server''s MERGE Statement - Aaron Bertrand

*An Interesting MERGE Bug - Paul White


text:
Q: Writing Tweets to the HDFS using Flume doesn't work I used the Cloudera CDH5 QuickStart VM with VMware and all the services are installed via the Cloudera Manager.
I created a /user/flume/tweets and a flume user and group. I restarted all the services but, doesn't matter how long I wait, no tweets will be written to the HDFS. The /user/flume/tweets/ directory is still EMPTY!
Why?
This is my flume.conf:
TwitterAgent.sources = Twitter
TwitterAgent.channels = MemChannel
TwitterAgent.sinks = HDFS
TwitterAgent.sources.Twitter.type = com.cloudera.flume.source.TwitterSource
TwitterAgent.sources.Twitter.channels = MemChannel
TwitterAgent.sources.Twitter.consumerKey = **
TwitterAgent.sources.Twitter.consumerSecret = **
TwitterAgent.sources.Twitter.accessToken = **
TwitterAgent.sources.Twitter.accessTokenSecret = ***
TwitterAgent.sources.Twitter.keywords = hadoop, big data, analytics, bigdata, cloudera,        data science, data scientiest, business intelligence, mapreduce, data warehouse, data     warehousing, mahout, hbase, nosql, newsql, businessintelligence, cloudcomputing
TwitterAgent.sinks.HDFS.channel = MemChannel
TwitterAgent.sinks.HDFS.type = hdfs
TwitterAgent.sinks.HDFS.hdfs.path =     hdfs://localhost.localdomain:804/user/flume/tweets/%Y/%m/%d/%H/
TwitterAgent.sinks.HDFS.hdfs.fileType = DataStream
TwitterAgent.sinks.HDFS.hdfs.writeFormat = Text
TwitterAgent.sinks.HDFS.hdfs.batchSize = 1000
TwitterAgent.sinks.HDFS.hdfs.rollSize = 0
TwitterAgent.sinks.HDFS.hdfs.rollCount = 10000
TwitterAgent.channels.MemChannel.type = memory
TwitterAgent.channels.MemChannel.capacity = 10000
TwitterAgent.channels.MemChannel.transactionCapacity = 100

This is what I get on flume log:
[cloudera@localhost ~]$ tail -f /var/log/flume-ng/flume.log
27 May 2014 21:40:28,536 INFO  [conf-file-poller-0]     (org.apache.flume.conf.FlumeConfiguration$AgentConfiguration.addProperty:1016)  -     Processing:HDFS
27 May 2014 21:40:28,536 INFO  [conf-file-poller-0]     (org.apache.flume.conf.FlumeConfiguration$AgentConfiguration.addProperty:1016)  -     Processing:HDFS
27 May 2014 21:40:28,536 INFO  [conf-file-poller-0]     (org.apache.flume.conf.FlumeConfiguration$AgentConfiguration.addProperty:1016)  -     Processing:HDFS
27 May 2014 21:40:28,537 INFO  [conf-file-poller-0] (org.apache.flume.conf.FlumeConfiguration$AgentConfiguration.addProperty:1016)  -     Processing:HDFS
27 May 2014 21:40:28,537 INFO  [conf-file-poller-0]     (org.apache.flume.conf.FlumeConfiguration$AgentConfiguration.addProperty:1016)  -     Processing:HDFS
27 May 2014 21:40:28,562 WARN  [conf-file-poller-0]     (org.apache.flume.conf.FlumeConfiguration$AgentConfiguration.isValid:319)  - Agent     configuration for 'agent' does not contain any channels. Marking it as invalid.
27 May 2014 21:40:28,564 WARN  [conf-file-poller-0]     (org.apache.flume.conf.FlumeConfiguration.validateConfiguration:127)  - Agent configuration     invalid for agent 'agent'. It will be removed.
27 May 2014 21:40:28,564 INFO  [conf-file-poller-0]     (org.apache.flume.conf.FlumeConfiguration.validateConfiguration:140)  - Post-validation     flume configuration contains configuration for agents: [TwitterAgent]
27 May 2014 21:40:28,564 WARN  [conf-file-poller-0]     (org.apache.flume.node.AbstractConfigurationProvider.getConfiguration:138)  - No     configuration found for this host:agent
27 May 2014 21:40:28,592 INFO  [conf-file-poller-0] (org.apache.flume.node.Application.startAllComponents:138)  - Starting new configuration:{     sourceRunners:{} sinkRunners:{} channels:{} }

How can I fix that?
Thanks in advance.

A: Did you setup the Flume Configuration using Cloudera Manager?  Please follow this link http://javet.org/?p=279 for implementing twitter firehose in CDH5.


text:
Q: Give a color for ID even and odd I have news from my DB. I would like to know how to give a color for ID even and odd? A grey for an even and a white for an odd?
$req = $bdd->query('SELECT id, titre, contenu, DATE_FORMAT(date_creation, \'%d/%m/%Y à %Hh%i\') AS date_creation_fr FROM billets ORDER BY date_creation DESC LIMIT '.$depart.', '.$articlesPage);

A: After fetching result, in foreach, you can check if id is dividable by 2.
If it's dividable, then its even, otherwise its odd.
if(($news->id % 2) === 1){
  // It's odd
}else{
  // It's even
}

A: This can be achieved by using php:
if(($news->id % 2) === 1){
  // It's odd
}
else{
  // It's even
}

Or if you are using html table than it can also achieve by using css:
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}


text:
Q: Homology of universal abelian cover of a manifold If one define the universal abelian covering $M_0$ of a manifold $M$ as the abelian covering (i.e. normal covering with abelian group of deck transformations) that covers any other abelian covering, then what can one say about $H_1(M_0)$ ? Note that Hurewicz Theorem gives us a group isomorphism between $H_1(M_0)$ and the abelianization of $[\pi_1(M),\pi_1(M)]$.
In particular, I would like to understand why is the following integral independent of the choice of a $C^1$ curve $\tau$ in $M_0$ with fixed endpoints:
$$
\int_\tau \overline{\omega},
$$
where $\overline{\omega}$ is the lift of a closed 1-form $\omega$ on $M$.

A: This has not much to do with $H_1(M_0)$. If $\pi :M_0\rightarrow M$ is your abelian covering, we have $\int_{\tau }\overline{\omega} =\int_{\pi _*\tau }\omega $. But the  exact sequence $0\rightarrow \pi _1(M_{0})\rightarrow \pi _1(M)\rightarrow H_1(M)\rightarrow 0$ shows that $\pi _*\tau $ is zero in $H_1(M)$, hence the integral is zero.


text:
Q: A confusion about a transfer function's Bode plot and s domain view Recently I have been stuck with a simple Bode plot and H(s) comparison.
To begin with, here is the transfer function:
H(s) = 1/s
For Bode plots I write:
H(jw) = (jω)^-1 = 1/(jω)
For the magnitude and phase I use:
|H(jω)| = 20*log(abs(H)) versus log(ω) and here is the plot:

You see above at ω = 0 the dB is finite and in this case it is zero.
Now I 3D plot |H(s)| on the s-plane and try to see how it will show up along the imaginary axis. It is because the Bode plot should be the projection of |H(s)| on the imaginary axis.
Now below is the plot of |H(s)|:

As you see, for the same transfer function 1/s the projection of |H(s)| on the imaginary axis is not the same with the Bode plots I obtained at the beginning.
The Bode plot is logarithmic but the at ω = 0 projection of |H(s)| on the imaginary axis goes to infinity, on the other hand in the Bode plot it is zero.
What is wrong here?
Edit:
From the answer I found out the problem was I was blindly plotting versus log10(ω).
Actually when transfer function is in dB it becomes as:

But on the other hand look what happens below when you plot the Bode plot linearly
ω versus |H(jω)|:

MATLAB plots infinity as 1.

A:
You see above at ω = 0 the dB is finite and in this case it is zero

No, that is not true; \$\omega\$ = 1.
Look at your graph - you are are plotting against a base of log\$_{10}(\omega)\$.
At \$\omega\$ = 1, H(s) will be 0 dB. 0 dB = unity or 1.
For an integrator, at zero frequency, gain will be infinite because that is where the pole is.

A: The practical realization of an integrator implies an active circuit having a finite gain like the open-loop gain of an op amp \$A_{OL}\$ for instance. In this case, the integrator is built with an \$RC\$ network associating a time constant \$\tau\$ to \$s\$ in the denominator.

The perfect transfer function \$H_1(s)=\frac{\omega_p}{s}\$ in which \$\omega_p=\frac{1}{\tau}\$ with \$\tau=RC\$ becomes \$H_2(s)\approx\frac{A_{OL}}{1+\frac{s}{\omega_p}A_{OL}}\$ if we neglect the low-frequency pole of the op amp. The gain as \$s\$ approaches 0 is bounded by the op amp open-loop gain as the below Mathcad sheet shows.

On the other hand, Mathcad predicts the gain approaching infinity as \$s\$ approaches 0 with \$H_1\$.


text:
Q: Dynamically binding custom directive to ng-repeat my controller has the json for my form then i have a directive that gets repeated to produce the form elements.  based on the 'type' passed to the directive, the directive should know how to render the element.
but i don't know why it's not rendering the form templates properly here but that's a separate issue.
my immediate issue is, i can't seen to pass the ng-model and bind it correctly to the template.
does anyone see my problem?

var myApp = angular.module('myApp', []);

myApp.directive('ioProductElement', ['$compile', function ($compile) {
    var dropdownTemplate = '<select ng-model="model" ng-options="option.Text for option in data"></select>';
    var textAreaTemplate = '<textarea ng-model="model" class="form-control">{{ data }}</textarea>';
    var radioListTemplate = '<input ng-model="model" type="radio" name="{{ data.Name }}" ng-checked="item.Selected" />{{ item.ProductLabel }}  ';

    return {
        restrict: 'E',
        replace: true,
        scope: {
            model: '=',
            type: '=',
            data: '='
        },
        link: function (scope, element) {
            var getTemplate = function (type) {
                var template = '';
                switch (type) {
                    case 'SelectListItem':
                        template = dropdownTemplate;
                        scope.model = _.find(scope.data, {
                            Selected: true
                        });
                        break;
                    case 'TextArea':
                        template = textAreaTemplate;
                        break;
                    case 'RadioList':
                        template = radioListTemplate;
                        break;
                }
                return template;
            };

            element.html(getTemplate(scope.type));
            $compile(element.contents())(scope);
        }
    };
}]);

myApp.controller('DynamicFormController', function () {
    this.productElement = {};
    this.product = {
        ProductName: 'Online Form',
        Company: 'TEST',
        Data: []
    };
    this.productItems = [{
        ProductLabel: "Status",
        ProductType: "SelectListItem",
        ProductData: [{
            "Text": "Item1",
                "Value": "1",
            Selected: true
        }, {
            "Text": "Item2",
                "Value": "2"
        }]
    }, {
        ProductLabel: "Publication",
        ProductType: "SelectListItem",
        ProductData: [{
            Text: 'Item1',
            Value: '1'
        }, {
            Text: 'Item2',
            Value: '2',
            Selected: true
        }]
    }, {
        ProductLabel: "Caption",
        ProductType: "TextArea",
        ProductData: "this is some data for the textarea"
    }, {
        ProductLabel: "Display Advertising",
        ProductType: "RadioList",
        ProductData: {
            Name: "classifiedAdvertising",
            Items: [{
                Text: 'Full Page',
                Selected: true
            }, {
                Text: '1/2 Page'
            }]
        }
    }, {
        ProductLabel: "Status2",
        ProductType: "SelectListItem",
        ProductData: [{
            "Text": "Item1",
                "Value": "1"
        }, {
            "Text": "Item2",
                "Value": "2"
        }, {
            "Text": "Item3",
                "Value": "3",
            Selected: true
        }]
    }, ];

    this.save = function () {
        this.product.Data = this.productItems;
        console.log('in save', this.product);
    };
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

    <form class="form-horizontal" ng-controller="DynamicFormController as ctrl">

            {{ item.ProductLabel }}

                <io-product-element data-model="ctrl.productElement[item.ProductLabel]" data-type="item.ProductType" data-data="item.ProductData"></io-product-element>

                <input type="button" class="btn btn-info" data-ng-click="ctrl.save()" value="Submit" />

                 product: {{ ctrl.product | json }}

    </form>

A: Try To add a break statement in the first switch case
//[...]
switch (type) {
    case 'SelectListItem':
        template = dropdownTemplate;
        scope.model = _.find(scope.data, {
            Selected: true
        });
        break;
     case 'TextArea':
        template = textAreaTemplate;
        break;
     case 'RadioList':
        template = radioListTemplate;
        break;
}
//[...]


text:
Q: Too long TextView makes other Views disappear How to stop checkbox from disappearing in code below when text in the TextView is too long? I'm not interested in hardcoding max_width for the TextView and I want to display my whole text.
<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv"
                style="@style/Text"
                android:layout_weight="0"
                android:text="@string/multiple_sounds" />

            <CheckBox
                android:id="@+id/cb"
                style="@style/Text"
                android:layout_gravity="right"
                android:layout_weight="1"/>

        </LinearLayout>

styles.xml
<style name="Text">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:padding">@dimen/margin</item>
    <item name="android:textSize">@dimen/text</item>
    <item name="android:textAlignment">center</item>
</style>

A: I would use weight. Add android:weightSum to your LinearLayout with value 1.
For each element in your LinearLayout add weight. For example 0.8 for textview and 0.2 for Checkbox.
Then set width to 0dp for each element !
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1">

        <TextView
            android:id="@+id/tv"
            style="@style/Text"
            android:layout_weight="0.8"
            android:text="@string/multiple_sounds" />

        <CheckBox
            android:id="@+id/cb"
            style="@style/Text"
            android:layout_gravity="right"
            android:layout_weight="0.2"/>

    </LinearLayout>

And update your style :
    <style name="Text">
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_width">0dp</item>
        <item name="android:padding">@dimen/margin</item>
        <item name="android:textSize">@dimen/text</item>
        <item name="android:textAlignment">center</item>
    </style>

A:
If you are about to display large data on textview, i suggest to use scroll view in your parent layout.

A: I'm late for this but I hope to help smn with this issue. Have same problem checkBox make TextView unreachable for LinearLayout, both checkBox and textView need to have this line in xml:
android:layout_gravity="center_vertical"

A: use text view weight = 1 and other view as wrap_content so size of other view not change according your text
 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <TextView
        android:id="@+id/tv"
        style="@style/Text"
        android:layout_weight=""
        android:text="@string/multiple_sounds" />

    <CheckBox
        android:id="@+id/cb"
        style="@style/Text"
        android:layout_gravity="right"
        android:layout_weight="wrap_content"/>

</LinearLayout>

A: If you want text to go in new line (use RelativeLayout):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true" />

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_toStartOf="@id/checkbox" />

</RelativeLayout>

Another solution is to use this lib to shrink text:
https://github.com/grantland/android-autofittextview

A: I would suggest to use RelativeLayout to maintain uniformity in UI. Below is sample Relative layout code
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">

<TextView
    android:id="@+id/tv"
    style="@style/Text"
    android:layout_toLeftOf="@+id/cb"
    android:text="@string/multiple_sounds" />

<CheckBox
    android:id="@+id/cb"
    style="@style/Text"
    android:layout_gravity="right"
    android:layout_alignParentEnd="true"/>

</RelativeLayout>


text:
Q: Find the third vertex if the vertices of the hypotenuse of an isosceles right triangle are given
If the vertices of the hypotenuse of an isosceles right triangle are $(9,-9)$ and $(1,-3)$, then find the third vertex

The fomula for this is given by $(x,y)=\bigg(\dfrac{x_1+x_2\pm(y_1-y_2)}{2},\dfrac{y_1+y_2\mp(x_1-x_2)}{2}\bigg)$
I really don't seem to find any reason to simply just bi-hart the equation. What is the easier way to solve such problems ?. Can I do transformations of the triangle and solve the problem ?
Attempt

$A(9,-9)$, $B(1,-3)$, $C(a,b)=\;?$
First the triangle is transformed such that the third vertex becomes zero.ie, $A(9-a,-9-b)$, $B(1-a,-3-b)$, $C(0,0)$. Now I think I can rotate AC and BC so that they coincide with the $x$ and $y$ axes, then from there I can find the third vertex ?
How do I do it mathematically ?

A: One easy way to see this is to add in the midpoint $M$ of $AB$. Now since the angle at $C$ is $90^\circ$, $MA=MB=MC$, and since it is isosceles $MC$ is perpendicular to $AB$. The vector $\vec{AM}=\frac12\vec{AB}=\frac12\binom{x_2-x_1}{y_2-y_1}$, and $\vec{MC}$ is equal in magnitude and perpendicular, so must be $\pm\frac12\binom{y_2-y_1}{x_1-x_2}$. Thus $$\vec{OC}=\binom{x_1}{y_1}+\frac12\binom{x_2-x_1}{y_2-y_1}\pm\frac12\binom{y_2-y_1}{x_1-x_2}.$$

A: If $(x_1,y_1);(x_2,y_2)$ are the two vertices of hypotenuse of  an isosceles right triangle
and $(h,k)$ be third vertex
$$\dfrac{y_1-k}{x_1-h}\cdot\dfrac{y_2-k}{x_2-h}=-1\ \ \ \ (1)$$
and $$(x_1-h)^2+(y_1-k)^2=(x_2-h)^2+(y_2-k)^2$$
$$\iff x_1^2-2x_1h+y_1^2-2y_1k=x_2^2-2x_2h+y_2^2-2y_2k\ \ \ \  (2)$$
Solve the two simultaneous equations for $h,k$

A: Hint:
If $(x_1,y_1);(x_2,y_2)$ are the two vertices of hypotenuse of  an isosceles right triangle
and $(h,k)$ be third vertex
$$\dfrac{k-y_1}{\cos t}=\dfrac{h-x_1}{\sin t}=r$$
where $2r^2=(x_1-x_2)^2+(y_1-y_2)^2$  where $t=\pm45^\circ$


text:
Q: $3$ independent events $ A, B, C $ what is the $P(AB\cup C)$? $A, B, C$ are mutually independent. What is the $P(AB\cup C)$?
My guess
$$P(AB \cup C)=P(AB)+P(C)=P(A)P(B)+P(C) $$
Is this correct or do I have to add some subtraction [$-P(A\cap B \cap C)$]? I guess, I don't have a full understanding of independent events.

A: You have to subtract $P(A \cap B \cap C)$ since the term need not be zero.
\begin{align}
P(AB \cup C)&=P(AB)+P(C)-P(ABC)\\&=P(A)P(B)+P(C)-P(A)P(B)P(C)
\end{align}
A particular examples of $A,B,C$ that are mutually independent and are not mutually exclusive are whether you get heads from 3 independent coin tosses.


text:
Q: json.simple: class cast exception can anybody help me with the following error:
 java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.xy.paket

class is a class extending JSON and that is why I do not understand why a cast is not possible? If I print an object of class on my console, I get the same output when printing an JSON object. It looks like:
{"receiver":"server","sender":"client","payload":"bookID;bookTitle","action":"doStuff"}

Can anybody help me how to solve this problem?

A: Your error indicates that you are trying to cast a JSONObject to paket. For this to work, JSONOject has to extend paket (which I expect it does not). If paket extends JSONObject, then you can cast from paket to JSONObject, but not the other way.


text:
Q: what are dependencies in rails/ruby I am a beginner is rails, every now and then I come across dependencies. I tried to figure out what it means, but was not able to. Can someone please explain me what it means?

A: Hm, if you are talking about the :dependent option for describing a has_one relationship, you use that option to change the default behavior for what happens to a child row when a row in the parent table gets deleted.
:dependent => :destroy

Child row is destroyed when parent row is destroyed.
:dependent => :nullify

Child row's foreign key is set to null (it is orphaned).
:dependent => :delete

When parent is destroyed the child row is deleted without calling its destroy method.
You can also use these to change the behavior of a has_many relationship, except they will apply to every child row, and you would use :delete_all instead of :delete.
A "dependency" in the general sense of the word means that a table is being used by another table - thus one table "depends" on another.

A: Say you install a gem in rails and if it in turn installs other gems then those gems are its dependencies.
As far as the answer above goes, you can accomplish the same using validates_uniqueness_of plugin.