text:
Q: Is there a way to change Foreground of a TextBox ScrollViewer in xaml whithout change the local property? Is there a way to change the Foreground of a custom TextBox in xaml with triggers or visualstates without change the local main Foreground property?
Here is the xaml style of a generic custom TextBox with randomly chosen colors:
<Style TargetType="{x:Type local:CustomTextBox}">
    <Setter Property="Background" Value="White"/>
    <Setter Property="BorderBrush" Value="Black"/>
    <Setter Property="Foreground" Value="Black"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustomTextBox}">
                <Border x:Name="PART_Border"
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="1">
                    <ScrollViewer x:Name="PART_ContentHost"
                                    HorizontalScrollBarVisibility="Hidden"
                                    VerticalScrollBarVisibility="Hidden"
                                    Focusable="False"/>
                </Border>
                <ControlTemplate.Triggers>
                    <!-- Can be IsMouseOver, IsFocused, etc... -->
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="PART_Border"
                                Property="Background" Value="Green"/>
                        <Setter TargetName="PART_Border"
                                Property="BorderBrush" Value="DarkGreen"/>
                        <!-- The only method I know that works is this one
                             that changes the local property -->
                        <Setter Property="Foreground" Value="Yellow"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I've tried to use these lines in trigger but everyone fails (does nothing):
<Setter TargetName="PART_ContentHost" Property="Foreground" Value="Yellow"/>
<Setter TargetName="PART_ContentHost" Property="TextBlock.Foreground" Value="Yellow"/>
<Setter TargetName="PART_ContentHost" Property="TextElement.Foreground" Value="Yellow"/>
<Setter TargetName="PART_Border" Property="TextBlock.Foreground" Value="Yellow"/>
<Setter TargetName="PART_Border" Property="TextElement.Foreground" Value="Yellow"/>

In Buttons the Foreground color can be changed by changing TextBlock.Foreground of the parent element (e.g. TextBlock.Foreground of PART_Border), but this not works with TextBoxes.
Changing the local property as this line does...
<Setter Property="Foreground" Value="Yellow"/>

...has the problem that if I change later the main Foreground property (from Black to Gray for example), the trigger cannot change it anymore to Yellow, for example with this:
<local:CustomTextBox ... Foreground="Gray"/>

VisualStates cannot interact even with the main Foreground property.
So is there another way I don't know to accomplish this in xaml or is it a limitation of wpf?

A: What if you completely override the ControlTemplate?
    <TextBox Text="Hiho" Foreground="Red">
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Background" Value="White"/>
                <Setter Property="BorderBrush" Value="Black"/>
                <Setter Property="Foreground" Value="Black"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type TextBox}">
                            <TextBox Name="TheContent" Text="{TemplateBinding Text}"/>

                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="TheContent" Property="Foreground" Value="Yellow"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TextBox.Style>
    </TextBox>

A: You could animate the property using a Storyboard. This will take effect over local values:
<Window ...>
    <Window.Resources>
        <Style TargetType="{x:Type local:CustomTextBox}">
            <Setter Property="Background" Value="White"/>
            <Setter Property="BorderBrush" Value="Black"/>
            <Setter Property="Foreground" Value="Black"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:CustomTextBox}">
                        <Border x:Name="PART_Border"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="1">
                            <ScrollViewer x:Name="PART_ContentHost"
                                        HorizontalScrollBarVisibility="Hidden"
                                        VerticalScrollBarVisibility="Hidden"
                                        Focusable="False"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="PART_Border" Property="Background" Value="Green"/>
                                <Setter TargetName="PART_Border" Property="BorderBrush" Value="DarkGreen"/>
                                <Trigger.EnterActions>
                                    <BeginStoryboard x:Name="sb">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetProperty="Foreground">
                                                <DiscreteObjectKeyFrame KeyTime="00:00:00" Value="{x:Static Brushes.Yellow}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </BeginStoryboard>
                                </Trigger.EnterActions>
                                <Trigger.ExitActions>
                                    <RemoveStoryboard BeginStoryboardName="sb" />
                                </Trigger.ExitActions>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <StackPanel>
        <local:CustomTextBox Margin="10" Text="sample text" Foreground="Red" />
    </StackPanel>
</Window>


text:
Q: Java - VariableDeclaratorID expected after this token, when assigning value to an instance variable I'm studying linked lists from this video from UC Berkeley. However, when I try typing the same version in my Eclipse compiler, like this....
public class CreateLinkedList{

    public class Node{
        String PlayerName;
        Node next;
    }

    Node first = new Node();
    Node second = new Node();
    Node third = new Node();

    first.PlayerName = "Sanchez";
    second.PlayerName = "Ozil";
    third.PlayerName = "Welbeck";

    public static void main(String[] args) {

    }
}

I get the error "Syntax error on token "PlayerName", VariableDeclaratorID expected after this token" on the following lines
first.PlayerName = "Sanchez";
second.PlayerName = "Ozil";
third.PlayerName = "Welbeck";

Can anyone explain where I'm going wrong?

A: This code
Node first = new Node();
Node second = new Node();
Node third = new Node();

first.PlayerName = "Sanchez";
second.PlayerName = "Ozil";
third.PlayerName = "Welbeck";

is not in a code block, try moving it to main.
Also the Node class will need to static, or else move it to a seperate .java file.

A: You can't initialize like this
first.PlayerName = "Sanchez";
second.PlayerName = "Ozil";
third.PlayerName = "Welbeck";

You have to move it to some of the methods of class CreateLinkedList
If you are putting it in main you have to declare the Node instances static
static Node first;
static Node second;
static Node third;

A: Review nested class definitions... If you want to set the properties from a static context... you need a static class.
public class CreateLinkedList{

static class Node{
    String playerName;
    Node next;
}

public static void main(String[] args) {

    Node first = new Node();
    Node second = new Node();
    Node third = new Node();

    first.playerName = "Sanchez";
    second.playerName = "Ozil";
    third.playerName = "Welbeck";

    System.out.println("First is : " + first.playerName);
    System.out.println("Second is : " + second.playerName);
    System.out.println("Third is : " + third.playerName);

    }
}

If you wish to keep your inner class as a nested public class then you need to instantiate the upper class first.
public class CreateLinkedList {

    public class Node {
        String playerName;
        Node next;
    }

    public static void main( String[] args ) {

        Node first = new CreateLinkedList().new Node();
        Node second = new CreateLinkedList().new Node();
        Node third = new CreateLinkedList().new Node();

        first.playerName = "Sanchez";
        second.playerName = "Ozil";
        third.playerName = "Welbeck";

        System.out.println( "First is : " + first.playerName );
        System.out.println( "Second is : " + second.playerName );
        System.out.println( "Third is : " + third.playerName );

    }
}

A: shouldn;t these lines be in main() function :
Node first = new Node();
Node second = new Node();
Node third = new Node();

