text:
Q: Sum same item in one list I am still learning C# and I have a problem about list. I was trying to write a code using list. Here is my code
List<Item> itemList = new List<Item>();

itemList.Add(new Item { ItemID = (int)itemID, ItemQty = (decimal) itemQty });

And here is the input for the list
index  Item ID & Amount
-------------------------
0      0001         20
1      0002         10
2      0001         30
3      0003         40

What I was trying to do is to get the total amount of each ID. For this case, the total amount of Item 0001 is 50.
I know how to sum all item, but I wasn't able to sum the amount for specific item. Thank you in advance for the help

A: I posted this in a comment but it would be easier to explain / elaborate as an answer, as Ahmad suggested ;)
You could use LINQ's GroupBy() with Sum() as follows (remember using System.Linq;)
var grouped = itemList.GroupBy(i => i.ItemId).Select(i => new { ItemId=i.Key, Total=i.Sum(item => item.ItemQty) });

The above line groups itemList based on ItemIds, and then creates a new anonymous type with ItemId and the sum of ItemQty's (Total).
Later, to get the total for a specific ID, you can do:
var sumForId1 = grouped.Where(g => g.ItemId == 1).Select(g => g.Total).Single();

Edit to add an alternative:
As Ahmad suggests in the comments, another method (quicker for lookups involving huge lists) is to use ToDictionary<> to create a Dictionary as follows:
var grouped = itemList.GroupBy(i => i.ItemID).ToDictionary(i => i.Key, i => i.Sum(item => item.ItemQty));
//doesn't matter if ItemID is string or int here

var sumForId1 = grouped[1];     //or if ItemID is string, grouped["1"]

A: If we have a class
class Item
{
    public int ItemID;
    public decimal ItemQty;
}

Then this is one possible solution
void Main()
{
    List<Item> itemList = new List<Item>();

    itemList.Add(new Item { ItemID = 1, ItemQty = 20m });
    itemList.Add(new Item { ItemID = 2, ItemQty = 10m });
    itemList.Add(new Item { ItemID = 1, ItemQty = 30m });
    itemList.Add(new Item { ItemID = 3, ItemQty = 40m });

    var itemGroup = itemList.GroupBy(i => i.ItemID).Select(g => new { ItemID = g.Key, TotalQty = g.Select(j => j.ItemQty).Sum() });
    foreach (var i in itemGroup)
        Console.WriteLine($"{i.ItemID}: {i.TotalQty}");
}

.


text:
Q: DTD required elements ordering I want to have list of required elements in any order defined in dtd, but have no idea how I could do this.
For example, I have following definition:
<!ELEMENT parent (child1, child2, child3)>

This dtd declaration will successfully validate following piece of xml:
<parent>
   <child1></child1>
   <child2></child2>
   <child3></child3>
</parent>

But in following case xml will not pass validation:
<parent>
   <child2></child2>
   <child1></child1>
   <child3></child3>
</parent>

One of the possible solution is to declare
<!ELEMENT parent (child1 | child2 | child3)>

But in this case one of the childs might be missing though validation will be successful.
I need correct dtd element declaration for the case when list of required elements can be present in any order.

A: Try:
<!ELEMENT parent (child1 | child2 | child3)*>

Should allow zero or more of any child, in any order.

A: Reading the spec is would appear you can't.

When children are declared in a sequence separated by commas, the children must appear in the same sequence in the document. In a full declaration, the children must also be declared, and the children can also have children.

I think it's because you are declaring a sequence (or ordered list if you like) rather than a collection (or unordered list).

A: This is tricky when you need exactly one of each child elements. This is the only way I can think of and it's not very pretty. It works though...
<!ELEMENT parent (
                 (child1,child2,child3)|
                 (child1,child3,child2)|
                 (child2,child1,child3)|
                 (child2,child3,child1)|
                 (child3,child1,child2)|
                 (child3,child2,child1)
                )>