first.PlayerName = "Sanchez";
second.PlayerName = "Ozil";
third.PlayerName = "Welbeck";

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to insert text with apostrophe and other special characters in PHP "echo"? I can only paste the text as it is (I can add some function around the text however before echoing it) between the echo ''; apostrophes - how can I insert the text in a way that it does not break the code?
Thanks!
EDIT:
Snippet from the code:
else {
echo '

The place you're at, something "cute" you notice about her,

';

A: If you only have apostrophes, use echo "your text here";. If you only have double quotes, use echo 'your text here';. If you have both, you will need manipulate your string beforehand one way or another, or use another source than pasting directly in the instruction (pulling it from a file, for example).

EDIT:
If you can change the HTML:
else {
echo '

The place you\'re at, something "cute" you notice about her,

';

If you can't, you'll need the PHP changed to pull the contents from somewhere else (a file, for example).


text:
Q: Either of them will be fine. / Either of them is fine. / I would like either of them Are there any of the following answers wrong and why? How do you usually answer that question if there is a need to answer especially politely?

Would you like a piece of cake or a candy bar?

Either of them will be fine.
Either of them is fine.
I would like either of them.

A: In this context fine means good or satisfactory and would be deemed offhand. So your first two sentences would be more suitable when choosing, say, a ladder.
At my politest I'd probably say, 'Thank you. I'd like either.' More effusively I might prefix an 'Ooh!' or a 'How lovely!' or both.


text:
Q: Postgres function error: column 't001' does not exist Here is my code:
-- Team --
    DROP TABLE IF EXISTS team;
    CREATE TABLE team (
     tid      char(4) not null,
     name     varchar(20),
     city     varchar(25),
     headcoach varchar(12),
    primary key(tid)
    );

-- Players--
    DROP TABLE IF EXISTS players;
    CREATE TABLE players (
     pid     char(4) not null,
     players varchar (9),
     name    varchar(15),
     priceUSD  numeric(8,0),
     position varchar(2),
    primary key(pid)
    );

-- Equipment --
    DROP TABLE IF EXISTS equipment;
    CREATE TABLE equipment (
     eid      char(4) not null,
     item     varchar(18),
     priceUSD numeric(10,0),
    primary key(eid)
    );

-- Team Equipment --
    DROP TABLE IF EXISTS teamequipment;
    CREATE TABLE teamequipment (
     tid      char(4) not null,
     eid    char(4),
     qty     integer,
     priceUSD numeric(10,0),
    primary key(tid)
    );

-- Team--
    INSERT INTO team( tid, name, city, headcoach )
     VALUES('t001', 'Giants', 'New York', 'Coughlin');

    INSERT INTO team( tid, name, city, headcoach )
     VALUES('t002', 'Jets', 'New York', 'Ryan');

    INSERT INTO team( tid, name, city, headcoach )
     VALUES('t003', 'Patriots', 'Boston', 'Belichick');

    INSERT INTO team( tid, name, city, headcoach )
     VALUES('t004', 'Steelers', 'Pittsburgh', 'Tomlin');

    INSERT INTO team( tid, name, city, headcoach )
     VALUES('t005', 'Dolphins', 'Miami', 'Philbin');

    INSERT INTO team( tid, name, city, headcoach )
     VALUES('t006', 'Panthers', 'Charlotte', 'Rivera');

-- Players--
    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p001', 'Manning', 'Giants', 10000000.00, 'QB' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p002', 'Cruz', 'Giants', 5000000.00, 'WR' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p003', 'Smith', 'Jets', 3000000.00, 'QB' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p004', 'Pace', 'Jets', 6000000.00, 'LB' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p005', 'Brady', 'Patriots', 12000000.00, 'QB' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p006', 'Ridley', 'Patriots', 5000000.00, 'RB' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p007', 'Polamalu', 'Steelers', 7000000.00, 'SS' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p008', 'Miller', 'Steelers', 4000000.00, 'TE' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p009', 'Pouncey', 'Dolphins', 6000000.00, 'C' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p010', 'Wake', 'Dolphins', 11000000.00, 'DE' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p011', 'Newton', 'Panthers', 9000000.00, 'QB' );

    INSERT INTO players( pid, players, name, priceUSD, position )
     VALUES('p012', 'Hardy', 'Panthers', 13000000.00, 'DE' );

-- Equipment

    INSERT INTO equipment ( eid, item, priceUSD)
     VALUES('e01', 'shoulder pads', 225.00 );

    INSERT INTO equipment ( eid, item, priceUSD)
     VALUES('e02', 'gloves', 40.00 );
    INSERT INTO equipment ( eid, item, priceUSD)
     VALUES('e03', 'cleats', 115.00 );

    INSERT INTO equipment ( eid, item, priceUSD)
     VALUES('e04', 'helmets', 300.00 );

    INSERT INTO equipment ( eid, item, priceUSD)
     VALUES('e05', 'socks', 10.00 );

    INSERT INTO equipment ( eid, item, priceUSD)
     VALUES('e06', 'knee pads', 6.00 );

    INSERT INTO equipment ( eid, item, priceUSD)
     VALUES('e07', 'jerseys', 150.00);

    INSERT INTO equipment ( eid, item, priceUSD)
     VALUES('e08', 'visors', 50.00 );

    INSERT INTO equipment ( eid, item, priceUSD)
     VALUES('e09', 'pants', 30.00 );

-- Team Equipment

    INSERT INTO teamequipment ( tid, eid, qty, priceUSD)
     VALUES(t001, e01, 25, 5625.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t001, e04, 33, 9900.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t001, e08, 15, 750.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t002, e01, 37, 8325.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t002, e02, 45, 1800.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t002, e04, 20, 6000.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t002, e07, 55, 8250.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t003, e01, 10, 2250.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t003, e03, 25, 2875.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t004, e05, 50, 500.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t004, e07, 55, 8250.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t004, e09, 11, 330.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t005, e01, 22, 4950.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t005, e06, 40, 240.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t005, e08, 20, 1000.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t006, e02, 13, 520.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t006, e05, 15, 150.00);

    INSERT INTO teamequipment( tid, eid, qty, priceUSD)
     VALUES(t006, e08, 3, 150.00);

The error I get is:
****** Error ******
ERROR: column "t001" does not exist
SQL state: 42703
Character: 3637

How do I fix this?

A: Character Varying OR char values must be in single quote.
Change your query like below:
INSERT INTO teamequipment( tid, eid, qty, priceUSD) VALUES('t001', 'e04', 33, 9900.00);

A: When inserting use quotes with t00x eg 't001'. You have declared the column as char(4).


text:
Q: How to improve code around flawfinder memset warning? In my code, all calls to memset appear as warnings with the flawfinder tool.
In the simplest case it could boil down to the equivalent to
    float f1;
    float f2;
    void* p1 = &f1;
    void* p2 = &f2;
    memcpy(p1, p2, sizeof(float));

The message is
./file.cpp:10:  [2] (buffer) memcpy:
  Does not check for buffer overflows when copying to destination (CWE-120).
  Make sure destination can always hold the source data.

I absolutely understand that this could be replaced by a simple copy, this is just a simplified example.
I also understand what are the potential problems with using memcpy and buffer overrun.
The question is what is exactly flawfinder asking me to do here?
Perhaps something like adding an assert? (this didn't suppress the warning)
    assert( sizeof(*p1) == sizeof(*p2) );
    memcpy(p1, p2, sizeof(float));

Or is it just telling me just don't use memset?
I am programming in C++, but I am pretty sure the question and the solution is common to both C and C++ languages.

A: errno_t  err = memcpy_s(dest, dsize, src, cnt);

that should be the 'safe' version which hopefully satisfies flawfinder


text:
Q: Replacing repeated lines of code with a function I work on embedded C and am trying to refactor code to improve readability and optimize ROM used in my project.
I have this 3 lines of code repeats many  times in switch-cases to update a particular edit box on a particular screen name.
EbSetText and SetState are predefined graphics library functions.
sprintf(Screen1_Editbox1_Text,"%04d",GetHV(0));
EbSetText((EDITBOX *)GOLFindObject(ID_Screen1_Editbox1), Screen1_Editbox1_Text);
SetState(GOLFindObject(ID_TestProbe_HVEb01), EB_DRAW);

Some code repeats like this:
EbSetText((EDITBOX *)GOLFindObject(ID_Screen1_Editbox1), "Text to output");
SetState(GOLFindObject(ID_TestProbe_HVEb01), EB_DRAW);

The above pieces of code repeats  120 times for various text-boxes and strings/buffer inputs present.It hurts readability of my code mainly and i am nearing 90% of my ROM.
I am thinking of replacing it with a utility function to contain all above logic.
SetTextofEditBox(Screen1_Editbox1_Text,ID_Screen1_Editbox1);

Does replacing it with single utility function give any advantage here?

A: As unwind said: it might be possible that a function call turns out to be more expensive than what you have now. Of course, bulky functions and repeating the same code makes for ugly code, that is harder to maintain and as a result: more error prone.
I'd personally consider using an inline function, and let the compiler decide if the code should be executed locally, or a function call is indeed a better option.
Or, if you want to, you could simply use a macro, too.
inline is generally considered the better option, and looking at those tiny snippets of code you posted, I'd say you should probably go for inline functions here, too.
Remember that inline leaves it to the compiler to decide if the function is going to be inlined or not, so if -after some serious, and representative testing- you feel as though the function should always be inlined, and you are using gcc, you could use the GCC always_inline attribute:
__attribute__((always_inline)) void your_inline_func(void *x, const char *y){}

If your compiler can't be persuaded to always inline the function so easily, then you'll have to revert back to using a macro. Be advised: macro's are not type safe, and can have side-effects: thorough testing is a must.
Based on the 2 statements you posted, one way of making your code more "data-drive", as unwind suggested could be this:
const char *txt_argument;
//and for any other argument you might need, too:
EDITBOX *edit = NULL;
//possibly add SetState's  arguments
switch(foo)
{
    case bar:
        txt_argument = Screen1_Editbox1_Text;
        edit = (EDITBOX *)GOLFindObject(ID_Screen1_Editbox1);
        break;
    case zar:
        txt_argument = "Text to output";
        edit = (EDITBOX *)GOLFindObject(another_editbox);
        break;
}
EbSetText(edit, txt_argument);

That doesn't really reduce the amount of code you have by much, but it does make it easier to oversee what the switch is actually doing.
If you are looking into ways to (further) optimize this one big switch statement then you could look into nesting the switch cases. It could well be that this has little of no effect, but for some compilers, and in some cases, it can make a difference.
If you have 120 cases, try to see if you can't break them up into 2 or 3 groups: those that are very common, those that are likely, and those cases that occur rarely. The most common cases go in the main switch, then the default contains another switch that lists the less common cases, and the default there, in turn, is the switch that deals with the rarer cases.
Nesting is of course prone to messy code, if you like, you can replace the default: switch bit simply with a series of shorter switch-es, followed by a return...

A: Perhaps. It's hard to say for sure, it depends on whether the overhead of the extra function call will be greater than the overhead of doing the work locally.
You could try breaking it out and making it a bit more "data-driven", i.e. arrange the code so that the EbSetText() and SetState() functions are always called after the switch, but make their arguments into variables that are set properly by each case.


text:
Q: d3js get corner coordinates of rect I am trying to draw lines between two rectangles. I want the line to go from the mid of the first rect to the mid of the second rect. For this I need to find the coordinates of the rect. Currently the coordinates for the line are hard coded but this is not a good approach. Please help, thanks in advance.
Here is my code:
  const svgContainer = d3.select('body').append('svg')
      .attr('width', 1200)
      .attr('height', 8000);

    const A1 = svgContainer.append('rect')
      .attr('x', 10)
      .attr('y', 10)
      .attr('width', 550)
      .attr('height', 850)

    const A2 = svgContainer.append('rect')
      .attr('x', 680)
      .attr('y', 10)
      .attr('width', 550)
      .attr('height', 850)

 const lineA1ToA2 = svgContainer.append("line")
                       .attr("x1", 10)
                       .attr("y1", 270)
                       .attr("x2", 680)
                       .attr("y2", 270)
                       .attr("stroke-width", 2)
                       .attr("stroke", "black");

A: there is no "center coordinates" in javascript and svg. so you would need to calculate these coordinates by yourself. In your case the best option would be to put params into variables and calculate all the coordinates based on them
const x1 = 10, y1 = 10, width1 = 550; height1 = 850;
const x2 = 680, y2 = 10, width2 = 550, height2 = 850;
    const A1 = svgContainer.append('rect')
      .attr('x', x1)
      .attr('y', y1)
      .attr('width', width1)
      .attr('height', height1)

    const A2 = svgContainer.append('rect')
      .attr('x', x2)
      .attr('y', y2)
      .attr('width', width2)
      .attr('height', height2)

 const lineA1ToA2 = svgContainer.append("line")
                       .attr("x1", x1 + width1 / 2)
                       .attr("y1", y1 + height1 / 2)
                       .attr("x2", x2 + width2 / 2)
                       .attr("y2", y2 + height2 / 2)
                       .attr("stroke-width", 2)
                       .attr("stroke", "black");

maybe some variables are redundant, as  you repeat some sizes. just added them for more general case


text:
Q: How to prevent INNER JOIN from returning multiple matches?  Every row in my table on the left should have only one match in the table on the right (right table is the master table with all rows in it; left table contains only a subset of these rows). The timestamps of the rows in each table do not match exactly, but they are usually within 1 second of each other. Therefore, when I join the tables, I have to use:
FROM left_table INNER JOIN right_table
ON left_table.timestamp BETWEEN right_table.timestamp - .00015 AND right_table.timestamp + .00015
--This is approximately a 2 second wide range since this is a DATETIME field
AND left_table.name = right_table.name
AND ........

Except for the timestamp, every other criteria matches exactly. Is there a way around this?
Most of the time, this is good enough to return only 1 row, but sometimes when there are two identical rows within a second of each other, they will both be returned.

A: This should be more accurate. The only way to get dupes now is if they both have the same time difference:
FROM left_table
INNER JOIN
  (
     SELECT l.name, min(abs(r.timestamp - l.timestamp)) as offset
     FROM left_table l
     INNER JOIN right_table ON r on r.name=l.name
     GROUP BY l.name
  ) lrmap ON left_table.name = lrmap.name
INNER JOIN right_table
ON left_table.name = right_table.name
    AND abs(left_table.timestamp-right_table.timestamp) = lrmap.offset

I won't vouch for performance, though, because the subtractions are slow and placing them inside the abs() function kills any chance of using indexes on those columns. If I had more time to spend I might be able to put something together that would be more index-friendly... but maybe not, because this looks like weak table design to me, and the real fix will be to add a column that more directly links the records.

A: If you only need precision down to the second, you could truncate off the rest in your select.

A: A where exists() clause is a good way to prevent Cartesian products
FROM left_table lt
where exists(
    select 1 from right_table
    where lt.[timestamp] BETWEEN [timestamp] - .00015 AND [timestamp] + .00015
    and lt.name=name
    AND ........
)
AND ........


text:
Q: Can a contract be written that unlocks parts? Is it possible to write a contract that unlocks parts rather than, or in addition to, money or science?
I want to make it so that, for example, to unlock a better engine you would have to prove that the previous one was tested by taking it to an altitude above the ground, to simulate learning and using the part.

A: This question is old. I started playing on version 1.6. But it's not answered today:
Contracts which order you to test some part, enable the part as "experimental".
You kind of unlock it. But only until you solve this mission.


text:
Q: NSURLRequest autorelease: crash I am having problem releasing NSMutableURLRequest object.
Application crashes during the deallocation of request object.
The object is created via [[NSMutableURLRequest alloc] initWithURL:my_http_url];
As mainstream flow of control, I try to release the connection object in response to connectionDidFinishLoading handler being invoked.
At first  I tried autoreleasing NSMutableURLRequest right inside connectionDidFinishLoading handler. This caused crashing, so I assumed it might be because connection class pushes autorelease pool internally before calling connectionDidFinishLoading and still expects connection object to be valid when the handler returns, so it is impossible then to release or autorelease the connection object inside connectionDidFinishLoading.
If I do not release NSMutableURLRequest at all, according to Instruments it leaks with reference count 1.
Therefore I decided to do a delayed release via firing an NSRunLoop event that autoreleases NSMutableURLRequest passed to it.
This still causes a crash.
retainCount before calling autorelease is 1.
Crash stack is:
#
0   0x9448aedb in objc_msgSend
#1  0x04a47ce0 in ??
#2  0x02e51501 in HTTPMessage::~HTTPMessage
#3  0x02945621 in _CFRelease
#4  0x02e516a9 in HTTPRequest::~HTTPRequest
#5  0x02e50967 in URLRequest::~URLRequest
#6  0x02945621 in _CFRelease
#7  0x0032fb70 in -[NSURLRequestInternal dealloc]
#8  0x0032fb1a in -[NSURLRequest dealloc]
#9  0x002f27a5 in NSPopAutoreleasePool
#10 0x003b5dd0 in __NSFirePerformTimer
#11 0x0299e8a2 in __CFRunLoopDoObservers
#12 0x0296a39e in CFRunLoopRunSpecific
#13 0x0296a048 in CFRunLoopRunInMode
#14 0x031d289d in GSEventRunModal
#15 0x031d2962 in GSEventRun
#16 0x0058ede1 in UIApplicationMain
#17 0x00002b9c in main at main.m:14

Thanks for advise.

A: After using NSDebugEnabled/NSZombieEnabled/NSAutoreleaseFreedObjectCheckEnabled I identified the problem:
result of
http_url = [NSURL URLWithString:...]

should have been either retained or not autoreleased on its own.

A: Try to instantiate it as an autoreleased object using:
[NSMutableURLRequest requestWithURL:my_http_url];

A: I believe Instruments are not useful for any tracing in this case since the
application crashes and then is auto-restarted (it's iPad/iPhone app), so all
Intruments history is gone.

I do not see much point instantiating NSMutableURLRequest as autoreleased object
since it needs to be retained for the duration of async call spanning multiple
idle loop cycles. NSURLConnection may retain it internally or not, but keeping
an extra reference for safety should not hurt.

The initialization code boils down to essentially the following:

rq->url_encoded = [url_encode(rq->url) retain];
 rq->http_url = [NSURL URLWithString:rq->url_encoded];
 rq->http_request = [[NSMutableURLRequest alloc] initWithURL:rq->http_url];
 [rq->http_request setHTTPMethod:@"GET"];

 NSArray* availableCookies = [rq->service.CookieJar cookiesForURL:rq->http_url];
 NSDictionary* headers = [NSHTTPCookie
 requestHeaderFieldsWithCookies:availableCookies];
 [rq->http_request setAllHTTPHeaderFields:headers];
 rq->http_connection = [NSURLConnection alloc];

 [rq->http_connection initWithRequest:rq->http_request delegate:rq
 startImmediately:YES];

The release procedure is that connectionDidFinishLoading calls [rq->http_connection
cancel] and [rq autorelease], the latter eventually leading to:

// [http_request autorelease];
 // delayedAutoRelease(http_request);
 [http_connection autorelease];
 [http_url autorelease];
 [url release];
 [url_encoded release];
 [response release];

Note that [response release] just pairs previous [response retain] executed inside didReceiveResponse.
If I leave first two lines commented out, NSURLRequest leaks with reference
count 1 per Instruments, and this is the only leak observed.
Whenever I attempt to autorelease http_request whichever way as described above,
a crash occurs.


text:
Q: Python(tkinter) Как сделать чтобы окно во время работы программы, увеличивалось? А после 10 секунд исчезло?
Пробывал использовать sleep(), не помагает, он блочит всю программу.

A: Используйте метод after:
root.after(lambda: <your code>)


text:
Q: Quick search directly without AltGr in Total Commander Total Commander requires pressing AltGr with some letter to enter quick search mode. This is a bit difficult.
Is it possible if by pressing any letter to make Total Commander enter into quick search mode?

A: You can configure the quick search mode in the Configuration dialog (Configuration\Options...).
This is a screenshot for Total Commander 8:


text:
Q: Problems with Column content and GridSplitter How can set the width of the content of the 1st 3rd or 5th columns, and still have the splitters work properly?
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Infinity.Shell.Controls.Text;assembly=Infinity.Shell"
    xmlns:dock="clr-namespace:Infinity.Shell.Controls.Docking;assembly=Infinity.Shell"
    xmlns:syncfusion="http://schemas.syncfusion.com/wpf" x:Class="Infinity.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="499.573" Background="#FF1E1E1E">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Button Content="First" Grid.Column="0"/>
    <GridSplitter Grid.Column="1" Width="5" VerticalAlignment="Stretch" HorizontalAlignment="Center"/>
    <Button Content="Second" Grid.Column="2"/>
    <GridSplitter Grid.Column="3" Width="5" VerticalAlignment="Stretch" HorizontalAlignment="Center"/>
    <Button Grid.Column="4" Content="Third"/>
</Grid>


text:
Q: Where I can get the chapterx package? I was viewing a good page where Yiannis Lazarides show how to use chapterx and put it on google drive but right now it does´t exist, some one have it o know how to get it?
Thank you in advanced

A: You're most likely referring to Fancy chapter headings (which has the broken link to chapterx. According to Yiannis' comment, the source has been updated and now lives on GitHub. It's not known as chapterx anymore, but phd.


text:
Q: What is the relative path for data files as shown below? EDIT: I want this to work not only in the IDE (when it runs from the root directory) but also when I run it from Terminal (I have cd'd into the src directory.
I have a file called main.java.org.name.nlp.lg.Class, which is in the src directory. Outside the src directory (in the root directory), I have a folder called data which contains the file data/en/words/file.txt. How can I load file.txt into Class.java via a relative path? My current code gives me a NPE:
URL url = new Class().getClass().getResource("../../../../../../../data/en/words/file.txt");
File f = new File(url.getPath());
List<String> list = Files.readAllLines(f.toPath());
System.out.println(list);

Here is the file tree:
src
  main
    java
      org
        name
          nlp
            lg
              Class
data
  en
    words
      file.txt

Thanks.

A: Path pathToYourFile = Paths.get(Paths.get("data/en/words").toAbsolutePath().toString(),
                               "file.txt");

File yourFile = pathToYourFile.toFile();


text:
Q: Qt Quick Controls 2 and QAbstractTableModel I have a model based on QAbstractTableModel that I would like to use to display its content in a list in QML.
Actually, I need to display the first column only.
TableView does not exist in Qt Quick Controls 2 and suffers from performance issue and rendering issues on HiDPI devices.
There is suggestion in this question to use a ListView. But I fail to see how I can tell the model that I need to display the first column only.
Is there any solution for this ?

A: This is automatically done in QML by ListView: the first column from the model is taken for any requested role.


text:
Q: Import threshold_yen and threshold_isodata from skimage.filter I am working with different threshold algorithms from SKimage, and when I go to import certain packages I get an error, but have no problem with others. For example:
from skimage.filter import threshold_adaptive, threshold_isodata
returns the traceback:
ImportError: cannot import name threshold_isodata. I am using python 2.7, and following the documentation found here: http://scikit-image.org/docs/dev/api/skimage.filter.html#skimage.filter.threshold_isodata
Specifically, I'm hoping to use threshold_isodata and threshold_yen. Does anybody have suggestions for how to solve this error? Alternatively, are there other packages that use the same algorithm?

A: As mentioned in a comment, threshold_isodata is only available in the master repo (i.e. not officially released in v0.9), hence the import error.
It turns out that threshold_yen wasn't properly imported into the filter subpackage in version 0.9. (This has been fixed in master.) Until v0.10 is released, you should import threshold_yen as follows:
from skimage.filter.thresholding import threshold_yen

EDIT: Note that this question and answer are specific to very old versions of scikit-image. The skimage.filter module was renamed skimage.filters in v0.11


text:
Q: How to use non standard evaluation with dollar sign in r Context
I want to use non-standard evaluation with dollar sign in R.
I want to customize a function with two parameters. data is the input data frame, var is the name of the variable in the input data frame. The return value is the value corresponding to the variable name.
I can do this with fun1.
library(dplyr)

df = data.frame(a = 1:3)

fun1 <- function(data, var){
  data %>% pull({{var}})
}

> fun1(data = df, var = a)
[1] 1 2 3

Question
Is there any way to perform the function of fun1 with non-standard evaluation and dollar signs($).
My solution is as follows (fun2) but it reports an error.
fun2 <- function(data, var){    # Can't create fun2, it will report an error.
  data${{var}}
}

fun2(data = df, var = a)

A: We may use [[ to extract after converting the unquoted to string
fun2 <- function(data, var){
     var <- deparse(substitute(var))
     data[[var]]
}

-testing
> fun2(data = df, var = a)
[1] 1 2 3

It is better to use [[ instead of $.  In case, we want to only use $, then paste the names and eval (not recommended)
fun2 <- function(data, var) {
  argslist <- as.list(match.call()[-1])
  eval(parse(text = sprintf('%s$%s',
    deparse(argslist$data), deparse(argslist$var))))
}
> fun2(df, a)
[1] 1 2 3


text:
Q: Warnings NoJoinPredicate This morning, our SQL Server 2016 started using high CPU percentage(90%) when normally is about 30%.
Reviewing cache plan with sp_blitzcache, I saw a new plan for an old query in the top of CPU time.
Full query plan is here.
This plan had a warning about no join predicate.
(@TokenCentro nvarchar(36),@Tarjeta nvarchar(max) ,@TarjetaAux nvarchar(max) )
SELECT   Socios.id, Socios.id AS IdSocio, Centros.id AS IDCentro, Centros.nombre,
         ISNULL(NombreWEB, Centros.Nombre) AS NombreWeb, Socios.Token, Foto, ISNULL(Socios.IdIdioma, 1) AS IdIdioma,
         AplicacionPropia, ISNULL(Socios.IdConf_Regional, 1) AS IdUnidad, Socios_Asignar_Centro.AplicacionWEB,
         CASE WHEN Socios.Email = '' THEN 1
              ELSE CASE WHEN Socios.Email IS NULL THEN 1
                        ELSE 0
                   END
         END AS ConEmail, Centros.HorarioVisible, Centros.PerfilApp, TactilEntrenoSocio, Centros.ColorKiosco,
         Conf_Regional.PrimerDia, ISNULL(Centros.IdGrupoApp, 0) AS IdGrupoApp, Centros.requiere_LOPD,
         ISNULL(Centros.LOPD, '') AS LOPD, Socios.aceptada_lopd, Centros.IntegracionDieta, Empresas.Chat, Centros.field,
         Centros.valoracionApp, Empresas.p_Premios, Centros.Reservas, ISNULL(CustomCss, '') AS CustomCss,
         Socios_Asignar_Centro.PuedeReservar, zonasHorarias.Zona, zonasHorarias.ZonaIana,
         ISNULL(Socios.TokenExten, '') AS TokenExtern, Centros.field1, Centros.tipoServicioPush,
         Socios.Nombre AS NombreSocio, Socios.Apellidos AS ApellidosSocio, Centros_Opciones.forzarLogin
FROM     Socios
INNER JOIN Socios_Asignar_Centro
ON Socios_Asignar_Centro.IdSocio = Socios.Id
INNER JOIN Conf_Regional
ON Conf_Regional.Id = Socios.IdConf_Regional
INNER JOIN Centros
ON Centros.Id = Socios_Asignar_Centro.IdCentro
   AND Centros.FechaBaja IS NULL
INNER JOIN Empresas
ON Empresas.Id = Centros.IdEmpresa
INNER JOIN zonasHorarias
ON Socios.idzonahoraria = zonasHorarias.id
INNER JOIN Centros_Opciones
ON Centros_Opciones.IdCentro = Centros.Id
INNER JOIN Centros_Tactiles
ON Centros_Tactiles.IdCentro = Centros.Id
WHERE    Socios.tarjeta IS NOT NULL
         AND Socios.tarjeta <> ''
         AND Socios.tarjeta <> '0'
         AND (
                 Socios.Tarjeta = @Tarjeta
                 OR Socios.Tarjeta = @TarjetaExtend )
         AND Centros_Tactiles.Token = @Token
         AND (
                 Socios_Asignar_Centro.FechaBaja IS NULL
                 OR Socios_Asignar_Centro.FechaBaja > CONVERT(DATE, GETUTCDATE()))
ORDER BY IdCentro, IdSocio DESC

After changing the length of the parameter from nvarchar(max) to nvarchar(50), the new plan was normal again. However, I can not see where the problem is.
Any ideas?

A: The first thing that jumps out to me is the difference in table access method on Socios. Both queries use the 79271_79270_Socios index but they use them in very different ways. The slow query does a seek to find all rows with Tarjeta not equal to ''. The query optimizer expects to read 6496920 rows out of 6498640 total rows in the table. A predicate is applied to filter out rows not equal to '0'. A filter operator is applied restrict the rows down to those that equal @Tarjeta OR @TarjetaAux, which are NVARCHAR(MAX) variables. This strategy seems odd and a not very efficient use of an index. You said that changing the data type helped so let's do some simple testing to see if SQL Server handles NVARCHAR(MAX) predicates in some special way.
I'm going to assume that the Tarjeta column has a data type of NVARCHAR(50) but I don't think that's particularly important for this demo. Here is my sample data:
create table #demo (col nvarchar(50));

INSERT INTO #demo WITH (TABLOCK)
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) / 1000
FROM master..spt_values t1
CROSS JOIN master..spt_values t2;

create index ix on #demo (col);

For this query I get a nice, simple index seek that has a low cost and only expects to read and return 1000 rows:
SELECT col
FROM #demo
WHERE col = '123';

This query has the same plan:
SELECT col
FROM #demo
WHERE col <> '0' AND col = '123';

It looks like the optimizer is smart enough to eliminate the col <> '0' filter because it's redundant.
If I cast my filter value to NVARCHAR(MAX) things take an unexpected turn:
SELECT col
FROM #demo
WHERE col = CAST('123' AS NVARCHAR(MAX));

The performance of the query is fine. It still only reads 1000 rows from the index. However, the plan is much more complicated. It looks like some information is missing from the XML and I can't figure out how to properly read it. Within the XML I found this:
<ScalarOperator ScalarString="GetRangeWithMismatchedTypes(CONVERT(nvarchar(max),'123',0),CONVERT(nvarchar(max),'123',0),(62))">

Which seems like a hint that SQL Server has to do some kind of conversion to deal with the nvarchar(max) constant value. You can find more information about this in Dynamic Seeks and Hidden Implicit Conversions.
If I make the query a little more complicated I get a similar access pattern to what you experienced with the bad query:
SELECT col
FROM #demo WITH (FORCESEEK)
WHERE col <> '0' AND col = CAST('123' AS NVARCHAR(MAX));

The FORCESEEK hint was an attempt to make the query plan better but it didn't work. SQL Server will read all of the rows from the index and this plan has a much higher cost than before. Note that if we prevent SQL Server from applying an index seek on the <> '0' filter we can get a much more reasonable plan:
SELECT col
FROM #demo
WHERE LEFT(col, 50) <> '0' AND col = CAST('123' AS NVARCHAR(MAX));

However, a better solution is to change the datatype if possible. When switching to NVARCHAR(50) as you did I get a nice, simple index seek with this code:
DECLARE @Tarjeta nvarchar(50) = '123';

SELECT col
FROM #demo
WHERE col <> '0' AND col = @Tarjeta;

In conclusion, the unnecessary use of VARCHAR(MAX) appears to be resulting in extra work in some cases and leading to unnecessarily inefficient plans in others. Based on the information that we have, changing the variable's type seems to be the right preventative step.
Regarding the No Join Predicate warning, you always see that when SQL Server implements part of your query as a cross join. Check out StarJoinInfo in Execution Plans for further information on why that might happen. Sometimes cross joins are good for performance and the right thing to do. Sometimes they may not be ideal but the cross join may be part of a plan that is good enough or the best plan that was found before the optimizer ran out of moves. The query optimizer assigned a very low cost to the cross join based on row estimates. Joining 414 rows to 1 row in a cross join isn't really a big deal, but it could be a problem if those estimates are inaccurate.
It's also hard to say why this plan is suddenly worse than before, especially with what we observed with the simple NVARCHAR(MAX) testing above. Perhaps there was parameter sniffing and SQL server cached a plan generated from unlucky parameters. It's important to realize that SQL Server doesn't know anything about the values of the local variables in your plan without a RECOMPILE hint. The better query that you posted has hardcoded values which isn't a fair comparison to the other query which required SQL Server to guess or to use a cached plan.


text:
Q: How to change image source when a property changes through databinding in XAML from viewmodel in xamarin forms? I am working on providing wishlist feature for my app by tapping wishlist icon on each product in list through MVVM. Once tapped, an API call is made to update database(add/remove from wishlist table). Based on result from api call, I updated the specific product's respective property to either 'True' or 'False'. Once property updated, I want to change the icon image source of corresponding product. I am using trigger on wishlist icon to differentiate non-wishlist and wiahlist products while binding the list itself.
My code is below,
MODEL
public class PublisherProducts
{
   public long ProductId { get; set; }
   public string ProductName { get; set; }
   public string ImageURL { get; set; }
   public decimal Price { get; set; }
   public bool IsWishlistProduct { get; set; }
}

VIEWMODEL
public class OnlineStoreViewModel : BaseViewModel
{
 private ObservableCollection<PublisherProducts> publisherProducts;
 public Command<long> WishlistTapCommand { get; }

 public OnlineStoreViewModel()
 {
    publisherProducts = new ObservableCollection<PublisherProducts>();
    WishlistTapCommand = new Command<long>(OnWishlistSelected);
 }

 public ObservableCollection<PublisherProducts> PublisherProducts
 {
   get { return publisherProducts; }
   set
   {
    publisherProducts = value;
    OnPropertyChanged();
   }
 }

 public async Task GetProducts(long selectedCategoryId)
 {
  try
    {
      ...
      PublisherProducts = new ObservableCollection<PublisherProducts>(apiresponse.ProductList);
      ...
    }
    catch (Exception ex) {  ... }
    finally {  ... }
 }

 async void OnWishlistSelected(long tappedProductId)
 {
   if (tappedProductId <= 0)
     return;
   else
     await UpdateWishlist(tappedProductId);
 }

 public async Task UpdateWishlist(long productId)
 {
   try
   {
    var wishlistResponse = // api call
    var item = PublisherProducts.Where(p => p.ProductId == productId).FirstOrDefault();
    item.IsWishlistProduct = !item.IsWishlistProduct;

    PublisherProducts = publisherProducts;  *Stuck here to toggle wishlist icon*

    await App.Current.MainPage.DisplayAlert("", wishlistResponse.Message, "Ok");
   }
   catch (Exception ex) {  ... }
   finally {  ... }
 }
}

XAML
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" ... >
     <ContentPage.Content>
      <ScrollView>
        <StackLayout Padding="15,0,15,10">
         <FlexLayout x:Name="flxLayout" BindableLayout.ItemsSource="{Binding PublisherProducts}" ...>
           <BindableLayout.ItemTemplate>
             <DataTemplate>
               <AbsoluteLayout Margin="6" WidthRequest="150">
                  <Frame Padding="0" WidthRequest="150" CornerRadius="10" HasShadow="True">
                     <StackLayout Orientation="Vertical" Padding="10" HorizontalOptions="FillAndExpand">
                       <Image Source="{Binding ImageURL}" WidthRequest="130" HeightRequest="130" HorizontalOptions="Center"/>
                       <Label Text="{Binding ProductName}" Style="{StaticResource ProductNameStyle}"></Label>
                       ...
                       <StackLayout ...>
                         ...
                         <Frame x:Name="wlistFrame" Padding="0" WidthRequest="30" HeightRequest="30" CornerRadius="10" BorderColor="#02457A">
                           <StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="Center">
                              <Image x:Name="wlImage" WidthRequest="13" HeightRequest="12" HorizontalOptions="Center" VerticalOptions="Center" Source="ic_wishlist_open">
                                <Image.Triggers>
                                   <DataTrigger TargetType="Image" Binding="{Binding IsWishlistProduct}" Value="true">
                                      <Setter Property="Source" Value="ic_wishlist_close" />
                                   </DataTrigger>
                                </Image.Triggers>
                               </Image>
                            </StackLayout>
                            <Frame.GestureRecognizers>
                                <TapGestureRecognizer Command="{Binding Source={RelativeSource AncestorType={x:Type local:OnlineStoreViewModel}}, Path=WishlistTapCommand}" CommandParameter="{Binding ProductId}" NumberOfTapsRequired="1" />
                            </Frame.GestureRecognizers>
                         </Frame>

                       </StackLayout>
                     </StackLayout>
                  </Frame>
               </AbsoluteLayout>
             </DataTemplate>
          </BindableLayout.ItemTemplate>
        </FlexLayout>
       </StackLayout>
     </ScrollView>
    </ContentPage.Content>
  </ContentPage>

I am stuck at this place to change wishlist icon, when 'IsWishlistProduct' property value is changed in UpdateWishlist().

A: Guessing through your code, the BaseViewModel contains code similar to the following:
public class BaseViewModel : INotifyPropertyChanged
{
   ...
   public event PropertyChangedEventHandler PropertyChanged;
   ...

   public void OnPropertyChanged(string name)
   {
      this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
   }
   ...
}

And your viewmodel should be like this:
...
public ObservableCollection<PublisherProducts> PublisherProducts
 {
   get { return publisherProducts; }
   set
   {
    publisherProducts = value;
    OnPropertyChanged(nameof(PublisherProducts));
   }
 }
...

As Jason mentioned, If there is a change in data in the ViewModel, it is reflected in the UI when it is notified to the View through NotifyPropertyChanged. You already implemented "OnPropertyChanged" function in your BaseViewModel but it seems you don't pass the object name.


text:
Q: difference in meaning: morphology / structure What is the difference in meaning between "morphology" and "structure"?
Coming from a physics background and being a native German speaker, I tend to use "structure" when describing an internal configuration, and to use "morphology" when describing an overall outer appearance.
I wonder if this distinction is correct? I would like to learn about the difference between the two terms in general, in order to decide when to use which.

A: Morphology in the most general sense means the "study of shape". In most fields and in most situations it's basically the same as studying the structure of something, but occasionally there will be something which has a shape but no apparent structure. For example, here are two galaxies. You can talk about the morphology of both, but only the second has much structure to talk about:


text:
Q: How to share image intent with viewpager? I need to develop an application, where I need to be able to share image from ImageView in ViewPager when user press on Share Button.
My problem:

*

*when Ipress on Share Button the ImageView cache the next Image not the current .

public class MainActivity extends Activity {
    private ViewPager pager;
       private ImageView Imgv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    pager = (ViewPager) findViewById(R.id.pager);
    final Integer[] imageUrls={
        R.drawable.img1 , R.drawable.img2 , R.drawable.img3 , R.drawable.img4
    };
    pager.setAdapter(new MyAdapter(imageUrls));

    Button share = (Button) findViewById(R.id.share);
    share.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Imgv.setDrawingCacheEnabled(true);
            Bitmap icon = Imgv.getDrawingCache();
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            File file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
            try {
                file.createNewFile();
                FileOutputStream  fo = new FileOutputStream(file);
                fo.write(bytes.toByteArray());
            } catch (IOException e) {
                    e.printStackTrace();
            }

            Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
            shareIntent.setType("image/jpeg");
            Uri uri = Uri.parse("file:///sdcard/temporary_file.jpg");
            shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            shareIntent.putExtra(Intent.EXTRA_STREAM,uri);
            startActivity(shareIntent);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
private class MyAdapter extends PagerAdapter {

    private LayoutInflater inflater;
    private Integer[] fimg;

    public MyAdapter(Integer[] fimg ) {
        this.fimg=fimg;

        inflater = getLayoutInflater();

    }

    @Override
    public Object instantiateItem(View collection,  int position  ) {

        final View imageLayout = inflater.inflate(R.layout.imgview, null);

       Imgv =  (ImageView)imageLayout.findViewById(R.id.full_image_view);

        Imgv.setBackgroundResource(fimg[position]);

         ((ViewPager) collection).addView(imageLayout ,0);

           return imageLayout;

       }

    @Override
    public int getItemPosition(Object object) {
        // TODO Auto-generated method stub
        return super.getItemPosition(object);
    }

    @Override
    public int getCount() {
        return fimg.length;
    }
    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((View) object);
    }
    @Override
    public boolean isViewFromObject(View view, Object object) {
        // TODO Auto-generated method stub
        return view==((View)object);
    }

      @Override
      public void restoreState(Parcelable arg0, ClassLoader loader) {}

      @Override
      public Parcelable saveState() {
          return null;
      }
      @Override
        public void startUpdate(View container) {
        }
      @Override
        public void finishUpdate(View container) {

        }

}
}

A: It is because you think that Imgv is ImageView from current visible page in ViewPager. But it isnt. In your case Imgv is ImageView from the last inflated page, but not the current visible page.
I suggest you to add tag to ImageView:
Imgv.setBackgroundResource(fimg[position]);
Imgv.setTag(position);  // add this line

Then you can find your ImageView by tag:
ImageView Imgv = (ImageView)pager.findViewWithTag(pager.getCurrentItem());
Imgv.setDrawingCacheEnabled(true);
...

A: To avoid using the drawing cache which may sometimes mean a downscaled image, I'd check out the onPageSelected() event of the ViewPager onPageChange listener.
Save the current index, and create the file to be saved from your original asset.

A: The Simplest and best way to get the images is by using http://developer.android.com/reference/android/support/v4/view/ViewPager.html#getCurrentItem()
This will give you the index of the current page which is nothing but the index of the imageUrls which has the current image.
So get your bitmap from imageUrls using BitmapFactory.
BitmapFactory.decodeResource(getResources(), imageUrls[pager.getCurrentItem()]);


text:
Q: Maya Python object assigned as a listType, but won't convert to string? I'm starting to use objects a bit more to store Maya commands in Python. This is super useful!
But I've run into a problem. Sometimes objects get commands that return Unicode lists rather than a string. Even using str() doesn't work.
Code:
cubeParent = cmds.polyCube(sx=10, sy=15, sz=5, h=20)

print cubeParent                # prints transform and shape node, but unicode list?
print str(cubeParent)           # prints transform and shape node, again unicode list?
print cubeParent[0]             # prints transform node with good formatting! yay!

Why is cubeParent assigned as a listType?

A: You need to convert each item in the list to string datatype.
print list(map(str, cubeParent))

OR
print [str(i) for i in cubeParent]

A: for lurkers:  You can get the info you want with multiple assignments as well:
transform, shape = cmds.polyCube()
print transform
# 'pCube1'


text:
Q: aligning 3 images in HTML and CSS without table Im trying to align 2 images and some text.
I do not want to use a table to do this.
Is there a way to do it using inline styling?
I would like them to all be equally spaced as well.
IMG 1 > TEXT > IMG 2
Hope this makes sense

A: Try this,
Updated

div {
    text-align: justify;
    display:table;
}

span{
    display:table-cell;
    vertical-align:middle;
    padding:0 60px;
}

 Text Here

A: You can do this with flexbox:
HTML

text

CSS
div {
    display: flex;
    justify-content: center;
}

More info: https://css-tricks.com/snippets/css/a-guide-to-flexbox/


text:
Q: c-string being saved to the end of another c-string I am making a program to store a library's book collection. One of the options is to add a new book to an array of structures.
Here is the code
do
{
    repeat = 0;

    cout << "Enter the book's title: ";
    cin.getline(tempTitle, (TITLE_SIZE) * 2);

    for (int i = 0; i < bookNumber; i++)
    {
        if (strcmp(tempTitle, bookArray[i].title) == 0)
        {
            cout << "That title has already been entered, please enter a new book\n";
            repeat = 1;
        }
    }

    if (strlen(tempTitle) < 1 || strlen(tempTitle) > TITLE_SIZE)
    {
        cout << "The Book's title must be between 1 and 50 characters long\n";
        repeat = 1;
    }

} while (repeat == 1);

strncpy(bookArray[bookNumber].title, tempTitle, TITLE_SIZE);
file << bookArray[bookNumber].title << "\n";

do
{
    repeat = 0;

    cout << "Enter the book's ISBN number: ";
    cin.getline(tempIsbn, (ISBN_SIZE) * 2);

    if (strlen(tempIsbn) != ISBN_SIZE)
    {
        cout << "The Book's title must be 13 digits long\n";
        repeat = 1;
    }

} while (repeat == 1);

strncpy(bookArray[bookNumber].isbn, tempIsbn, ISBN_SIZE);

Here is my input
Enter the book's title: new book title
Enter the book's ISBN number: 0000000000000
Enter the book's author: Person
Is the book currently in stock (y/n)? y

Here is what it is saved as
Title : new book title
ISBN #: 0000000000000Person
Author: Person
Status: Available

Why is it saving the author c-string to the end of the isbn c-string?

A: book::ISBN seems to be a 13-element char array. If you pass this array to a C string processing function, the function receives just the start address and not the length, so it scans the memory for a byte with the numeric value 0 (not ASCII '0'), and considers that to be the end of the string. The thirteen chars in ISBN are completely filled by the digits, and directly followed by the author, so printing of the ISBN goes on until the terminating 0 byte of the author member.
You can do a limited-length printing like this for example:
printf("ISBN: %.13s\n", books[index].ISBN);

A: Your logic of inputing data is invalid. For example if data member isbn is defined like
char isbn[ISBN_SIZE];

where ISBN_SIZE is equal to 13  then this data member can store only 12 digits because the last character of the array will store the terminating zero.
So you should define ISBN_SIZE as equal to 14 if you want that data member isbn. would store 13 digits.
Also if isbn has size ISBN_SIZE then it is not clear why you use expression
(ISBN_SIZE) * 2 to enter a value.
cin.getline(tempIsbn, (ISBN_SIZE) * 2);

Thus after enetering a value data member isbn does not contain the terminating zero of the string.
The corresponding code snippet could look the following way
bool repeat = false; // the initialization only for exposition

do
{
    cout << "Enter the book's ISBN number: ";
    cin.getline( tempIsbn, ISBN_SIZE );

    if ( repeat = ( strlen( tempIsbn ) != ISBN_SIZE - 1 ) )
    {
        cout << "The Book's ISDN number must be " << ISBN_SIZE - 1 << " digits long\n";
    }

} while ( repeat );

strcpy( bookArray[bookNumber].isbn, tempIsbn );

The same remarks are valid for entering the title of a book.


text:
Q: SharpGL not rendering on Button Click I was testing the SharpGL sample on winform, where it is rendering triangle on openGLDraw event. But when I am trying to render it with button click its not working. Is it supposed to not render outside of openGLDraw event ? Here are the codes:
private void DrawScene()
{
    OpenGL gl = openGLControl.OpenGL;
    gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);
    gl.LoadIdentity();
    gl.Begin(OpenGL.GL_TRIANGLES);
    gl.Color(1.0f, 0.0f, 0.0f);
    gl.Vertex(0.0f, 1.0f, 0.0f);
    gl.Color(0.0f, 1.0f, 0.0f);
    gl.Vertex(-1.0f, -1.0f, 1.0f);
    gl.Color(0.0f, 0.0f, 1.0f);
    gl.Vertex(1.0f, -1.0f, 1.0f);
    gl.Color(1.0f, 0.0f, 0.0f);
    gl.Vertex(0.0f, 1.0f, 0.0f);
    gl.Color(0.0f, 0.0f, 1.0f);
    gl.Vertex(1.0f, -1.0f, 1.0f);
    gl.Color(0.0f, 1.0f, 0.0f);
    gl.Vertex(1.0f, -1.0f, -1.0f);
    gl.Color(1.0f, 0.0f, 0.0f);
    gl.Vertex(0.0f, 1.0f, 0.0f);
    gl.Color(0.0f, 1.0f, 0.0f);
    gl.Vertex(1.0f, -1.0f, -1.0f);
    gl.Color(0.0f, 0.0f, 1.0f);
    gl.Vertex(-1.0f, -1.0f, -1.0f);
    gl.Color(1.0f, 0.0f, 0.0f);
    gl.Vertex(0.0f, 1.0f, 0.0f);
    gl.Color(0.0f, 0.0f, 1.0f);
    gl.Vertex(-1.0f, -1.0f, -1.0f);
    gl.Color(0.0f, 1.0f, 0.0f);
    gl.Vertex(-1.0f, -1.0f, 1.0f);
    gl.End();
}

private void openGLControl_OpenGLDraw(object sender, RenderEventArgs e)
{
    //this.DrawScene(); //Working
}

private void button1_Click(object sender, EventArgs e)
{
    this.DrawScene(); //Not working
}

A: Just add openGLControl.Refresh(); after DrawScene(). It was fooling me for past few days. I discovered it after reading their source code. :D
private void button1_Click(object sender, EventArgs e)
{
    this.DrawScene(); //Not working
    openGLControl.Refresh();
}


text:
Q: deleting list element if the element is present on another column of a dataframe I have a list of dataframe list=[df1,df2,df3,df4,...df10]  the dataframe are constructed as following :
>df1
     col1  col2  col3  col4
      Y     2     XX     PP

I have another dataframe DATA_SEL such that
>DATA_SEL
col1  col2  col3  col4
A      KK   C      D
A1     PP   C      D
...................
..................

If the first value (a string) of col4 for every dataframe in list (df1 ,df2,df3....df10 )does not match with any value of col2 in DATA_SEL , I want to delete that df from list.
How could I possibly do that?
Also if I want to construct a new list, list2 where the first value (a string) of col4 for every dataframe in list (df1 ,df2,df3....df10 ) matches with any value of col2 in DATA_SEL , how to do that?

A: Use list comprehension with filtering:
L = [df1,df2,df3,df4,...df10]

#tested first value of col4
out = [x for x in L if DATA_SEL['col2'].eq(x.at[x.index[0], 'col4']).any()]
#if first row has index == 0
out = [x for x in L if DATA_SEL['col2'].eq(x.at[0, 'col4']).any()]

#tested any value of col4
out = [x for x in L if DATA_SEL['col2'].isin(x['col4']).any()]


text:
Q: Create Drop Down Menu Hi Everyone I'm working on a website now and i want to create horizontal navigation menu with dropdown submenus. In the below i add some websites example navigation menu. When you click free tutorials you 'll get what i mean. I can create simple drop down menu with ul and li and the css's but i don't know how to assign diffirent hover color for each row.
I hope someone guide me to create this. The Link is;
http://tutsplus.com/
Thank you all
Here's the what i'm trying for
in the source code i wrote this:

Main Menu

Main Menu 2

Sub Menu

Sub Item 1

Sub Item 2

Main Menu 2

Sub Item

Sub Item

Main Menu 3

Main Menu 4

and the css is
#menu {
  border: none;
  border: 0px;
  margin: 0px;
  padding: 0px;
  font: 67.5% "Lucida Sans Unicode", "Bitstream Vera Sans", "Trebuchet Unicode MS", "Lucida Grande", Verdana, Helvetica, sans-serif;
  font-weight: bold;
  width: auto;
}
#menu ul {
  background: #333333;
  height: 35px;
  list-style: none;
  margin: 0;
  padding: 0;
}
#menu li {
  float: left;
  padding: 0px;
}
#menu li a {
  background: #333333 url("images/seperator.gif") bottom right no-repeat;
  display: block;
  font-weight: normal;
  line-height: 35px;
  margin: 0px;
  padding: 0px 25px;
  text-align: center;
  text-decoration: none;
  font-size: 14px;
}
#menu > ul > li > a {
  color: #cccccc;
}
#menu ul ul a {
  color: #ffffff;
}
#menu li > a:hover,
#menu ul li:hover > a {
  background: #58bce1 url("images/hover.png") bottom center no-repeat;
  color: #ffffff;
  text-decoration: none;
}
#menu li ul {
  background: #333333;
  display: none;
  height: auto;
  padding: 0px;
  margin: 0px;
  border: 0px;
  position: absolute;
  width: 225px;
  z-index: 200;
  /*top:1em;
    /*left:0;*/

}
#menu li:hover ul {
  display: block;
}
#menu li li {
  background: url('images/sub_sep.gif') bottom left no-repeat;
  display: block;
  float: none;
  margin: 0px;
  padding: 0px;
  width: 225px;
}
#menu li:hover li a {
  background: none;
}
#menu li ul a {
  display: block;
  height: 35px;
  font-size: 12px;
  font-style: normal;
  margin: 0px;
  padding: 0px 10px 0px 15px;
  text-align: left;
}
#menu li ul a:hover,
#menu li ul li:hover > a {
  background: #58bce1 url('images/hover_sub.png') center left no-repeat;
  border: 0px;
  color: #ffffff;
  text-decoration: none;
}
#menu p {
  clear: left;
}
#menu ul ul li {
  position: relative;
}
#menu ul ul ul {
  left: -9999px;
  top: 0;
}
#menu ul ul li:hover > ul {
  left: 100%;
}
#menu.align-center > ul > li {
  display: inline-block;
  float: none;
}
#menu.align-center > ul {
  text-align: center;
  font-size: 0;
}
#menu > ul > li {
  position: relative;
}
#menu.align-right > ul > li {
  float: right;
}
#menu.align-right > ul > li:hover > ul {
  right: 0;
  left: auto;
  text-align: right;
}
#menu.align-right ul ul li a {
  text-align: right;
}
#menu.align-right ul ul li:hover > ul {
  left: auto;
  right: 100%;
}

A: So you want to create a hover effect for each menu in the dropdown? So when i hover over the first one it will get red and the second will be blue?
Here's how you can do that:
#menu ul ul > li:nth-child(2):hover {
    background: #ff0000;
}

Here 2 means second element. So you can add this for every element.
Here's a WORKING FIDDLE (use other selectors tho, this is just for demonstrating)

A: You are actually looking for this
That is exactly what you want to do.
Hope will help you.


text:
Q: mknod on cifs samba : operation not permitted when pulling with docker I have a smb share mounted in my linux box using cifs that seems to work. It is able to pull gcc:8 docker image and download, verify and pull all layers of the image (I verified this to a pull of the image on a local drive).
I resolved an issue with creating symbolic links; The cifs mounted share is using file and dir access permissions 0777, and I use a cifs argument int /etc/fstab called mfsymlinks to make softlinks work for docker.
The docker pulling has failed before by saying it could not create symlinks, while pulling one of the layers and it also failed once by not being able to 'mkdir', probably because of the access permissions not being permissive. I did not yet 'clean' the docker staging area on the disk, so maybe it could be a leftover of that failure?
Here are the last few lines of the docker pull process:
...
16ea0e8c8879: Pull complete
50024b0106d5: Pull complete
ff95660c6937: Pull complete
9c7d0e5c0bc2: Pull complete
29c4fb388fdf: Pull complete
f87845d1b3b4: Pull complete
adc3e1e98dd6: Pull complete
4dc8223d50f0: Pull complete
failed to register layer: Error processing tar file(exit status 1): failed to mknod("/usr/bin/g++", S_IFCHR, 0): operation not permitted