Basically I'm specifying every possible combination of exactly one child1, child2, and child3 elements.
Here's an example instance. child1, child2, and child3 can be in any order, but they each must occur exactly one time.
<!DOCTYPE parent [
<!ELEMENT parent (
                 (child1,child2,child3)|
                 (child1,child3,child2)|
                 (child2,child1,child3)|
                 (child2,child3,child1)|
                 (child3,child1,child2)|
                 (child3,child2,child1)
                )>
<!ELEMENT child1 (#PCDATA)>
<!ELEMENT child2 (#PCDATA)>
<!ELEMENT child3 (#PCDATA)>
]>
<parent>
  <child2></child2>
  <child1></child1>
  <child3></child3>
</parent>

A: ChrisF is wrong to say you can't do this (but kudos for checking the spec!); DevNull [now known as Daniel Haley] is right to say you can.
There is, however, one complication:  the content model given by DevNull for parent violates the determinism rules of XML.  Informally, these rules say the parser must know, without lookahead, which token in the content model each element in the document matches.  If in a parent element the parser sees a child1, it can't know without lookahead whether it has just matched the first or second occurrence of child1 in DevNull's content model.  This is an error (but as it happens it's an error that processors are not obligated to report -- it's an error that means "all bets are off, the processor may do anything here, including fail to notice anything is wrong").
A content model for parent that obeys the determinism rules can be formed by factoring out common prefixes, thus:
<!ELEMENT parent (
                   (child1, ( (child2,child3)
                            | (child3,child2)))
                 | (child2, ( (child1,child3)
                            | (child3,child1)))
                 | (child3, ( (child1,child2)
                            | (child2,child1)))
                 ) >

This is less convenient than declarations for this model can be in other schema languages, and for more than three elements it's error prone and extremely tedious to do by hand.  But it's not impossible to declare the content model you want with DTDs.  Or perhaps I should say it's impossible only for DTD authors who are incapable of putting up with any inconvenience.
Note also that unless the sequence of children carries some information, some design authorities argue strongly that it's better to fix a sequence.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Moving from ISC DHCPd to Windows Server 2008 R2 DHCP I currently have a Linux server running ISC DHCPd and I'd like to eliminate this server and move to a Windows DHCP server. I'm wondering if there is an easy way to accomplish this or if someone could recommend some best practices?

A: The DNS servers in Windows Server 2003 and 2008 (R2) are capable of being configured textually using the netsh command. I'm not aware of any projects to parse the ISC DHCPd configuration file and output the equivalent netsh commands but it ought to be reasonably easy. (I see where some as written a REXX script to convert the other direction, but that's probably of limited utility to you.)
Some background on netsh should be able to get you started.


text:
Q: delay qTip call using setTimeout and clearTimeout  This was working fine:
$('#panel_derecho a.tooltip').each(function(){

  $(this).qtip({
     content: { url: '/includes/qtip.php?'+$(this).attr('rel')+' #'+$(this).attr('div'), text:''  },
     show: { delay: 700, solo: true,effect: { length: 500 }},
     hide: { fixed: true, delay: 200 },
     position: {
     corner: {
        target: 'topLeft',
        tooltip: 'middleRight'
                }
                },
     style: {
       name: 'light',
       width: 700,
       padding: 0,border: {
         width: 4,
         radius: 3,
         color: '#5588CC'
      }
       }
   });

});

but sometimes the user hovered while scrolling down the page and many calls to qtip that won't be shown where called so thought that adding a timeout was best go (isn't it?)
so i tried to set delayTip var with time to wait (while hover) and to clear it when mouse out:
$('#panel_derecho a.tooltip').each(function(){
    var delayTip;

       $(this).bind('mouseover',function(){
            delayTip = setTimeout(function () {
              $(this).qtip({
                 content: { url: '/includes/qtip.php?'+$(this).attr('rel')+' #'+$(this).attr('div'), text:''  },
                 show: { delay: 700, solo: true,effect: { length: 500 }},
                 hide: { fixed: true, delay: 200 },
                 position: {
                 corner: {
                    target: 'topLeft',
                    tooltip: 'middleRight'
                            }
                            },
                 style: {
                   name: 'light',
                   width: 700,
                   padding: 0,border: {
                     width: 4,
                     radius: 3,
                     color: '#5588CC'
                  }
                   }
               });
           }, 500);
       };
       $(this).bind('mouseout',function(){  clearTimeout(delayTip);  });

    });

the ting is that the tooltip is not shown and no errors are jumping in firebug,
what am I missing?

A: When the timeout fires the this keyword refers to the global object (most likely the window), try to do something like this:
$('#panel_derecho a.tooltip').each(function(){
    var delayTip = 0;
    var self = $(this);
    self.bind('mouseover',function(){
        if (delayTip === 0) delayTip = setTimeout(function () {
            self.qtip({
                content: { url: '/includes/qtip.php?'+self.attr('rel')+' #'+self.attr('div'), text:''  },
                show: { delay: 700, solo: true,effect: { length: 500 }},
                hide: { fixed: true, delay: 200 },
                position: {
                    corner: {
                        target: 'topLeft',
                        tooltip: 'middleRight'
                    }
                },
                style: {
                    name: 'light',
                    width: 700,
                    padding: 0,border: {
                        width: 4,
                        radius: 3,
                        color: '#5588CC'
                    }
                }
            });
            delayTip = 0;
        }, 500);
    };
    self.bind('mouseout',function(){ clearTimeout(delayTip); delayTip = 0; });
});


text:
Q: NotificationCenter observers are not receiving posts I have been trying for many hours to get notification posts to be received by an observer, but it has been failing me every time I try. I put the observer into my root view controller with is an embedded tab controller and tried to get one of the tab controllers to send a post for it to receive, but to no avail. I cannot, for the life of me, figure this out, and I'd really like to because notifications could be so freaking useful!
Here's my code:
ViewController
let myNotification = Notification.Name(rawValue:"categoryChange")

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func viewDidLoad() {
    super.viewDidLoad()
    let nc = NotificationCenter.default
    nc.addObserver(forName:myNotification, object:"test", queue:nil, using:test)
}

func test(notification:Notification) -> Void {
    print("Yo")
}

And here's my DashboardController:
override func viewDidLoad() {
    super.viewDidLoad()
    let myNotification = Notification.Name(rawValue:"categoryChange")
    let nc = NotificationCenter.default
    nc.post(name:myNotification,
            object: nil,
            userInfo:["message":"Hello there!"])
}

I have tried putting the observer into the init, viewDidLoad, and viewDidAppear while the post is in the viewDidLoad, and I did the vice versa. Nothing has worked so far, and I can't figure out why.
Thanks in advance to anyone who can help!

A: It works in my project.
Post Notification
 let dic: [String:AnyObject] = ["news_id": 1 as AnyObject,"language_id" : 2 as AnyObject]
     NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NotificationKeyIndentifier"), object: dic)

Notification Observer
          override func viewDidLoad() {
              super.viewDidLoad()
              NotificationCenter.default.addObserver(self, selector: #selector(self.handlePushNotification(notification:)), name: NSNotification.Name(rawValue: "NotificationKeyIndentifier"), object: nil)
          }
         func handlePushNotification(notification: NSNotification){

            if let dic = notification.object as? [String: AnyObject]{

                if let language_id = dic["language_id"] as? Int{

                    if let news_id = dic["news_id"] as? Int{
                        print(language_id)
                        print(news_id)
                    }
                }
            }
        }

A: Your problem is you are passing test (as String) with object parameter when you adding observer in NotificationCenter.
(From Documentation) object:

The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.
If you pass nil, the notification center doesn't use a notification's sender to decide whether to deliver it to the observer.

So it is the reason your notification is not getting called because you are not posting notification with the help of that object, simply set object to nil will works for you.
nc.addObserver(forName:myNotification, object:nil, queue:nil, using:test)


text:
Q: Prove that $S_{ABC}=2S_{MNP}$ We draw a line out of triangle $ABC$ and then we draw prepediculars $AA',BB',CC'$ to that line and name the mid point of those $M,N,P$.Prove that $S_{ABC}=2S_{MNP}$
We have midpoints and some trapezoid it is obvious that the area of that trapezoids becomes half but I don't know the rest.
Edit:$S$ is the area of the triangle.

A:
The area of the $\triangle ABC$ is expressed
in terms of coordinates $A(A_x,A_y),B(B_x,B_y),C(C_x,C_y)$
as
\begin{align}
S_{ABC}&=\tfrac12|(B_x-A_x)(C_y-A_y)-(C_x-A_x)(B_y-A_y)|
,\\
\text{similarly, }
S_{MNP}&=\tfrac12|(N_x-M_x)(P_y-M_y)-(P_x-M_x)(N_y-M_y)|
.
\end{align}
Let's consider the line $\mathcal{L}$ as the $x$-axis,
then
\begin{align}
A_x&=M_x,\quad B_x=N_x, \quad C_x=P_x
,\\
A_y&=2\,M_y,\quad B_y=2\,N_y,\quad C_y=2\,P_y
.
\end{align}
Then
\begin{align}
S_{ABC}&=\tfrac12|(N_x-M_x)(2\,P_y-2\,M_y)-(P_x-M_x)(2\,N_y-2\,M_y)||
=2\,S_{MNP}
.
\end{align}

A: $$
S_{ABC}=S_{A'ACC'}+S_{B'BCC'}-S_{A'ABB'}=
2(S_{A'MPC'}+S_{B'NPC'}-S_{A'MNB'})=2S_{MNP}
$$
[Diagram from g.kov's answer]

A: Let us take line $\frak{L}$ as the support of a first coordinate axis. Let the ordinate line be any line orthogonal to $\frak{L}$. Then triangle $MNP$ is the image of triangle $ABC$ by the affine transform given by matrix:
$$T=\left(\begin{array}{cc}1 & 0\\ 0 & \tfrac12 \end{array}\right).$$
It is well know that, whatever the figure $A$, the ratio of areas $\frac{S_{T(A)}}{S_A}$ is given by the determinant of transform $T$, i.e., $\tfrac12$.


text:
Q: Make Target _Blank With This Attacment PHP this php below will print like this http://example.com/wp-content/uploads/2013/01/imagename.jpg with anchor text 'DOWNLOAD'
<?php

if ( $attachments = get_children( array(
'post_type' => 'attachment',
'post_mime_type'=>'image',
'numberposts' => 1,
'post_status' => null,
'post_parent' => $post->ID
)));
foreach ($attachments as $attachment) {
echo wp_get_attachment_link( $attachment->ID, '' , false, true, 'Download');
}
?>

1.when user clicking this link, how to target in _blank or open in new tab.
2.is possible this short code combine with Javascript to make Force download link? look like bellow.
if ( $attachments = get_posts( array(
    'post_type' => 'attachment',
    'post_mime_type'=>'image',
    'numberposts' => -1,
    'post_status' => 'any',
    'post_parent' => $post->ID,
) ) );
foreach ( $attachments as $attachment ) {
    echo 'ID ) . '\');">
        Download This Wallpaper';
}

A: This is what I meant below in my response.
array(
'post_type' => 'attachment',
'post_mime_type'=>'image',
'numberposts' => 1,
'post_status' => null,
'post_parent' => $post->ID ,
'target' => 'target="_blank"';
)

See if it works this way.

A: amek teh chages and try this
 foreach ( $attachments as $attachment ) {
echo 'ID ) . '\');" target="blank">
    Download This Wallpaper';

}
hope this will helpt you


text:
Q: Add/Remove current_page_parent class I created some custom post types and custom taxonomies, if I'm on an archive page of the custom taxonomy, the Blog menu item is highlighted due to the current_page_parent class.
Well this is obviously false and I want to remove the class, but I also want to add it to another menu item.
How can I add and remove the current_page_parent class dynamically for all my custom taxonomies?
I'm currently removing the class with
function wpdev_nav_classes( $classes ) {
  if( is_archive() ){
    $classes = array_diff( $classes, array( 'current_page_parent' ) );
  }
  return $classes;
}
add_filter( 'nav_menu_css_class', 'wpdev_nav_classes', 10, 2 );

but I have no clue on how to add it to an other menu item, let's call the item Example.

A: Replace news with your custom post type and menu-item-000 with the menu item you want to highlight.
function wpdev_nav_classes($classes) {
    // Remove "current_page_parent" class
    $classes = array_diff( $classes, array( 'current_page_parent' ) );

    // If this is the "news" custom post type, highlight the correct menu item
    if ( in_array('menu-item-000', $classes) && get_post_type() === 'news' ) {
        $classes[] = 'current_page_parent';
    }

    return $classes;
}
add_filter('nav_menu_css_class', 'wpdev_nav_classes');

If you have more than one post type, it would be better to use a switch statement. Let me know if that's the case, and I'll update the code.


text:
Q: Is it okay to rewrite unit tests? I am still learning OOP, and each day I discover something foreign. So when writing unit tests, it looks like it's common to have function names, and the program design in general, already defined. "Test this factory or that dependency container to see if it works as expected", for example.
Being a learner, I am pretty sure I'd want to change a lot of things, from function names to the structure of the code to what the functions do themselves, over time. Obviously, this would mean rewriting the tests to make them pass. Did you face this problem? A few things I read speak like it is taboo to touch tests once written, so how do you solve this?

A:
it is taboo to touch tests once written

This is total nonsense, of course. Time passes, things change, code evolves, tests need to be touched. Feel free to amend and rewrite tests, but be careful to not accidentally lose functionality in the process (when rewritten version does not test cases that previous version did).
For me this problem simply doesn't exist.

A: As @Sergio said, of course you have to change tests if the class under test changes.
Just to note about changing tests in general: don't forget to make sure that the new test actually fails if the class under test is wrong. When you're doing new code and writing tests first, you get to see the test fail before you implement the new functionality and the test passes (TDD's "red/green" rhythm). When you're changing tests, you need to make sure you didn't just make a test that always passes.
For your question about changing things about the class under test (names, behaviour), you can easily do this in a test-first manner too:

*

*Change the test to reflect the changes you would like to make to the class under test

*Run the test to verify that it fails (or possibly won't compile, if name changes) [Red]

*Update the class and see the test pass [Green]

A: An important thing to remember is that test code is just as important as production code, if it's not, why bother with it at all? With this in mind, it's just as important to maintain and refactor your tests as it is to maintain and refactor your production code.
That said, I wouldn't recommend rewriting a test just because your knowledge has moved forward and you don't like the way you did it initially. If a test is testing something worthwhile, is understandable, and always passes, i'd leave it alone.

A: I think this depens on your programm. If you have a really huge programm you should not rewrite your tests if you are not sure that other functions uses that functions. If you are in the development you can change them if you are sure that this will make no trouble.


text:
Q: Keeping the main form tidy - conventions This is not a question about coding per se but about good practice in code structure. I'm currently building a WinForms application and already after a few hours in, my main form contains 130 lines of code. That might not be much but this only includes event handling - since I tried to avoid this exact situation by having seperate class files for basically everything ... but right now all the controls and events just make my main code pretty hard to read.
Now this is a topic I could find surprisingly little on and I do have some ideas on how to tackle this, like creating custom controls and splitting up the form into big portions. Is there a sort of best practice for this? How do you keep your main form clean when 80% of user interaction takes place here? Also is there a basic guideline on how to structure a project (not code) you can recommend?
(Hope this qualifies as a valid question)
Thanks!
EDIT: I decided to add in the code. See anything redundand?
public partial class MainForm : Form
{
    string currentFilter = "all";

    public MainForm()
    {
        InitializeComponent();
    }
    private void MainForm_Load(object sender, System.EventArgs e)
    {
        RefreshGenres();
        RefreshMovies(currentFilter);
    }

    private void addToolStripMenuItem_Click(object sender, System.EventArgs e)
    {
        var fAdd = new AddNewForm();

        fAdd.SetDesktopLocation(MousePosition.X, MousePosition.Y);
        fAdd.ShowDialog();
    }

    private void refreshToolStripMenuItem_Click(object sender, System.EventArgs e)
    {
        RefreshGenres();
        RefreshMovies(currentFilter);
    }

    private void addCategoryToolStripMenuItem_Click(object sender, System.EventArgs e)
    {
        tvCategories.Nodes.Add(new TreeNode("category"));
        tvCategories.Nodes[tvCategories.Nodes.Count - 1].BeginEdit();
    }
    private void tvCategories_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
    {
        var genre = e.Label;
        var writer = new Writer();
        writer.AddGenre(e.Label);

    }

    private void everythingToolStripMenuItem_Click(object sender, System.EventArgs e)
    {
        EraseData("all");
    }
    private void clearGenres_Click(object sender, System.EventArgs e)
    {
        EraseData("genres");
    }
    private void clearMovies_Click(object sender, System.EventArgs e)
    {
        EraseData("movies");
    }
    private void EraseData(string eraseThis)
    {
        DialogResult r = MessageBox.Show("Are you sure?\nLost data can NOT be retrieved.", "Clear Data", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

        var cmdText = "";

        if (r == DialogResult.Yes)
        {
            switch (eraseThis)
            {
                case "all":
                    cmdText = "TRUNCATE TABLE MOVIES GENRES";
                    break;

                case "movies":
                    cmdText = "TRUNCATE TABLE MOVIES";
                    break;

                case "genres":
                    cmdText = "TRUNCATE TABLE GENRES";
                    break;
            }
            conn.Open();
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = cmdText;
                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }
    }

    private void RefreshGenres()
    {
        tvCategories.Nodes.Clear();

        var reader = new Reader();
        var genres = reader.GetGenreList();

        foreach (string str in genres)
        {
            tvCategories.Nodes.Add(str);
        }
    }
    private void RefreshMovies(string filter)
    {
        lvMovies.Items.Clear();

        var reader = new Reader();
        var movies = reader.GetMovieList(filter);

        foreach (ListViewItem item in movies)
        {
            lvMovies.Items.Add(item);
        }
        reader.conn.Close();

    }

    private void tvCategories_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
    {
        currentFilter = e.Node.Text;
        RefreshMovies(currentFilter);
    }
}

A: I think that the problem here is not the length of your code, but the fact that you are mixing up many different things and that you are not dealing with your events in a consistent way.
These are the main things that I would change:
EraseData: this method opens and uses a DB connection, and this is something that you usually should avoid (changing something in the DB would cause you to modify the UI code), your WinForm code should not know where the data it is exposing come from. Here you'd be better adding an EraseData to your Writer class.
RefreshMovies: it is quite different from RefreshGenres, even if both of these methods do essentially the same thing: they are getting lists of data which are added to some UI controls. RefreshGenres seems ok, but looking at RefreshMovies you immediately see that you are closing a connection that was not opened in this method. Probably you opened it in the Reader class, but that's the place where you should have closed it, too. In fact, it'd be better for conn to be private (remember, UI doesn't have to know whether data come from a DB, a text file, or a user input). Furthermore GetGenreList of Reader returns a list of strings, which is ok, but GetMovieList returns a list of ListViewItem, which is not good because this is something strongly related to your specific implementation of UI. This means that your implementation of Reader could not be used in a WPF or web application. the ListViewItems should be created in RefreshMovies using plain data got from the Reader.


text:
Q: D3 v4 graph not updating bars - but appending new axis data I have seen this type of question asked a lot but no answers i found solved it for me.
I created a fiddle here of a stripped down simplified version of my code
https://jsfiddle.net/00m2cv84/4/
here is a snippet of the ganttish object - best to check out the fiddle though for context
const ganttish = function (data) {
  this.dataSet = data
  this.fullWidth = +document.getElementById('chart').clientWidth
  this.fullHeight = 700
  this.pad = { top: 50, right: 50, bottom: 50, left: 50 }
  this.h = this.fullHeight - this.pad.top - this.pad.bottom
  this.w = this.fullWidth - this.pad.left - this.pad.right
  this.svg = d3.select('#chart')
    .append('svg')
    .attr('width', this.fullWidth)
    .attr('height', this.fullHeight)
}

ganttish.prototype = {
  redraw (newDataSet) {
    this.dataSet = newDataSet // this should overwrite the old data
    this.draw()
  },
  draw () {
    let y = d3.scaleBand()
    .padding(0.1)
    .range([0, this.h])
    y.domain(this.dataSet.map(d => d.idea_id))

    let x = d3.scaleTime().range([this.pad.left, this.w + this.pad.left])
    x.domain([
      d3.min(this.dataSet, d => new Date(Date.parse(d.start_date))),
      d3.max(this.dataSet, d => new Date(Date.parse(d.end_date)))
    ])

    let xAxis = d3.axisBottom(x).tickSize(-(this.h), 0, 0)
    let yAxis = d3.axisLeft(y).tickSize(-(this.w), 0, 0)

    let xA = this.svg.append('g')
      .attr('transform', 'translate(0,' + this.h + ')')
      .attr('class', 'x axis')
      .call(xAxis)

    let yA = this.svg.append('g')
      .attr('transform', 'translate(' + this.pad.left + ', 0)')
      .attr('class', 'y axis')
      .call(yAxis)

    let timeBlocks = this.svg.selectAll('.timeBlock')
      .data(this.dataSet)

    let tbGroup = timeBlocks
      .enter()
      .append('g')

    tbGroup
      .append('rect')
      .attr('class', 'timeBlock')
      .attr('rx', 5)
      .attr('ry', 5)
      .attr('x', d => x(new Date(Date.parse(d.start_date))))
      .attr('y', d => y(d.idea_id))
      .attr('width', d => parseInt(x(new Date(Date.parse(d.end_date))) - x(new Date(Date.parse(d.start_date)))))
      .attr('height', d => y.bandwidth())
      .style('fill', (d) => {
        return d.color ? d.color : 'rgba(123, 173, 252, 0.7)'
      })
      .style('stroke', 'black')
      .style('stroke-width', 1)

    tbGroup
      .append('text')
      .attr('class', 'timeBlockText')
      .attr('x', d => x(new Date(Date.parse(d.start_date))) + 10)
      .attr('y', d => y(d.idea_id) + (y.bandwidth() / 2))
      .attr('alignment-baseline', 'middle')
      .attr('font-size', '1em')
      .attr('color', 'black')
      .text(d => d.name)

    /**
      I have literally tried exit().remove() on pretty much everything i could think of :(
      this.svg.exit().remove()
      timeBlocks.exit().remove()
      this.svg.selectAll('.timeBlock').exit().remove()
      this.svg.selectAll('.timeBlockText').exit().remove()
      this.svg.select('.x').exit().remove()
      this.svg.select('.y').exit().remove()
    */
  }

Sidenote:
I have a Vue js application and i'm implementing a Gantt(ish) style horizontal bar chart.  In the fiddle i have simulated the Vue part by creating an Object which then you call the redraw method on it, this pattern simulates a watcher in the component updating the dataset when the parent data changes.  The issue i face is the same.
issue:
When i change the data to the chart it does not update my chart rects or text.  It does however append the new axis' on top of the old ones.
i understand that i should be calling .exit().remove() on anything .enter() 'd when finished in order to clear them for the next data push, but everywhere i try this it fails.  I can get it to work by creating a fresh svg on every draw, but i understand i won't be able to do any transitions - and it seems a very bad approach :)
What is twisting my noodle is that if i push extra data to the new data object, it appends it fine, once - then does not do it again.  It seems once element X in the data array has been added it will not update again.
https://jsfiddle.net/00m2cv84/5/
I know that the this.dataSet is updating, it just does not seem to be accepted by D3
Any help would be greatly appreciated for a D3 noob :)

A: You're problem is that you're not handling your data join properly. I'd highly recommend reading some of Mike Bostock's examples probably starting with Three Little Circles. To summarize though:
D3 joins created by calling .data() contain 3 selections:

*

*Enter (DOM elements that need to be created as they exist in the data but don't yet exist in the DOM)

*Exit (DOM elements that need to be removed, as they're not longer represented in the data)

*Update (DOM elements that already exist and still exist in the data)

Within your code you're handling the enter() selection with this bit of code:
let tbGroup = timeBlocks
  .enter()
  .append('g')

The problem is you're not handling any of the other selections. The way I'd go about doing this is:
let join = this.svg.selectAll('.timeBlock').data(this.dataSet);

// Get rid of any old data
join.exit().remove();

// Create the container groups. Note that merge takes the "new" selection
// and merges it with the "update" selection. We'll see why in a minute
const newGroups = join.enter()
                      .append('g')
                       .merge(join);

// Create all the new DOM elements that we need
newGroups.append("rect").attr("class", "timeBlock");
newGroups.append('text').attr('class', 'timeBlockText');

// We need to set values for all the "new" items, but we also want to
// reflect any changes that have happened in the data. Because we used
// `merge()` previously, we can access all the "new" and "update" items
// and set their values together.
join.select(".timeBlock")
    .attr('rx', 5)
    .attr('ry', 5)
    .attr('x', d => x(new Date(Date.parse(d.start_date))))
    .attr('y', d => y(d.idea_id))
    ...

join.select(".timeBlockText")
    .attr('x', d => x(new Date(Date.parse(d.start_date))) + 10)
    .attr('y', d => y(d.idea_id) + (y.bandwidth() / 2))
    .attr('alignment-baseline', 'middle')
    .attr('font-size', '1em')
    .attr('color', 'black')
    .text(d => d.name)


text:
Q: Angular - How to wrap a dynamically loaded component in another component I would like to dynamically add components to a Angular app using the ViewContainerRef API.
The dynamically created components should be wrapped by another component within the project but I don't understand how I can do this without creating additional "wrapping components".
Ideally: I would like to define how the new component is wrapped in the component that creates the dynamic components.
Expected result in DOM:
<div class="container">
   <wrapping-component>
      <sub-component></sub-component>
   </wrapping-component>
   <wrapping-component>
      <sub-component></sub-component>
   </wrapping-component>
</div>

In order to create the structure above with my current solution I would have to create a "wrapper component" which in its turn creates the SubComponent. Is that the preferred way to solve this or are there better options?
Angular dynamic-component-loader


text:
Q: Removes outlier points that aren't part of the ellipse's points I want to remove the points that are not part of the ellipse's point like in this image :

I've implemetend the function getactualcontours to remove outlier points that aren't part of the ellipse's points but it did not remove them .
def getactualcontours(contours,bin):
  """
  Removes outlier points that aren't part of the ellipse's points
  input: contours, and a parameter()
  output : contours
  """
  actualcontours=[]
  average=getaverage(contours)
  for j in contours:
    avgdistance=[]
    centerj=getcenter(j)
    for i in contours:
      centeri=getcenter(i)
      dx= centeri[0] - centerj[0]
      dy = centeri[1] - centerj[1]
      D = np.sqrt(dx*dx+dy*dy)
      avgdistance.append(D)
    if((sum(avgdistance)/len(avgdistance))<average+bin): actualcontours.append(j)
  return actualcontours

def getcenter(contours):
  """
  gets the center of the contour
  input : contours
  output : float
  """
  M = cv2.moments(contours)
  try:
    cX = int(M['m10'] /M['m00'])
    cY = int(M['m01'] /M['m00'])
    return [cX,cY]
  except:
    return [0,0]

def getaverage(contours):
  """
  gets the average of all the average distances of every point (to compare the outlier point to this average)
  input : contours
  output : float
  """
  avgavg=[]
  for j in contours:
    avgdistance=[]
    centerj=getcenter(j)
    for i in contours:
      centeri=getcenter(i)
      dx= centeri[0] - centerj[0]
      dy = centeri[1] - centerj[1]
      D = np.sqrt(dx*dx+dy*dy)
      avgdistance.append(D)
    avgavg.append((sum(avgdistance)/len(avgdistance)))
    if len(avgavg)!=0:
      return (sum(avgavg)/len(avgavg))
    else:
      return 1


text:
Q: report builder - queries returning incorrect results I have set a reporting project where I would like to get stats for my tables and later integrate this into a webservice. For the following queries though, I am getting incorrect results and I will note where below:
1 - Get the number of new entries for a given day
 SELECT COUNT(*) AS RecordsCount,CAST(FLOOR(CAST(dateadded AS float))
 AS datetime)as collectionDate
 FROM TFeed GROUP BY CAST(FLOOR(CAST(dateadded AS float))
 AS datetime) order by collectionDate

works fine and I am able to put this in a bar graph successfully.
2 - Get the top 10 searchterms with the highest records per searchterm requested by a given client in the last 10 days
SELECT TOP 10 searchterm, clientId, COUNT(*) AS TermResults FROM TFeed
where dateadded > getdate() - 10 GROUP BY
searchterm,clientId order by TermResults desc

does not work
If I do a query in the Database for one of those terms that returns 98 in the report, the result is 984 in the database.
3 - I need to get the number of new records per client for a given day as well.
Also I was wondering if it is possible to put these queries into one report and not individual reports for each query which is not a big deal but having to cut and paste into one doc afterwards is tedious.
Any ideas appreciated

A: For #2,
WITH tmp as
(
 SELECT clientId, searchTerm, COUNT(1) as TermResults,
   DENSE_RANK() OVER (partition by clientId
    ORDER BY clientId, COUNT(1) DESC) as rnk
 FROM TFeed
 WHERE dateadded > GETDATE() - 10
 GROUP BY clientId, searchterm
)
SELECT *
FROM   tmp
WHERE rnk < 11

USE RANK() if you want to skip a rank if there are two matches (if lets say term1 and term2 have the same number of count, they are both rank 1 and the following term will be ranked 3rd instead of 2nd
For #3,
you can define multiple datasets within one report. Then you would just create three charts / table and associate those with their respective datasets


text:
Q: Javascript - Object Notation Script vs Object Oriented Script I have been working on web applications for very long time. Worked with most experienced technical architects. Everywhere I used javascript in object notation with namespaces.
var web = {};
web.app = {};
web.app.customer = {
    name: 'John',
    getName: function(){
        return 'The name is ' + this.name;
    }
};

document.write(web.app.customer.getName());

But, when I look for any object oriented javascript, we come with function and creating object of it by calling its constructor.
function Customer(name){
    this.name = name;
    this.getName = function(){
        return 'The name is ' + this.name;
    }
}

var cust = new Customer('Bob');
document.write(cust.getName());

I am not sure why architects advised me the former approach(namespace) always. I never used the latter approach, whereas the latter one is object oriented javascript.

*

*Cant we have object oriented javascript with namespace notation(former one)? If so can you create an object of that and inherit them.

*Why can't I have private fields in first approach(namespace)? If I declare any field with var, javascript error is thrown.

A: The only difference between the two approaches is that the former (literal notation) creates one specific object, while the latter defines a constructor function which can be used to create objects. It's the difference between being able to only have one object (asterisk argument about object cloning here), and being able to instantiate many similar objects from the same template ("class").
Both are equally valid, depending on what you want. Both are equally object oriented.

Cant we have object oriented javascript with namespace notation(former one)? If so can you create an object of that and inherit them.

web.app.Customer = function (name) {
   ..
};

Why can't I have private fields in first approach(namespace)? If I declare any field with var, javascript error is thrown.

Because "private fields" don't exist in Javascript. You can use the characteristics of closures/variable scoping to emulate something like "private properties". But for that you obviously need a function. With an object literal notation, you don't get that.


text:
Q: laying out month names in two columns using css what HTML and CSS would you use to layout the names of the months in two columns like:
january july
feb     aug
mar     sep
apr     oct
may     nov
jun     dec

month names are coming from an array and html is dynamically generated for i18n purposes.
If it was:
january february
mar     apr
 ...

I would just put them in a DIV, all with double the width of a single month + some space and float them. but ordering them as stated seems more complicated...
Must i introduce two additional DIVs for the columns ?

A: I would just use a single div and assign the following CSS
column-count: 2;
-moz-column-count: 2;
-webkit-column-count: 2;

This creates 2 columns that are filled with the data given.
Further reading: column-count@MDN and multi column layouts @caniuse.com

A: You can try to generate this html:

MONTH FROM 1 TO 6

MONTH FROM 7 TO 12

Of course you can move the styles definition to a CSS stylesheet

A: If the HTML is generated, you could do something like this (jsFiddle):


text:
Q: deleting pages from pdf I am writing a replacement for \include that will only include the file if it has been modified. To do this I need to delete or extract files from a pdf. I am using lua to do all this.
I see there are some cmd line tools to do it: http://www.verypdf.com/wordpress/201112/delete-specified-pdf-pages-using-command-line-15756.html
But is there any easier way? Ultimately I would like to extract/copy only a subset of pages from a pdf to a new pdf rather than copy the whole file(which may be large) into another then delete the pages.


text:
Q: How to add textfield in inside appbar action widget? When i am trying to add textfield in Appbar, inside action widget, its showing error like "RenderBox was not laid out: RenderRepaintBoundary#a81ba NEEDS-LAYOUT NEEDS-PAINT", Have u guys anyone know how to add textfield in appbar, inside actions, please add,
When i am trying to add
             actions:[
            TextField()
               ],

The error is like
               ════════ Exception caught by rendering library
                ═════════════════════════════════
        RenderBox was not laid out: RenderRepaintBoundary#a81ba NEEDS-LAYOUT NEEDS-PAINT
          'package:flutter/src/rendering/box.dart':
     package:flutter/…/rendering/box.dart:1
      Failed assertion: line 1982 pos 12: 'hasSize'

A: You need to give it some width (height is optional) like:
actions: [
  SizedBox(
    width: 50,
    child: TextField(),
  )
]


text:
Q: Translate special character ½ I am reading a source that contains the special character ½. How do I convert this to 1/2? The character is part of a sentence and I still need to be able to use this string "normally". I am reading webpage sources, so I'm not sure that I will always know the encoding??
Edit: I have tried looking at other answers, but they don't work for me. They always seem to start with something like:
s= u'£10"

but I get an error already there: "no encoding declared". But do I know what encoding I'm getting in, or does that not matter? Do I just pick one?

A: This is really two questions.
#1. To interpret ½:  Use the unicodedata module.  You can ask for the numeric value of the character or you can normalize using a canonical normalization form it and parse it yourself.
>>> import unicodedata
>>> unicodedata.numeric(u'½')
0.5
>>> unicodedata.normalize('NFKC', u'½')
'1⁄2'

#2. Encoding problems: If you're working with the terminal, make sure Python knows the terminal encoding.  If you're writing source files, make sure Python knows the file encoding.  You can't just "pick" an encoding to set for Python, you must inform Python about the encoding that your terminal / text editor already uses.
Python lets you set the encoding of files with Vim/Emacs style comments.  Put a comment at the top of the file like this if you use Vim:
# coding=UTF-8

Or this, if you use Emacs:
# -*- coding: UTF-8 -*-

If you use neither Vim nor Emacs, then it doesn't matter which one.  Obviously, if you don't use UTF-8 you should substitute the encoding you actually use.  (UTF-8 is the only encoding I can recommend.)

A: Dietrich beat me to the punch, but here is some more detail about setting the encoding for your source file:
Because you want to search for a literal unicode ½, you need to be able to write it in your source file. Unfortunately, the Python interpreter chokes on any unicode input, unless you specify the encoding of that source file with a comment in the first couple of lines, like so:
 # coding=utf8
 # ... do stuff here ...

This assumes your editor is saving the file as UTF-8. If it's using a different encoding specify that instead. See PEP-0263 for more details.
Once you've specified the encoding you should be able to write something this in your code:
text = text.replace('½', '1/2')

Encoding of the webpage
Depending on how you are downloading the page, you probably don't need to worry about this at all, most HTTP libraries handle choosing the encoding for you automatically.

A: Did you try using codecs to read your file? [docs]
import codecs
fileObj = codecs.open( "someFile", "r", "utf-8" )
u = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file

You can check the whole guide here.
Also a good ref: http://docs.python.org/howto/unicode


text:
Q: 2 circles $C_1, C_2$ of radius $a$ and $b$ touch each other externally and they both touch a unit circle $C$ internally. Show $a+b=1$
2 circles $C_1, C_2$ of radius $a$ and $b$ touch each other externally and they both touch a unit circle $C$ internally. A circle $C_3$ of radius $r$ is inscribed to touch the circles $C_1, C_2$ externally and the circle $C$ internally. Show that $r=\frac{ab}{1-ab}$.

The solution starts by saying $2a+2b=2$.
I am having a hard time understanding it.
Can someone explain it to me in simple terms? If possible please attach a diagram.

A: It would be true if $C_1$ and $C_2$ had their centers on a diameter of $C$.  In the figure below the sum of the radii of circles $C$ and $E$ is much smaller than the radius of circle $A$


text:
Q: Avoid memory allocations for formatting paths I want to avoid memory allocations to construct the path for device
    char *device;
    const char *p;
    char buf[PATH_MAX];

Witch method is memory less use
PATH_MAX
    snprintf(buf, sizeof(buf) - 1, "/dev/%s", p);
    device = &buf[0];

or
asprintf
    asprintf(&device, "/dev/%s", p);

A: asprintf allocates the memory needed dynamically while the first method declares a (probably) larger buffer on the stack. So asprintf uses exactly as much bytes as needed and char buf[MAX] does not. But you have to make sure you free the memory allocated in asprintf yourself

A: The most significant difference is not the few bytes of memory, but where the memory is coming from and how you need to handle it afterwards.

*

*buf is allocated on the stack, and if you return from the function your snippet is coming from, then device will not point to a valid memory location anymore. Corruption or a crash will be the most likely outcome. On the other hand, if you only use device inside the function, you won't have to free it afterwards. Also, stack-allocated memory is more efficient in general, although caching and optimizations may equal the picture.

*asprintf allocates the memory from the heap, which means you can safely pass it around to all parts of your program as long as it runs. The downside is that you have to free it when you don't need it anymore or it will hang around forever and you have a memory leak (which might matter or not, depending on how many unfreed buffers are floating around). It's then your responsibility to free the memory.

But to answer your question: asprintf will allocate no more bytes than needed, and you don't have to specify a maximum size which might "feel" better. You probably shouldn't worry about a few bytes of stack memory extra though. How big is PATH_MAX? Half a kilobyte?


text:
Q: How these python for loop and slicing working?
*

*How this statement will work?
j for i in range(5)

Example:
x1=(j for i in range(5))

will yield five 4's when iterated. Why it will not yield 01234 like when we replace j with i.

*How this statement working?
a = [0, 1, 2, 3]
for a[-1] in a:
    print(a[-1])
0
1
2
2

A: Your first example is a generator expression (the parentheses are required, so the first version you show doesn't actually make sense). The generator expression repeatedly yields j, which is not defined in the code you show. But from your description, it already has the value 4 in the environment you were testing in, so you see that value repeatedly. You never use the i value, which is what's getting the values from the range.
As for your other loop, for a[-1] in a keeps rebinding the last value in the list, and then printing it.
A for loop does an assignment to the target you give it between for and in. Usually you use a local variable name (like i or j), but you can use a more complicated assignment target, like self.index or, as in this case, a[-1]. It's very strange to be rewriting a value of your list as you iterate over it, but it's not forbidden.
You never get 3 printed out, because each of the previous assignments as you iterated overwrote it in the list. The last iteration doesn't change the value that gets printed, since you're assigning a[-1] to itself.

A: Your first question raises error when iterating, as j is not defined. If you are getting any response from that, you probably have defined a value for j above your generator, which sounds to be 4 in your code.
About your second question:
when you have something like this:
for i in a:
    ...

Actually you are are doing this in each cycle: i=a[0], i=a[1], ....
When you write a[-1] in a, it is kind of equal to: a[-1]=a[0], a[-1]=a[1], ... and you are changing last element of a each time. So at the end, the last element of your list would be 2.


text:
Q: File explorer GUI for a running docker container? Is it possible to have a GUI file explorer (e.g. like winscp/windows or nautilus/linux) on my host machine that can show the filesystem of a running docker container?
Primarily interested in a GUI for Linux/Ubuntu

A: Docker uses cgroups for isolation.
You should be able to browse the docker container's filesystem directly via the procfs. Specifically, if you browse /proc/<pid>/root/, where <pid> is the PID of a process within the container.
From the Moby issue tracker:
docker inspect --format {{.State.Pid}} $YOUR_CONTAINER

Should give you a PID.
Therefore, from the command line, you could cd into:
/proc/$(docker inspect --format {{.State.Pid}} $YOUR_CONTAINER)/root

You should then be able to browse to that same directory from your GUI file browser. However, you likely will not be able to use the $() construct directly, which leaves you with either:

*

*Using a CLI to launch a GUI file explorer pointing to that path

or

*

*Using a CLI to retrieve the PID and then browse directly there in the GUI, e.g. /proc/123/root


text:
Q: Disable joblib.memory caching globally during unittest I use the joblib.Memory module to cache some functions within several modules. The cache is initialized within modules and classes separately.
Module1:
memory = Memory(location='/cache/')
@memory.cache
def heavy_function(...)
    .....

Module2:
memory = Memory(location='/cache/')
@memory.cache
def heavy_function2(...)
    .....

Module3:
import Module1
import Module2

def heavy_function3(...)
    Module1.heavy_function1(...)
    Module1.heavy_function1(...)
    .....

Now I have a unit testing script and I want to disable the usage of the cache globally during the unit testing to make sure everything is correctly computed.
Is this possible without manually disabling it for each module via
Module1.memory.cachedir=None or without deleting the cachedir?
My current solution just patches each memory call manually
unittest1:
from joblib import Memory
import Module1
Module1.memory = Memory(location=None)
...
unittest.run()

unittest3:
from joblib import Memory
import Module1 # need to import module 1 just to disable its memory
import Module2 # need to import module 2 just to disable its memory
import Modul3
Module1.memory = Memory(location=None)
Module2.memory = Memory(location=None)
...
unittest.run()

The more modules I create, the more manual patching up of the Memory I need. I thought there might be a better solution. One work-around is proposed by me below.

A: One work-around is to set a flag or an environment variable when running tests. Then check for these flags before initializing the Memory:
Module1
import os
memflag = os.environ.get('UNITTESTING', False)
memory = Memory(location= None if memflag else '/cache/')
@memory.cache
def heavy_function(...)
    .....

unittest1
os.environ["UNITTESTING"] = '1'
import Module1
.....
unittest.run()
del os.environ["UNITTESTING"]

A: To disable joblib.memory caching globally I would look at calling register_store_backend to overwrite the default 'local' FileSystemStoreBackend with a DummyStoreBackend that does nothing.
Something like the following, noting that DummyStoreBackend is copied from the unit tests for Memory, and I have not yet tested if this works as intended
from joblib.memory import register_store_backend
from joblib._store_backends import StoreBackendBase

class DummyStoreBackend(StoreBackendBase):
    """A dummy store backend that does nothing."""

    def _open_item(self, *args, **kwargs):
        """Open an item on store."""
        "Does nothing"

    def _item_exists(self, location):
        """Check if an item location exists."""
        "Does nothing"

    def _move_item(self, src, dst):
        """Move an item from src to dst in store."""
        "Does nothing"

    def create_location(self, location):
        """Create location on store."""
        "Does nothing"

    def exists(self, obj):
        """Check if an object exists in the store"""
        return False

    def clear_location(self, obj):
        """Clear object on store"""
        "Does nothing"

    def get_items(self):
        """Returns the whole list of items available in cache."""
        return []

    def configure(self, location, *args, **kwargs):
        """Configure the store"""
        "Does nothing"

register_store_backend("local", DummyStoreBackend)

A: You can patch it at import time like so:
with patch("joblib.Memory") as mock_memory:
    mock_memory.return_value.cache = lambda x: x

# then proceed with your tests
def test_whatever():
    assert True

mock_memory.return_value.cache = lambda x: x sets joblib.Memory.cache to return the input, ie it won't modify the function that it decorates.


text:
Q: Is checked=no valid in HTML checkboxes? So, I've been fixing up my website. My website of course generates HTML from a "view".
Right now, a portion of my view looks like this:
<input type="checkbox" name="Publish" checked="{=Entry.Publish ? "yes" : "no" =}" value="true" />

This is the easiest way to go about this. However, when it generates checked="no", the checkbox will still be checked by default whenever I load the page. Do I really have to exclude the checked attribute all together for it to not be checked?
Also, I'm using HTML5 as my doctype.

A: Short version: yes, it needs to be excluded.
The value of the attribute is irrelevant, as long as it is present, the box will be checked.
<input type="checkbox" name="Publish" value="true" checked />

This is valid in HTML5.
In XHTML, the attribute needed a value and the convention was checked="checked" since values like "yes" or "true" implied that the opposites would uncheck the box, which is not true and would confuse beginners.  Similar conventions were adopted for readonly="readonly" and disabled="disabled".

A: Yes. checked is a bool attribute that is "off" when it's absent and "on" when it's present.
W3C reference for boolean attributes and for checked attribute.

A: from the spec

checked = "checked" or "" (empty string) or empty
Specifies that the element represents a selected control.

A: You want to include checked if it's to be checked, otherwise omit the attribute.


text:
Q: Reconciling the Markov property for different types of time Suppose $\mathbf{X} = \{X_t\}_{t \in T}$ is a random process, with $T$ being totally ordered. Let $\{\mathcal{F}_t\}_{t \in T}$ be the natural filtration generated by $\mathbf{X}$.
I have seen the following definitions of the Markov property.

*

*We say $\mathbf{X}$ is Markov if, for every bounded Borel function $h\colon \mathbb{R} \to \mathbb{R}$,
$$\mathbf{E}[h(X_t) \vert \mathcal{F}_s] = \mathbf{E}[h(X_t) \vert X_s] \quad \forall s < t, \, s, t \in T.$$

*If $T$ is discrete (say, $T = \mathbb{Z}_{\ge 0}$), and $X_t$ takes values in a common countable set $\mathcal{S}$ for every $t \in T$, then we say $\mathbf{X}$ is Markov if
$$\mathbf{P}(X_{n + 1} = x_{n + 1} \vert X_n = x_n, \, X_{n - 1} = x_{n - 1}, \, \dots, \, X_0 = x_0) = \mathbf{P}(X_{n + 1} = x_{n + 1} \vert X_n = x_n)$$
for every nonnegative integer $n$ and every sequence $\{x_k\}_{k = 0}^{\infty} \subseteq \mathcal{S}$.

*If $T$ is continuous (say, $T = \mathbb{R}_{\ge 0}$), and $X_t$ takes values in a common countable set $\mathcal{S}$ for every $t \in T$, then we say $\mathbf{X}$ is Markov if
$$\mathbf{P}(X_{t_{n + 1}} = x_{n + 1} \vert X_{t_n} = x_n, \, X_{t_{n - 1}} = x_{n - 1}, \, \dots, \, X_{t_0} = x_0) = \mathbf{P}(X_{t_{n + 1}} = x_{n + 1} \vert X_{t_n} = x_n)$$
for every nonnegative integer $n$, every increasing sequence $\{t_k\}_{k = 0}^{\infty} \subseteq T$ and every sequence $\{x_k\}_{k = 0}^{\infty} \subseteq \mathcal{S}$.
I believe the first is the most general, since there is no restriction on the type of time we are dealing with.
How do we show that the first is equivalent to the second and equivalent to the third in the respective time contexts?
I believe to handle equivalence to the second, we can use the fact that $\mathcal{F}_n$ is generated by the countable collection of events
$$\{\{X_0 = x_0, \, X_1 = x_1, \, \dots, \, X_n = x_n\} \;\vert\; \{x_k\}_{k = 0}^{n} \subseteq \mathcal{S}\},$$
but I am not so sure about equivalence to the third.


text:
Q: What controls a laptop's fan speed? Vostro 3560 overheating I own a vostro 3560 and I know about the terrible ventilation and heat dissipation problems it has. I've tried several configurations of the copper sheet fix, but what I've found is that my system's fan is very active for the initial 5 to 10 minutes and then, and specially if I watch video (youtube in brower or PotPlayer, the fan seems to idle at 2600 RPM and does not ramp up to cool the system down.
I've noticed that after I installed HWiNFO64, I find myself pressing the Fan button and then the System Auto button, but if HWInfo is NOT open or is not on top of other windows, the fan will only idle.

What exactly controls or tells the fan at what speed should it spin?
Could I have messed up those values installing HWiNFO64? I've reinstalled the BIOS, the video drivers but the solution is always the same: fan is quite active at startup, only to stay at idling speeds while watching video and eventually, laptop shuts down due to intense overheating.
Hope someone can point me to a productive and useful suggestion as to what I can do to regain proper fan speeds.
These values are almost at idle, just typing on a browser and BitTorrent running in the background:

A: Usually the BIOS controls the fan speed
If you can take a look at your fan on your laptop here is a thing to remember
2-wires
Thermally controlled
3 or 4-wires
PWM Controlled (Pulse Width Modulation) (BIOS)
3 wire
Wire color Black and Red (Power)
Other color (usually yellow) (RPM Read)
4 wire
Wire color black (common ground)
All other colors represent of the 3 wires of each pole (confirmation on answer required) (haven't had one of these fans yet to determine correctly)
Also if you have one of those laptops that have pices that come off like a ram door, hdd door with out anything falling off and or out and disrupt what you are doing then raise the back end of the laptop by using a cooler pad you can get somewhere as I had an HP Laptop that got extremely warm to too hot to use doing this I would recommend only as a last resort as you can actually disconnect the hard drive and or bump the ram and it will just shut off to just add air flow if you still want to use that laptop


text:
Q: Getting error of timeout exceed in mocha mocha error: timeout of 2000ms exceeded, for async test and hooks ensure the done() callback is being called in this test. if returning a promise, ensure it resolves.
This is what  the error i am getting while trying to get response,
This is my index.js file where i export function
exports.info = function(callback) {
    var https = require('https');
    var options = {
     host: 'api.github.com',
     path: '/repos/sayanee/build-podcast',
     method: 'GET',
     headers: { 'User-Agent': 'sayanee' } };
    var str = '';

    https.request(options, function(response) {
    response.on('data', function(data) {
        str += data;
    });

     response.on('end', function() {
       callback(JSON.parse(str));
     })

     response.on('error', function(error) {
       console.log(error);
       callback();
    })
})    .end();
}

This is my indexfile where i describe the test cases
function asyncFunction() {
    return new Promise(resolve => {
        setTimeout(resolve, 5000);
    });
}
describe('Github info', function() {
it.only('returns repo info from github', async function() {
    //this.timeout(5000);
    await asyncFunction();
    word.info(function(reply) {
        console.log("er")
        expect(reply.language).to.equal('JavaScript');
        expect(reply.watchers).to.equal(157);
        console.log('RECEIVED');

    });
    console.log('HELLO'); })
});

A: Mocha support async test also by passing done callback as param to it that you need to call at test end
describe("Github info", function () {
    it.only("returns repo info from github", function (done) {
        // set long timeout to be sure word.info finish
        this.timeout(5000);
        word.info(function (reply) {
            console.log("er");
            expect(reply.language).to.equal("JavaScript");
            expect(reply.watchers).to.equal(157);
            console.log("RECEIVED");
            // call done at end
            done();
        });
        console.log("HELLO");
    });
});

A: The response is in your question. Mocha is setted up to timeout after 2 second.

Either you makes your request to finish within 2000ms

Either you increase the Mocha timeout, example :
mocha -t 300000

EDIT :
You cannot use async/await mixed up with callbacks
// Wrap your function into a promise
wordInfoPromise() {
  return new Promise((resolve, reject) => {
    word.info((ret) => {
      if (!ret) return reject();

      return resolve(ret);
    });
  });
}

it('returns repo info from github', async function() {
    //this.timeout(5000);
    await asyncFunction();

    const reply = await wordInfoPromise();

    console.log("er")

    expect(reply.language).to.equal('JavaScript');

    expect(reply.watchers).to.equal(157);

    console.log('RECEIVED');

    console.log('HELLO'); })
});

EDIT 2 :
    const req = https.request(options, (res) => {
      res.on('data', (d) => {
        str += data;
      });

      res.on('end', () => {
        resolve(str);
      });
    });

    req.on('error', (e) => {
      reject();
    });

    req.end();


text:
Q: syslog-ng logs sent to multiple destination I'm getting remote nginx syslogs going to both /var/log/nginx and /var/log/splunk on my syslog-ng server.  How do I only get it to go to /var/log/nginx?
#/etc/syslog-ng/syslog-ng.conf
source s_sys {
    system();
    internal();
    udp(ip(0.0.0.0) port(514));
};

destination d_splunk { file("/var/log/splunk/$HOST-$PROGRAM-$YEAR-$MONTH-$DAY.log"); };
destination d_nginx { file("/var/log/nginx/$HOST-$PROGRAM-$YEAR-$MONTH-$DAY.log"); };

filter f_nginx   { program(nginx); };
filter f_default    { level(info..emerg) and
                        not (facility(mail)
                        or facility(authpriv)
                        or facility(cron)); };

log { source(s_sys); filter(f_nginx); destination(d_nginx); };
log { source(s_sys); destination(d_splunk); };

A: use the 'final' flag in the nginx log path:
log { source(s_sys); filter(f_nginx); destination(d_nginx); flags(final); };

For details, see https://syslog-ng.com/documents/html/syslog-ng-ose-latest-guides/en/syslog-ng-ose-guide-admin/html/reference-logflags.html


text:
Q: OWL complement in DL query (NOT) OWL uses Open World Assumptions.  Thus if I have class Animal and property eats (domain Animal, range Animal)  Mouse, Cat (eats Mouse), Dog  and if I state the DL Query for instances (Protege 5.2) Animal and not (eats some) the result is empty.
Is there any way to make this query return Mouse and Dog with Owl e.g. make it somehow behave closed world?
thanks,

A: The main point is as you implied: you have close the world in some way. I.e. currently there is nothing in your ontology from which the reasoner can infer that Dog and Mouse don't eat mice. This can be achieved by:
Class: Animal
    DisjointUnionOf:
        Cat, Dog, Mouse

Class: Cat
    EquivalentTo:
        eats some Mouse
    SubClassOf:
        Animal

Class: Dog
    SubClassOf:
        Animal,
        eats only (not (Mouse))

Class: Mouse
    SubClassOf:
        Animal,
        eats only (not (Mouse))

I have written about some of the ways in which open world assumption issues can be avoided when using existential (some) and universal (only) property restrictions here and here.
As an aside: You may want to rethink your domain and range restrictions on eats. What domain and range restrictions do is whenever, in this case, one individual eats another individual, it will infer that both individuals are of type Animal. This would mean if an individual of type Mouse eats say cheese, it will infer that the cheese is an Animal.


text:
Q: Error "Property setVariableName not found" using dot notation to set property I've just started learning Objective-C and I'm not sure when to use dot notation vs. square brackets. I know a similar question has been asked here but I'm still not really understanding the difference. I've read that [myObject doSomething] and myObject.doSomething are equivalent. What I'm not sure about though is that when I use @property to generate a method it automatically generates a setter method that I can only use with square brackets.
// MyClass.h

@interface MyClass : NSObject
@property int number;

// main.m
MyClass *object = [[MyClass alloc] init];
[object setNumber:3];
object.setNumber = 4; // Property 'setNumber' not found

Why am I getting error messages when I write object.setNumber = 4 and why can I only use square brackets for this?

A: You get that error because the property is called number not setNumber. It is common in OOP languages to create methods that access an object's data using "setters" and "getters." A property in Objective-C 2.0 synthesizes this process and automatically generates the setters and getters. If you go into MyClass.m and enter - setN you will see setNumber suggested by Xcode. That is because you can implement your setters and getters yourself to customize their behavior, or leave the default behavior of simply setting a value or getting a value.
Additionally, properties automatically generate the variable declaration as _variableName For instance, the default behavior of your property would be:
- (void) setNumber:(int)number {
    _number = number
}

- (int) getNumber {
    return _number;
}

Determining whether you should use one over the other really comes down to consistency. To ensure consistency in teams, a Style Guide should be in place. Take the NY Times for instance. They restrict dot notation strictly to Properties and brackets for non-property methods (i.e. setters and getters).

A: You're confusing methods and properties.
When you make a property, yes it creates a setter method called setVARIABLE.
The only way to call a method is with the bracket notation. IE [object setNumber:3]; (Unless you have 0, or 1 parameters, thanks HAS)
What you want to do is use the property name, not the setter (or getter) method.
[object number];

That will return the value of number. You can't read properties when accessing them through bracket notation, it's only readonly (only accessing the get function).
object.number = 3;

That's how you would set the property number using dot notation.
When you wrote object.setNumber = 3; you were treating setNumber like a property, which it's not, it's a method.
To recap

*

*methods are only usable by bracket notation, not dot notation [object setNumber:3]; (Unless you have 0, or 1 parameters)

*you can only read a property when accessing it through bracket notation [object number]; //returns the value of number

*you can read and write a property when using it through dot notation object.number = 3;


text:
Q: Cannot manage Azure DevOps from Work Account, even I am the organization owner Currently my organization in Azure DevOps contains two users: myname@mycompany.com (Personal Account) and myname@mycompany.com (Work Account).
myname@mycompany.com (Work Account) is the organization owner. When I log into devops with this account, I cannot do anything without avoid the user being switched to the Personal Account automatically.
The personal account does not have permission to manage users nor change and organization settings. So I am kind of stuck.
My end goal is to link this organization to our Azure Ad tennant, that my Work Account is member of.
How can I fix that?

A: If you want to use the AAD identity of the same email address to access the organization, you first need to check whether the organization is connected to AAD like this in the Azure Active Directory of the organization settings.

Secondly, when you log in, please select Work or school account. This happens when you sign in with an email address that's shared by your personal Microsoft account and by your work account or school account.

*

*Select Work or school account if you used this identity to create
your organization, or if you previously signed in with this identity.
Your identity is authenticated by your organization's directory in
Azure AD, which controls access to your organization.

*Select Personal account if you used your Microsoft account with Azure
DevOps. Your identity is authenticated by the global directory for
Microsoft accounts.

In addition, you can open a private or incognito browsing session and sign in, which can avoid the influence of the identity cached by the browser.
Here is the document about troubleshooting access via Azure AD you can refer to.


text:
Q: Force Direct3D anti-aliasing in a Direct3D game? Some old games look really jagged nowadays on large displays without any anti-aliasing, but don't have any option built-in to the game to enable it.
On a PC with an NVIDIA graphics card, it's possible to force anti-aliasing in the NVIDIA control panel which can really improve this.  But I'm playing the game in Parallels on a Mac, and although the Mac has an NVIDIA graphics card, it's Parallels' emulated card that Windows sees and so obviously there's no NVIDIA control panel.
Is there some generic way I can force anti-aliasing for a Direct3D game without using the NVIDIA control panel?

A: You can force SMAA on a DirectX 9, 10 or 11 game by using injectSMAA. It should work with any graphics card brand.

Description

*

*adds "Subpixel Morphological Antialiasing" to an application

*is based on "injectFXAA" (written by "some dude")

*is supposed to work only with directx 9, directx 10, directx 11, x86 applications

*may be incompatible with any other form of antialiasing

*may be incompatible with overlays (Steam Overlay, MSI Afterburner, Fraps, ...)

  SMAA is a very efficient GPU-based MLAA implementation, capable of
  handling subpixel features seamlessly, and featuring an advanced
  pattern detection & handling mechanism.
http://www.iryoku.com/smaa/

injectSMAA screenshots from the game, Halo: Combat Evolved (does not have an in-game anti-aliasing (AA) option and does not support graphics driver-forced AA):
Click image thumbnails below to view higher-resolution, original-sized image.
No AA:

With SMAA:

Screenshots source: http://mrhaandi.blogspot.com/p/injectsmaa.html (more screenshots from other games from the same webpage)

A: My answer may not be relevant to the question you're asking because I'm not sure it can introduce anti-aliasing into a game that doesn't support it.
But if you're looking to improve the general graphics quality of games that use DirectX 9, you might want to consider using a modded DirectX driver. I know of one popular mod called ENB Series that can help improve the overall graphics quality of a game.
However, it does require spending a lot of time tinkering with a lot of settings to get it "just right". The mod works for old DX9 games like Deus Ex as well as newer games like GTA IV.
Here are a few screenshots of the mod in action (for Deus Ex. Complete screens here):

To see a detailed analysis of the mod can do, read the GTA IV optimization guide for ENB Series mod.
Update:

I found out about another shader injector tool called SweetFX. It's based on InjectSMAA and improves upon it and other similar tools like InjectFXAA and FXAAtool (according to its own admission)
You can download SweetFX from here. However, it will only work on 32-bit DirectX 9, 10 and 11 games.
Luckily, this tool has a lot of tutorial/configuration videos for it created by the gamer community, so it is highly recommended that you watch these videos to get better acquainted with the tool.
There's also a configuration tool available called SweetFX Configurator that eases the configuration building.
Here's a list of effects that SweetFX supports (from the forum post):

* SMAA Anti-aliasing : Anti-aliases the image using the SMAA technique - see http://www.iryoku.com/smaa/
* LumaSharpen : Sharpens the image, making details easier to see
* Bloom : Makes strong lights bleed their light into their surroundings
* HDR : Mimics an HDR tonemapped look
* Technicolor : Makes the image look like it was processed using a three-strip Technicolor process - see http://en.wikipedia.org/wiki/Technicolor
* Cineon DPX : Makes the image look like it was converted from film to Cineon DPX. Can be used to create a "sunny" look.
* Lift Gamma Gain : Adjust brightness and color of shadows, midtones and highlights (avoids clipping)
* Tonemap : Adjust gamma, exposure, saturation, bleach and defog. (may cause clipping)
* Vibrance : Intelligently saturates (or desaturates if you use negative values) the pixels depending on their original saturation.
* Curves : Contrast adjustments using S-curves.
* Sepia : Sepia tones the image - see http://en.wikipedia.org/wiki/Sepia_tone#Sepia_toning
* Vignette : Darkens the edges of the image to make it look more like it was shot with a camera lens. - see http://en.wikipedia.org/wiki/Vignetting )
* Dither : Applies dithering to simulate more colors than your monitor can display. This lessens banding artifacts - see http://en.wikipedia.org/wiki/Dithering#Digital_photography_and_image_processing )
* Splitscreen : Enables the before-and-after splitscreen comparison mode.

A: I'm not sure if this is an answer since i don't have parallels myself, but you may want to try running NvidiaInspector.
It'll forcefully change the AA settings of games if you have a nvidia gpu. (Try running it on the windows platform)


text:
Q: Java EE App don't print JSP file like jsp, but like HTML I have project maven web-application. I have a few JSP files with HTML code and JSP tags. I have a connection in the local database and a few servlets.
Problem is that when I logged in to the app, I want to print a welcome message for the logged user.
This is the tag which should display a welcome message:

Hello ${sessionScope.user_name}. This is yours stats:

When I logged in the only text that I have is "Hello ${sessionScope.user_name}. This is your stats:
This is my servlet code for logging in:
@WebServlet("/login")
public class UserLoginServlet extends HttpServlet {

private static final long serialVersionUID = 2717450811223035557L;

private UserRepository userRepository = new UserRepositoryBean();

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setContentType("text/html");
    String login = req.getParameter("login");
    String password = req.getParameter("password");
    PrintWriter writer = resp.getWriter();

    if (login == null | login.isEmpty() | password == null | password.isEmpty()) {
        writer.write("ERROR");
        return;
    } else {
        if (userRepository.validateUser(login, password)) {
            HttpSession session = req.getSession();
            session.setAttribute("user_name", login);
            resp.sendRedirect("profile.jsp");
        } else {
            req.setAttribute("error", "Invalid login or password. Try again.");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }

    writer.close();
}

}
Why I don't have a message, for example, Hello Admin. This is your stats:?
I always have Hello ${sessionScope.user_name}. This is your stats:...

A: A sendRedirect should not be mixed by other output of some page.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String login = req.getParameter("login");
    String password = req.getParameter("password");

    if (login.isEmpty() || password.isEmpty()) {
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
        writer.write("ERROR");
        return;
    }
    if (userRepository.validateUser(login, password)) {
        HttpSession session = req.getSession();
        session.setAttribute("user_name", login);
        resp.sendRedirect("profile.jsp");
    } else {
        req.setAttribute("error", "Invalid login or password. Try again.");
        req.getRequestDispatcher("login.jsp").forward(req, resp);
    }
}

The first if could be done by the validation - as empty input happens often - by a nice error message reposted to the same form with already done input saved.
If the JSP comes as HTML, then ensure it has a valid servlet mapping.
Also the JSP better should not be placed in a public directory, but maybe under WEB-INF/jsps/ or such.


text:
Q: Merging in R: 1 row missing after merge I have a dataframe movielens:
str(u.data)
'data.frame':   100000 obs. of  4 variables:
 $ userID   : int  196 186 22 244 166 298 115 253 305 6 ...
 $ movieID  : int  242 302 377 51 346 474 265 465 451 86 ...
 $ rating   : int  3 3 1 2 1 4 2 5 3 3 ...
 $ timestamp: int  881250949 891717742 878887116 880606923 886397596 884182806 881171488 891628467 886324817 883603013 ...

and
str(u.item)
'data.frame':   1681 obs. of  20 variables:
 $ unknown    : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ Action     : Factor w/ 2 levels "0","1": 1 2 1 2 1 1 1 1 1 1 ...
 $ Adventure  : Factor w/ 2 levels "0","1": 1 2 1 1 1 1 1 1 1 1 ...
 $ Animation  : Factor w/ 2 levels "0","1": 2 1 1 1 1 1 1 1 1 1 ...
 $ Childrens  : Factor w/ 2 levels "0","1": 2 1 1 1 1 1 1 2 1 1 ...
 $ Comedy     : Factor w/ 2 levels "0","1": 2 1 1 2 1 1 1 2 1 1 ...
 $ Crime      : Factor w/ 2 levels "0","1": 1 1 1 1 2 1 1 1 1 1 ...
 $ Documentary: Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ Drama      : Factor w/ 2 levels "0","1": 1 1 1 2 2 2 2 2 2 2 ...
 $ Fantasy    : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ Film-Noir  : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ Horror     : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ Musical    : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ Mystery    : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ Romance    : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ Sci-Fi     : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 2 1 1 1 ...
 $ Thriller   : Factor w/ 2 levels "0","1": 1 2 2 1 2 1 1 1 1 1 ...
 $ War        : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 2 ...
 $ Western    : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ movieID    : int  1 2 3 4 5 6 7 8 9 10 ...

The number of row of u.data is 100.000
nrow(u.data)
100000

And
nrow(u.item)
[1] 1681

Then, I want to merge them:
all_data = u.data
all_data = merge(all_data, u.item, by = "movieID")

But the merged data has only 99.999 rows
nrow(all_data)
[1] 99999

Did I did something wrong while merging these two data frames?

A: This happens if min(u.data$movieID) < min(u.item$movieID) or if max(u.data$movieID) > max(u.item$movieID). Example for the latter:
# max(u.data$movieID) = 10
u.data <- data.frame(movieID = 1:10, NAME = LETTERS[1:10])
dim(u.data)
# [1] 10  2

# max(u.item$movieID) = 11
u.item <- data.frame(movieID = c(1:9,11), name = letters[c(1:9,11)])
dim(u.item)
# [1] 10  2

out <- merge(u.data, u.item, by = "movieID")
dim(out)
# [1] 9 3

# check if all elements of u.item$movieID exist in u.data$movieID
is.element(u.data$movieID, u.item$movieID)
# [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE

Suggested by Batanichek:
out <- merge(u.data, u.item, by = "movieID", all.x = TRUE)
dim(out)
# [1] 10  3


text:
Q: What are the prime and non-prime attributes in this relation? R(HIJKLMNO)

L -> MNO
HI -> JKLMNO
J -> KL
K -> H

HI is a key.
So, H is a prime attribute.
But, H is also in non-key part.
What are the prime and non-prime attributes in this relation?

A: Your schema has three (candidate) keys:
HI
IJ
IK

While it is immediate to discover tha HI is a candidate key since it determines all the other attributes, you can see that this is true also for IJ and IK by calculating the closure of those attributes:
IJ+ = IJ
IJ+ = IJKL     (by adding the right part of J → KL)
IJ+ = IJKLH    (by adding the rigth part of K → H)
IJ+ = IJKLHMNO (by adding the right part of L → MNO)

analogously for IK:
IK+ = IK
IK+ = IKH      (by adding the rigth part of K → H)
IK+ = IKHJLMNO (by adding the right part of HI → JKLMNO)

For this reason, the prime attributes of the relation are:
HIJK

while the non prime attributes are:
LMNO

Note that there are no other candidate keys since M, N and O appear only on the right side of functional dependencies, so that they cannot "contribute" to any key. L appears both on a left part and on a right part of functional dependencies, but it is determined by HI, IJ and IK, and does not determine any of these attributes, so it cannot be part of a key. Finally, you cannot remove any attribute from HI, IJ and IK without losing the key property.

A: You are trying to find out possible candidate keys. HI is the only possible candidate key or prime attribute since it independently identifies all other attributes or fields due to the functional dependency HI -> JKLMNO.
All the other attributes are non-prime attributes. Again, here HI is a composite candidate key and both H and I are key attributes together forming the primary key.
All other attributes are dependent on HI together, else it will result in partial function dependency (PFD) or, in other words, the criteria for 2nd Normal Form won't be satisfied.


text:
Q: Fantasy series with female main character angelspawn Book I read back in 2012, Main character was on front cover in form fitting leather armor. Main character was female. Main character was an angelspawn, and whenever in the presence of angels would go into "heat" (exact terminology used in the book). as an angelspawn, the main character was very fast and good at fighting. the plot had demons come from the ground in one part of the book. Angels in this setting are not looked at as totally favorable, since they try to stay away from normal humans and their troubles and only come in for "big" problems. I remember the series was put on hold due to a dispute the author had with her publisher, but she promised to try to finish the series with a different publisher. Setting was almost post apocalyptic if I remember correctly, I could be wrong though.

A: Bloodring by Faith Hunter. Next 2 are Seraphs and Host, but I haven't read those. Subtitle "A Rogue Mage novel".

No one thought the apocalypse would be like this. The world didn't end. And the appearance of seraphs heralded three plagues and a devastating war between the forces of good and evil. Over a hundred years later, the earth has plunged into an ice age, and seraphs and demons fight a never-ending battle while religious strife rages among the surviving humans.
Thorn St. Croix is no ordinary neomage. All the others of her kind, mages who can twist leftover creation energy to their will, were gathered together into Enclaves long ago; and there they live in luxurious confinement, isolated from other humans and exploited for their magic. When her powers nearly drive her insane, she escapes—and now she lives as a fugitive, disguised as a human, channeling her gifts for war into stone-magery and the pacific tasks of jewelry making. But when Thaddeus Bartholomew, a dangerously attractive policeman, shows up on her doorstep and accuses her of kidnapping her ex-husband, she retrieves her weapons and risks revealing her identity to find him. And for Thorn, the punishment for revelation is death….


text: Q: Creating a JAR file and using it in Android Studio There are no good tutorials about creating a JAR file. I'm trying to create a JAR file and use it in different projects. I can create a class without an Activity as a library project in format of ClassName.java. However, I tried to create JAR files many times, but I could not succeed. Please help me step by step creating a JAR file.


text:
Q: Простой пример с одним нейроном. Нужен простейший пример с реализацией:
Цветок
параметры:
цвет   +1.0
запах  + 2.0

Далее ввести объект с оценкой
оценить(evaluated)
цвет   -1.0
запах  + 2.0

Нейрон должен вернуть +3.
На библиотеке fann или opennn(или иной высокоуровневой).
Собственно никак не могу перейти к практике, так как нет простейший примеров в этих библиотеках.
Документация очень скудная.
К тому же библиотека fann выбрасывает исключения из dll(fanndouble.dll,fannfloat.dll) на функции fann_train_on_file()
При копировании примеров с их сайта.
A: int sravn(int arg1,int arg2)
{
int a,b,c
a=arg1/1;
b=arg2/2;
c=a+=b;
if(c>1)
{c=1-=c}
return c;
}

В арг1 записываем цвет сравнимаемого,а в арг2 - запах.
На выходе полуаем отношение нейрона к цветку.


text:
Q: How to create a display mode and edit mode in a Metro App? What is the best approach to change TextBlocks to TextBoxes after clicking on Edit button for a Windows 8 Store App? This is something similar to an iOS app that after clicking on an Edit button editable fields become TextBoxes and you can then change data.

A: You don't need to use TextBlock just use TextBox with IsReadOnly property.
on button click mark the IsReadOnly="True"

A: I think you want the IsReadOnly property.  IsReadOnly=true; when you don't want to let them edit the textbox, IsReadOnly=false; when you want to let them edit it.


text:
Q: pundit integration can't write unknown attribute `role` this is driving me crazy.  i am trying to setup pundit with devise and everything works fine until i try to set a default role.  in my case, the default role is user. when i try to login, i get the following error:
ArgumentError in Devise::SessionsController#new
app/models/user.rb:26:in `set_default_role'
here is my user.rb:
class User < ActiveRecord::Base
  enum role: [:user, :gig, :band, :venue, :promoter, :admin]
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :user
  end
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
    belongs_to :role
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

validates :profile, presence: true,
                    uniqueness: true,
                    format: {
                      with: /[a-zA-Z0-9-]+/,
                      message: 'Must be formated correctly.'
                    }

  before_create :set_default_role
  has_many :gigs

  private
  def set_default_role
    self.role ||= Role.find_by_name('user')
  end

  def gravatar_url
    stripped_email = email.strip
    downcased_email = stripped_email.downcase
    hash = Digest::MD5.hexdigest(downcased_email)

    "http://gravatar.com/avatar/#{hash}"
  end
end

here is my rold.rb:
class Role < ActiveRecord::Base
  has_many :users
end

any ideas?

A: apparently I did not have role as part of my user table.  this is what fixed my issue:
rails generate migration add_role_to_user role:integer

then:
rake db:drop db:create db:migrate db:seed


text:
Q: Error is occur when I pass the JSON value in AJAX url When I pass the json request in ajax url following error occur. I have pass the 200 and above datas in ajax. All my data's come from "/search/searchendpoint" url
controller:
$searchitem = $this->MbPriceList->find('all' , [
  'fields' => [
    'id',
    'name' => 't1.item_name'
  ],
  'join' => [
     'table' => 'mb_item_list',
     'alias' => 't1',
     'type' => 'INNER',
     'conditions' => [
       't1.item_code = MbPriceList.item_code'
     ]
  ]
]) ->toArray();

$this->set([
  'response' => $searchitem,
  '_serialize' => ['response']
]);

JSON request:
<script>
  var myUrl = "/search/searchendpoint";
  $.mockjax({
    url: myUrl,
    dataType: "json",
    type: "get",
    data: JSON.stringify(myUrl),
    contentType: 'application/json; charset=utf-8',
    response: function(data){
      alert(data)
    }
  });
</script>
<script>
  $('#search').typeahead({
    ajax: '/search/searchendpoint'
  });
</script>

Error:

jquery-2.2.4.min.js:2 Uncaught TypeError: Cannot use 'in' operator to
  search for 'length' in "/search/searchendpoint" at s
  (jquery-2.2.4.min.js:2) at Function.each (jquery-2.2.4.min.js:2) at
  isMockDataEqual (jquery.mockjax.js:67) at getMockForRequest
  (jquery.mockjax.js:119) at Function.handleAjax [as ajax]
  (jquery.mockjax.js:444) at Typeahead.execute
  (bootstrap-typeahead.js:170) at f (jquery-2.2.4.min.js:2)

A: try this. you have to echo out your variables that you intent to pass as a response to your view as JSON and then, very !important, exit the controller's code.
$this->set(['response' => $searchitem,'_serialize' => ['response']]);
echo json_encode('response');
exit();

and in your javascript you have to read that json, assuming you are using jquery you catch your php variable as a parameter on the success function, try this.
$ajax({
    type:"POST",
    data:data,
    url:URL,

    success:function(data){
        var jsresponse = $.parseJSON(data).response;
    }
});

Let me know if that worked for you.
Cheerios !!


text:
Q: Why do we need secondary indexes in cassandra and how do they really work? I was trying to understand why secondary indexes were even necessary on Cassandra.
I know that secondary indexes are used because:
"Secondary indexes allow for efficient querying by specific values using equality predicates (where column x = value y). Also, queries on indexed values can apply additional filters to perform operations such as range queries."
from: http://www.datastax.com/docs/0.7/data_model/secondary_indexes
But what I did not understand is why a query like:
get users where birth_date = 1973;

required that the birth_date had a secondary index. Why is it necessary for secondary indexes to even exist? Can't cassandra just go through the table and then return the values when the constrained is matched? Why do we need to treat things that we might want to query in that way in any special way?
I am assuming that the fact that cassandra is distributed and going through the whole table might not be easy due to each row key being allocated to a different node making it a little complicated. But I didn't really understand how making it distributed complicated the problem and how secondary indices resolved it (i.e. how does cassandra resolve this issue?).
Related to this question, is it true that secondary indexes and primary keys are the only things that can be queried in the for of SELECT * FROM column_family_table WHERE col_x = constraint? Why is the primary key special?

A: With amount of data these nosql databases meant to deal with, going for table scan or region scan is not an option. That's what Cassandra has restricted and allowed queries over non row key columns only if secondary indxes are enabled. That way such indices and data would be co located on same data node.
Hope it helps.
-Vivek


text:
Q: Setting a variable in Jquery based on an elements class Im confused and my head is sore, please help.
I am trying to send a variable to fancybox.js when an element has a class 'selected'. This works:
var showMe = true;

This also works:
if(a){
  var showMe = true;
}

This results in an alert saying "class is selected":
if($('#shuffle').hasClass('selected')){
  alert("class is selected");
}

Ive also checked in Firebug and the class is selected.
The problem is when I do this it doesn't work:
if($('#shuffle').hasClass('selected')){
    var showMe = true;
}

showMe is not set to true.
I know it must be simple, thanks in advance for any help.
EDIT Here is what worked:
For some reason, the class changing to selected didn't set the showMe = true.  I added an .click function to the button instead and it did work.  Not sure why, but if you know where I should be reading into this then please past the link in here.
$(function() {
  $("#shuffle").click(function(){

    showMe = true;
    console.log( showMe);
  });
});

Thanks for everyone that responded, Im guessing the reason your answers didn't work was something to do with the way i asked the question.  Cheers

A: By using var showMe = 'true' you are setting a local variable. If you want to use that variable outside the function, just use showMe = 'true' < that will set a global variable.
Like this
if($('#shuffle').hasClass('selected')){
    showMe = true;
}

A: Maybe you'll have a look at this:
var showMe = ($('#shuffle').hasClass('selected')) ? true : false;
alert(showMe);

Be sure the DOM is ready when you're running that!

A: Declare your variable before the document ready or whatever. That way you will make it global.
<script type="text/javascript">
    var showMe = false;
    jQuery(document).ready(function($) {
        console.log( showMe );
        if ( $('#shuffle').hasClass('selected') )
        {
            showMe = true;
            console.log( showMe );
        }
    });
</script>

A: try
if($('#shuffle').hasClass('selected')){
    showMe = true;
}

i have moved the showMe to global scope(by removing the var keyword), now where ever you are accessing it use it like
if(typeof(window.showMe) != 'undefined')
 alert(showMe);


text:
Q: What does 'to immolate (someone) to one's manes' mean? What does the phrase to immolate someone to one's manes mean as it used in the following pair of literary citations?

*

*"Do thou, brave wolf, avenge our queen, by immolating this traitor to her august manes."
― translation of Jean de La Fontaine's Fables, Les obsèques de la Lionne ('The Obsequies of the Lioness') via Google Books.

*" [...] whence he received the order to immolate his mother to the paternal manes."
― Le Antichità di Ercolano Esposte, via Google Books.

After long ratiocinations upon to immolate (someone) to one's manes, I settled upon the following meaning: "to seek revenge upon someone".  I would nevertheless like certain further explanation both of grammar and of meaning regarding how this idiomatic phrase has been used in the two citations provided above.
My specific questions are:

*

*What does august refer to? To the way the retaliation should be committed?

*Is the manes the character of the person who should be avenged?

*What does paternal refer to? To the person who should be revenged?

A: Manes (Latin) - (in ancient Roman belief) the souls of dead ancestors, worshipped as benevolent spirits.  (Definition from Oxford Dictionaries).
August = highly respected (presumably referring to the queen's spirit).
Paternal - presumably the spirit of the subject's father.

A: The verb immolate

To kill as a sacrifice especially by fire

The term "august manes" in La Fontaine may have the double meaning of "great ancestor" but also "great hair" like a lion's mane.
However I would be surprised if that particular wordplay exists in the original French.


text:
Q: 'Mage_News_Helper_Data' not found in magento
Fatal Error :Mage_News_Helper_Data' not found in magento
  directory/app/Mage.php on line 547

I created a new module for mage_news, eventhougth it shows the error.
What do I have to do?

A: It is pretty common magento error. Even if you yourself don't use helper, Magento admin does. You should always create helper class in your custom module. File location depends on module code pool and could be located in

[magento_root]/app/code/local/[company]/[module]/helper/Data.php

or

[magento_root]/app/code/community/[company]/[module]/helper/Data.php

Sample file content:
<?php
class Company_Module_Helper_Data extends Mage_Core_Helper_Abstract
{
}

Besides creating the Company_Module_Helper_Data class, you need to add class mapping to your config.xml
 <config>
        ...
        <global>
          <helpers>
            <module>
              <class>Company_Module_Helper</class>
            </module>
          </helpers>
        </global>
        ...
    </config>

If you have created Data.php and has class mapping in config.xml, try following:

*

*Clear cache ( System > Cache management )

*If you are using compilation, disable it or run recompile ( System > Tools > Compilation )

I hope this will help you.


text:
Q: issue for dockerizing nodejs app with yarn I am trying to dockerize my simple nodejs app with yarn. Here is my dockerfile.
FROM alpine:latest
RUN apk upgrade --update

FROM node:8

WORKDIR /apps/myapp

COPY . /apps/myapp

COPY package*.json /apps/myapp

RUN yarn && \
    yarn run build

COPY yarn.lock /apps/myapp

When I run this dockerfile, i see this output.
success Saved lockfile.
Done in 60.16s.
yarn run v1.15.2
$ react-scripts build
Creating an optimized production build...
Compiled with warnings.
I see 'Saved lockfile', but COPY fails with this error message.
Removing intermediate container d4975a5f1155
 ---> 12af3c2fd907
Step 9/9 : COPY yarn.lock /apps/myapp
COPY failed: stat /var/lib/docker/tmp/docker-builder042321912/yarn.lock: no such file or directory
Is there something wrong with my dockerfile?

A: Following David Maze's comment, you may want to set your Dockerfile like this
FROM alpine:latest

RUN apk add --no-cache nodejs yarn

WORKDIR /apps/myapp

COPY . /apps/myapp

RUN yarn && yarn run build