Given that only root is able to create new nodes (mknod) through kernel code calls (in this case, creating a node to store the g++ compiler within the docker layer), I started thinking that this issue has to do with the user permissions; either the gitlab-runner, the user-creddentials of the cifs mount, or the docker service, or something else?
Here's how that gitlab job initiates:
Running with gitlab-runner 12.5.0 (577f813d)
  on XYZ-for-project abcdefgh
Using Shell executor...
Running on XYZ...
Fetching changes with git depth set to 50...
Reinitialized existing Git repository in /mnt/share/NightlyBuild/abcdefgh/0/username/project/.git/
Checking out df111d72 as master...
Skipping Git submodules setup
$ docker login $IMAGE_PATH -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /home/gitlab-runner/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
$ docker info
Client:
 Debug Mode: false

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 0
 Server Version: 19.03.2
 Storage Driver: overlay2
  Backing Filesystem: <unknown>
  Supports d_type: true
  Native Overlay Diff: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version:
 runc version:
 init version:
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.3.0-24-generic
 Operating System: Ubuntu 19.10
 OSType: linux
 Architecture: x86_64
 CPUs: 4
 Total Memory: 7.775GiB
 Name: XYZ
 ID: 435N:UBGI:NS4Z:CX6F:GD2A:WMPT:4THN:FQQX:6NRU:VKJL:O7E2:V46F
 Docker Root Dir: /mnt/share/NightlyBuild/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

WARNING: No swap limit support
$ docker build -f Lin64-Base/Dockerfile -t docker-build .
Sending build context to Docker daemon    949MB

Step 1/37 : FROM gcc:8
8: Pulling from library/gcc
16ea0e8c8879: Pulling fs layer
50024b0106d5: Pulling fs layer
ff95660c6937: Pulling fs layer
9c7d0e5c0bc2: Pulling fs layer
29c4fb388fdf: Pulling fs layer
f87845d1b3b4: Pulling fs layer
adc3e1e98dd6: Pulling fs layer
4dc8223d50f0: Pulling fs layer
b601d78e8f0b: Pulling fs layer
f87845d1b3b4: Waiting
adc3e1e98dd6: Waiting
4dc8223d50f0: Waiting
b601d78e8f0b: Waiting
9c7d0e5c0bc2: Waiting
29c4fb388fdf: Waiting
50024b0106d5: Verifying Checksum
50024b0106d5: Download complete
...

** Update **
I mentioned that I did not 'clean' the docker stage area, but also on a fresh  docker home dir (replacing /var/lib/docker) the same behavior occurs, with the same error reported.
This is issue is such that I have to use a local ubuntu disk that lives inside a VirtualBox on Windows10 host. The partition has 150 GB available and is more than large enough, and the host has over 50 GB free disk size. So this seems like a solution, until I run into another issue. The vanishing disk space occurs during a (ninja) c++ build of sources, during the docker build stage. The forum tags the thread as 'resolved' and mentions chkdsk /f as the solution, but it is actually the reboot of Windows that fixes the wrongly reported free disk size of the host. When the disk size seemingly seems to be under megabyte, Windows 10 freezes with a blue message screen saying it cannot continue. Of course, rebooting windows shuts down the Virtual Box, Ubuntu, gitlabrunner job and docker build, so that's clearly NOT a good solution.


text:
Q: Why am I getting blob.Slice/blob.webkitSlice is not a function errors? Hi friendly and helpful people!
I not Web Developer at all, but unfortunately I've got to work with HTML/JavaScript/ASP.net right now. I need an Uploader which splits the to-be-uploaded files before uploading, due to file size reasons.
I've found this explanation online and tried to use it. Of course I edited it a little bit. My JavaScript looks like this now:
function upload(file) {
    var blob = file;
    var BYTES_PER_CHUNK = 1000000; // sample chunk sizes.
    var SIZE = blob.size;

    //upload content
    var start = 0;
    var end = BYTES_PER_CHUNK;
    var completed = 0;
    var count = SIZE % BYTES_PER_CHUNK == 0 ? SIZE / BYTES_PER_CHUNK : Math.floor(SIZE / BYTES_PER_CHUNK) + 1;

    while (start < SIZE) {
        var chunk = blob.Slice(start, end); // doesn't matter if use mozSlice/webkitSlice, same error

        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            completed = completed + 1;
            if (completed === count) {
                uploadComplete();
            }
        };
        xhr.open("POST", "/ItemTracking/MultiUpload", true);
        xhr.send(chunk);

        start = end;
        end = start + BYTES_PER_CHUNK;
    }
}

multiUpload() (in the following code block) will be called when a button has been clicked. It works so far. But every time I get the error that blob.Slice/blob.webkitSlice is not a function. Any ideas? What am I doing wrong? file is an HTML-Input-File (multiple) element. JavaSript is always killing me. :|
function multiUpload()
{
    var files = document.getElementById('file').files;
    var i;

    for (i = 0; i < files.length; ++i) {
        upload(files[i]);
    }
}


text:
Q: logmein is constantly trying to launch something on my Mac logmein is constantly trying to launch something on my Mac. I have looked everywhere but I can't find what is kicking it off.
I can't catch it either since it's only there for split second.

9/30/14 5:15:57.792 PM com.apple.xpc.launchd[1]: (com.logmein.logmeinserver[2983]) Service could not initialize: Unable to set current working directory. error=2, path=/Library/Application Support/LogMeIn/bin/: 14A361c: xpcproxy + 12907 [1227][238D58F9-901A-3047-9B11-EAC2A66E131C]: 0x2
9/30/14 5:15:57.792 PM com.apple.xpc.launchd[1]: (com.logmein.logmeinserver) Service only ran for 0 seconds. Pushing respawn out by 1 seconds.
9/30/14 5:15:58.798 PM com.apple.xpc.launchd[1]: (com.logmein.logmeinserver[2984]) Service could not initialize: Unable to set current working directory. error=2, path=/Library/Application Support/LogMeIn/bin/: 14A361c: xpcproxy + 12907 [1227][238D58F9-901A-3047-9B11-EAC2A66E131C]: 0x2
9/30/14 5:15:58.798 PM com.apple.xpc.launchd[1]: (com.logmein.logmeinserver) Service only ran for 0 seconds. Pushing respawn out by 1 seconds.
9/30/14 5:15:59.801 PM com.apple.xpc.launchd[1]: (com.logmein.logmeinserver[2985]) Service could not initialize: Unable to set current working directory. error=2, path=/Library/Application Support/LogMeIn/bin/: 14A361c: xpcproxy + 12907 [1227][238D58F9-901A-3047-9B11-EAC2A66E131C]: 0x2
9/30/14 5:15:59.801 PM com.apple.xpc.launchd[1]: (com.logmein.logmeinserver) Service only ran for 0 seconds. Pushing respawn out by 1 seconds.
9/30/14 5:16:00.858 PM com.apple.xpc.launchd[1]: (com.logmein.logmeinserver[2986]) Service could not initialize: Unable to set current working directory. error=2, path=/Library/Application Support/LogMeIn/bin/: 14A361c: xpcproxy + 12907 [1227][238D58F9-901A-3047-9B11-EAC2A66E131C]: 0x2
9/30/14 5:16:00.858 PM com.apple.xpc.launchd[1]: (com.logmein.logmeinserver) Service only ran for 0 seconds. Pushing respawn out by 1 seconds.
9/30/14 5:16:01.866 PM com.apple.xpc.launchd[1]: (com.logmein.logmeinserver[2987]) Service could not initialize: Unable to set current working directory. error=2, path=/Library/Application Support/LogMeIn/bin/: 14A361c: xpcproxy + 12907 [1227][238D58F9-901A-3047-9B11-EAC2A66E131C]: 0x2
9/30/14 5:16:01.866 PM com.apple.xpc.launchd[1]: (com.logmein.logmeinserver) Service only ran for 0 seconds. Pushing respawn out by 1 seconds.

A: I had the same problem.
You just need to execute in console the following command:
sudo launchctl remove com.logmein.logmeinserver


text:
Q: Remove Categories / Tags From Admin Menu I want to remove or hide Categories / Tags submenu under Posts in the Admin Menu. I know this works with the themes submenus:
remove_submenu_page( 'themes.php', 'widgets.php' );
The same doesn't seem to work for posts unfortunately:
remove_submenu_page( 'edit.php', 'edit-tags.php' );
I'm using the admin_menu action: add_action( 'admin_menu', 'function_call' )
Do I need to add something else?

A: You may also want to remove the meta boxes from the Post Creation page
// REMOVE POST META BOXES
function remove_my_post_metaboxes() {
  remove_meta_box( 'categorydiv','post','normal' ); // Categories Metabox
  remove_meta_box( 'tagsdiv-post_tag','post','normal' ); // Tags Metabox
}
add_action('admin_menu','remove_my_post_metaboxes');

A: Thanks to @mbacon40 and to @gmazzap I was able to use this to remove Product Tags and Categories (product_tag and product_cat) from my menu and from the product add/edit pages.
// Remove Categories and Tags
add_action('init', 'myprefix_remove_tax');
function myprefix_remove_tax() {
    register_taxonomy('product_cat', array());
    register_taxonomy('product_tag', array());
}

add_action('admin_menu', 'my_remove_sub_menus');
function my_remove_sub_menus() {
    remove_submenu_page('edit.php', 'edit-tags.php?    taxonomy=product_cat&post_type=product');
    remove_submenu_page('edit.php', 'edit-tags.php?    taxonomy=product_tag&post_type=product');
}

A: add_action('admin_menu', 'my_remove_sub_menus');

function my_remove_sub_menus() {
    remove_submenu_page('edit.php', 'edit-tags.php?taxonomy=category');
    remove_submenu_page('edit.php', 'edit-tags.php?taxonomy=post_tag');
}

A: If you want to completely remove categories and tags you can do so like this:
// Remove Categories and Tags
add_action('init', 'myprefix_remove_tax');
function myprefix_remove_tax() {
    register_taxonomy('category', array());
    register_taxonomy('post_tag', array());
}

A: for some reason the edit.php does not work at my setup 5.3
This however works
remove_submenu_page( 'edit-tags.php?taxonomy=category', 'edit-tags.php?taxonomy=post_tag' );
remove_submenu_page( 'edit-tags.php?taxonomy=category', 'edit-tags.php?taxonomy=category' );


text:
Q: Prevent re-loading of javascript if functions already exist. Otherwise ensure synchronous loading Using JQuery.load(), I change the content of my website's mainWindow to allow the user to switch between tabs. For each tab, there is one or multiple scipts that contain functions that are executed once the tab content is loaded.
Obviously when switching to the tab for the first time, the script has to be fetched from the server and interpreted, but this shouldn't happen if the user switches back to the tab later on. So, to put it short:

*

*Load() html

*make sure javascript functions exist, otherwise load script and interpret it.

*call a a function on the javascript after the DOM is rebuilt.
Step one and two have to be complete before step 3 is performed.
At the moment, I am using nested callbacks to realize this:
function openFirstTab(){
    $("#mainWindow").load("firstTab.php", function(){
        if(typeof(onloadfFirstTab) != "function"){
            jQuery.getScript("assets/js/FirstTab.js", function(){
                onloadFirstTab();
            });
        }
        else{
            onloadFirstTab();
        }

    } );

}

but I feel that there should be a better way.

A: You can't write the code entirely synchronously since you can't load script synchronously after page load ( unless you do a synchronous XHR request and eval the results - not recommended ).
You've got a couple of choices.  There are pre-existing dependency management libs like RequireJS which may fit the bill here, or if you just need to load a single file you can do something like this to clean up your code a bit rather than using if/else:
function loadDependencies() {
    // For the sake of example, the script adds "superplugin" to the jQuery prototype
    return $.getScript( "http://mysite.com/jquery.superplugin.js" );
}

function action() {
    // If superplugin hasn't been loaded yet, then load it
    $.when( jQuery.fn.superplugin || loadDependencies() ).done(function() {
        // Your dependencies are loaded now
    });
}

This makes use of jQuery Deferreds/Promises to make the code much nicer.

A: If you don't want to load the JS more than once and you are going to dynamically load it, then the only way to know whether it's already loaded is to test for some condition that indicates it has already been loaded.  The choices I'm aware of are:

*

*The simplest I know of is what you are already doing (check for the existence of a function that is defined in the javascript).

*You could also use a property on each tab (using jQuery's .data() that you set to true after you load the script.

*You could write the dynamically loaded code so that it knows how to avoid re-initializing itself if it has already been loaded.  In that case, you just load it each time, but the successive times don't do anything.  Hint, you can't have any statically defined globals and you have to test if it's already been loaded before it runs its own initialization code.

A: (Haven't tested it yet, so I am not sure if it works, especially since I didn't yet really understand scope in javascript:)
function require(scripts, callback){
var loadCount = 0;

function done(){
loadCount -=1;
if (loadCount==0){
    callback();
    }
}

for ( var script in scripts){
    if (!script.exitsts()){
        loadCount +=1;
        jQuery.getScript(script.url, done);
        }
}

}

This function takes an array of scripts that are required and makes sure all of them are interpreted before it calls the callback().
The "script" class:
function script(url, testFunc){
this.url =url;
this.testFunction = testFunc;
this.exists = function(){
if(typeof(testFunction)=="function"){
    return true;
    }
else{
    return false;
    }
}
}

Where the test-function is a function that is defined (only) in the concerned script.
PS:
To enable caching in JQuery and thus prevent the browser from doing a GET request every time getScript() is called, you can use one of the methods that are presented here.
Even though unnecessary GET - requests are avoided, the script is still getting interpreted every time getScript() is called. This might sometimes be the desired behavior. But in many cases, there is no need to re-interpret library functions. In these cases it makes sense to avoid calling getScript() if the required library functions are already available. (As it is done in this example with script.exists().


text:
Q: VB scripting without autocomplete I'm trying to write a short script for some data analysis (kind of software automation). - in vb
The program I have to use for that is so old that the autocomplete feature isnt working ... is it possible to somehow list all parameters from a disticnt method? - their reference just states 'The parameters for this algorithm are specified in the method' (which is very helpful)
[Edit]
It's a built-in editor of the Bruker Daltonics automation software; which uses VBA

A: Try ctrl-alt-J. That brings up the Object Explorer in most flavors of VB.
Also try right-clicking and see if there is a "Go to Definition" option.


text:
Q: Selector doesn't change color on API higher then 21 I need to change color of the ImageButton when user pressing it. It works as I expect on APIs 19 and 21 but on API higher then 21 it doesn't and I can't understand why.
Here is XML of selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <corners
                android:radius="100dp"
                />
            <solid
                android:color="#427A53"
                />
            <padding
                android:bottom="0dp"
                android:left="0dp"
                android:right="0dp"
                android:top="0dp"
                />
            <size
                android:width="60dp"
                android:height="60dp"
                />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <corners
                android:radius="100dp"
                />
            <solid
                android:color="#66bb6a"
                />
            <padding
                android:bottom="0dp"
                android:left="0dp"
                android:right="0dp"
                android:top="0dp"
                />
            <size
                android:width="60dp"
                android:height="60dp"
                />
        </shape>
    </item>
</selector>

A: SOLUTION
Problem was in android:backgroundTint attribute of ImageButton, it was the same color and it was "blocking" change of color.

A: bcz selector working lower than api 21, for higher version you can use like this..
 RippleDrawable rippleImgStart;
 final int ColorWhiteOpacity = Color.argb(75,255,255,255);
 imgStart = ContextCompat.getDrawable(this, R.drawable.start);
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            rippleImgStart = new
                    RippleDrawable(ColorStateList.valueOf(ColorWhiteOpacity), imgStart, null);
            btnselectvideo.setImageDrawable(rippleImgStart);
}


text:
Q: the status of a checkbox in Cocoa In Interface Builder I made a checkbox and a textbox. When the user checks the checkbox I want a message to appear in the textobx that says "the checkbox is checked." If the box is unchecked I want a message to appear in the textbox that says "the check box is unchecked." The problem is that I don't know how to get the status of the checkbox.

A: Ask the button for its state. If it's NSOnState, then it's checked. If it's NSOffState, then it's not checked. If it's NSMixedState, then it has some children that are checked, and some that are not checked.


text:
Q: Mysql server not starting I installed Mysql server 5.7.9 on RHEL 6.5 using mysql57-community-release-el6-7.noarch.rpm Repo. And installation was successfull but when i try to start it up and gives errors. And from /var/log/mysqld.log i get these logs
> 2016-02-16T08:16:55.473839Z 0 [Note] InnoDB: PUNCH HOLE support
> available 2016-02-16T08:16:55.473945Z 0 [Note] InnoDB: Mutexes and
> rw_locks use GCC atomic builtins 2016-02-16T08:16:55.473983Z 0 [Note]
> InnoDB: Uses event mutexes 2016-02-16T08:16:55.474011Z 0 [Note]
> InnoDB: GCC builtin __sync_synchronize() is used for memory barrier
> 2016-02-16T08:16:55.474038Z 0 [Note] InnoDB: Compressed tables use
> zlib 1.2.3 2016-02-16T08:16:55.474062Z 0 [Note] InnoDB: Using Linux
> native AIO 2016-02-16T08:16:55.474908Z 0 [Note] InnoDB: Number of
> pools: 1 2016-02-16T08:16:55.475257Z 0 [Note] InnoDB: Not using CPU
> crc32 instructions mysqld: Can't create/write to file '/tmp/ibUFqzVe'
> (Errcode: 13 - Permission denied) 2016-02-16T08:16:55.475430Z 0
> [ERROR] InnoDB: Unable to create temporary file; errno: 13
> 2016-02-16T08:16:55.475460Z 0 [ERROR] InnoDB: Plugin initialization
> aborted with error Generic error 2016-02-16T08:16:55.475490Z 0 [ERROR]
> Plugin 'InnoDB' init function returned error.
> 2016-02-16T08:16:55.475515Z 0 [ERROR] Plugin 'InnoDB' registration as
> a STORAGE ENGINE failed. 2016-02-16T08:16:55.475536Z 0 [ERROR] Failed
> to initialize plugins. 2016-02-16T08:16:55.475557Z 0 [ERROR] Aborting
>
> 2016-02-16T08:16:55.475583Z 0 [Note] Binlog end
> 2016-02-16T08:16:55.475695Z 0 [Note] Shutting down plugin
> 'keyring_file' 2016-02-16T08:16:55.476442Z 0 [Note] /usr/sbin/mysqld:
> Shutdown complete
>
> 2016-02-16T08:16:55.502968Z mysqld_safe mysqld from pid file
> /var/run/mysqld/mysqld.pid ended

Any advice what this error is talking about ......

A: > [ERROR] InnoDB: Unable to create temporary file; errno: 13

This line looks like a problem there. Try to check if /tmp dir exists (it should) and is available for mysql user (or the user you use). You can try to use a different path with --tmpdir or an option within config, more info at docs).
There can be problem with SELinux too (if it is in Enforcing mode). Check your audit log (eg. with ausearch -ts today -m avc | audit2allow) if /tmp dir isn't blocked for mysql. For tests you can disable SELinux with setenforce 0.

A: MySQL server is not able to access your /tmp directory, to write and create temporary files. Make sure /tmp directory is owned by root user and sticky bit is set on /tmp directory. Type the following commands to fix this error. You must be login as root user and type:
chown root:root /tmp
chmod 1777 /tmp
test it
/etc/init.d/mysqld start


text:
Q: BLE Peripheral & BLE Central I am developing an chat application using BLE Android to iOS,
Right now i am using below two libraries for the reference
https://github.com/izumin5210/Bletia
https://github.com/captain-miao/bleYan
Issue that i am facing is BLECallback in ble central device (Android) are not called when peripheral device write any characteristics.
My Callback Code
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        BleLog.i(TAG, "onConnectionStateChange: State = " + BleUtils.getBleConnectStatus(status)
                + " newState = " + BleUtils.getBleConnectStatus(newState));

        if (newState == BluetoothProfile.STATE_CONNECTED) {
            updateState(BleConnectState.CONNECTED);
            //开始发现服务
            BleLog.i(TAG, "gatt.discoverServices()");
            gatt.discoverServices();
        } else if (newState == BluetoothProfile.STATE_CONNECTING) {
            updateState(BleConnectState.CONNECTING);
        } else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
            updateState(BleConnectState.DISCONNECTING);
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            //断开了,需要做什么处理?
            sIsWriting = false;
            sWriteQueue.clear();
            updateState(BleConnectState.DISCONNECTED);
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {

        if (status == BluetoothGatt.GATT_SUCCESS) {
            onDiscoverServices(gatt);
            //需要返回 gatt
            updateState(BleConnectState.SERVICE_IS_DISCOVERED);
        } else {
            BleUtils.refreshDeviceCache(mGatt);
            //失败 需要做何处理 129
            if(mState != BleConnectState.SERVICE_IS_NOT_DISCOVERED) {
                updateState(mState);
            }
        }

        //MSG_BLE_ID_SERVICES_DISCOVERED
        Message msg = Message.obtain();
        msg.what = BleConstants.MSG_BLE_ID_SERVICES_DISCOVERED;
        msg.arg1 = status;
        msg.obj = gatt;
        notifyAllBleClients(msg);
        BleLog.i(TAG, "onServicesDiscovered: " + BleUtils.getGattStatus(status));
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt,
            BluetoothGattCharacteristic characteristic, int status) {
        BleLog.i(TAG, "onCharacteristicWrite: " + BleUtils.getGattStatus(status));
        UUID uuid = characteristic.getUuid();
        sendBleMessage(BleConstants.MSG_BLE_ID_CHARACTERISTIC_WRITE, status, uuid);
        onNextWrite();
    }

    @Override
    public void onDescriptorWrite(BluetoothGatt gatt,
            BluetoothGattDescriptor descriptor, int status) {
        BleLog.i(TAG, "onDescriptorWrite: " + BleUtils.getGattStatus(status));
        UUID uuid = descriptor.getUuid();

        sendBleMessage(BleConstants.MSG_BLE_ID_DESCRIPTOR_WRITE, status, uuid);
        onNextWrite();
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        final byte[] data = characteristic.getValue();
        BleLog.i(TAG, "onCharacteristicChanged: " + HexUtil.encodeHexStr(data));
        UUID uuid = characteristic.getUuid();

        sendBleMessage(BleConstants.MSG_BLE_ID_CHARACTERISTIC_NOTIFICATION, BluetoothGatt.GATT_SUCCESS, data, uuid);
        onNextWrite();
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        final byte[] data = characteristic.getValue();
        System.out.println(TAG +" onCharacteristicRead: " + data);

        if(data != null) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));

            final String values = stringBuilder.toString();

            BleLog.i(TAG, "onCharacteristicRead: " + new String(data));
        }else{
            BleLog.i(TAG, " onCharacteristicRead: " + "NULL");
        }

        UUID uuid = characteristic.getUuid();

        sendBleMessage(BleConstants.MSG_BLE_ID_CHARACTERISTIC_READ, status, data, uuid);
        onNextWrite();
    }

    @Override
    public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        final byte[] data = descriptor.getValue();

        if(data != null) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));

            final String values = stringBuilder.toString();

            BleLog.i(TAG, "onDescriptorRead: " + new String(data, Charset.defaultCharset()));
        }else{
            BleLog.i(TAG, " onDescriptorRead: " + "NULL");
        }
        UUID uuid = descriptor.getUuid();

        sendBleMessage(BleConstants.MSG_BLE_ID_DESCRIPTOR_READ, status, data, uuid);
        onNextWrite();
    }

    @Override
    public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
        BleLog.i(TAG, "onReliableWriteCompleted: " + BleUtils.getGattStatus(status));

        Message msg = Message.obtain();
        msg.what = BleConstants.MSG_BLE_ID_RELIABLE_WRITE_COMPLETED;
        msg.arg1 = status;
        notifyAllBleClients(msg);
        onNextWrite();
    }

    @Override
    public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
        BleLog.i(TAG, "onReadRemoteRssi: " + rssi + " status:" + BleUtils.getGattStatus(status));

        Message msg = Message.obtain();
        msg.what = BleConstants.MSG_BLE_ID_READ_REMOTE_RSSI;
        msg.arg1 = status;
        msg.arg2 = rssi;
        notifyAllBleClients(msg);
        onNextWrite();
    }

    @Override
    public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
        BleLog.i(TAG, "onMtuChanged: " + BleUtils.getGattStatus(status));

        Message msg = Message.obtain();
        msg.what = BleConstants.MSG_BLE_ID_MTU_CHANGED;
        msg.arg1 = status;
        msg.arg2 = mtu;
        notifyAllBleClients(msg);
        onNextWrite();
    }
};

iOS Notify Code
    if (myPeripheral.connectedToPeer)
    {
        CBCharacteristic *peerAvailable = [myPeripheral findCharacteristicFromUUID:myPeripheral.notifyPeerAvailableUUID];
        if (peerAvailable && !peerAvailable.isNotifying) {
            [myPeripheral.cbPeripheral setNotifyValue:YES forCharacteristic:peerAvailable];
        }

        CBCharacteristic *peerReceiveMessage = [myPeripheral findCharacteristicFromUUID:myPeripheral.peerSendToCentralFromPeripheralUUID];
        if (peerReceiveMessage && !peerReceiveMessage.isNotifying) {
            [myPeripheral.cbPeripheral setNotifyValue:YES forCharacteristic:peerReceiveMessage];
        }

    }

A: The peripheral device should notify that the characteristic has changed by using bluetoothGattServer.notifyCharacteristicChanged
The Android central device should subscribe the notification.
if (characteristic != null) {
                        //SetNotification
                        Log.i(TAG, "SetNotification");
                        gatt.setCharacteristicNotification(characteristic, true);
                        for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
                            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                            gatt.writeDescriptor(descriptor);
                        }

A: In the peripheral ,the Characteristic which you written should have the NOTIFY property, and the central should use the setCharacteristicNotification function to  listening the change of the characteristics . when  the value changed ,the onCharacteristicChanged callback will be triggered.