text:
Q: Select specific node just after a specific node using Xpath I want to select <space/> nodes which are just after <link> node using XPath.
Input :
<p>A.<space/>Olson,<c>1</c>
    <link>
        <context>
            <image/>
        </context><space/>
    </link><space/>W. M.<space/>Sischo,<c>1</c>
    <link>
        <context>
            <image/>
        </context><space/>
    </link><space/>A. C. B.<space/>Berge,<c>2</c>
    <link>
        <context>
            <image/>
        </context><space/>
    </link><space/>A.<space/>Adams-Progar,<c>3</c>
    <link>
        <context>
            <image/>
        </context><space/>
    </link>and<space/> D. A.<space/>Moore <space/><c>1</c> *
    <link>
        <context>
            <image/>
        </context><space/>
    </link>
</p>

I want to select all <space> node just after <link> node. There are 3 nodes like that. There is a another <space> node after <link> node. But there is text as and before <space> node. such  node should not be selected.
Tried Xpath:
space[preceding-sibling::link]

When using above Xpath, select all <space> nodes. Help me to solve this.

A: After running into something similar myself, I think this expression should do it:
//link[following-sibling::space[1][not(preceding-sibling::node()[1][normalize-space(self::text())])]]

A: You can use the following XPath-1.0 expression
//space[preceding-sibling::node()[1] = preceding-sibling::link[1]]/following::text()[1]

Its output is:
W. M.
A. C. B.
A.


text:
Q: Get the list of recently updated columns in PostgreSQL database Using an SQL query, I would like to get the list of columns (corresponding to multiple tables) which are recently updated with INSERT/UPDATE (with in 10 minutes) on the PostgreSQL database!
I have tried using the option information_schema.columns but there is no information like updated_time for the columns. Happy to get any insights on this!
Thanks.

A: This sort of information is not available in PostgresSQL. You would have to collect it yourself using triggers on the tables, but that would incur a performance penalty.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rest API for creating new workspace in Windchill I want to create a workspace in Windchill calling Rest API from our web application. But no where to find such API end point in any of the Windchill Rest API documentation.
Is it possible to create workspace using rest API, if not is there any alternative way to achieve it.

A: On which Windchill version do you work?
When I don't find standard endpoints in the REST Services, I write them myself.
Since Windchill 11.1 I use Spring to create them.
For that you need an entry in codebase/WEB-INF/web.xml like:
<servlet>
    <servlet-name>ConnectorName</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>ConnectorName</servlet-name>
    <url-pattern>/servlet/connector/*</url-pattern>
</servlet-mapping>

In the same folder you need a file named like the Servletname-servlet like ConnectorName-servlet.xml with following content:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd ">
<context:component-scan base-package="packagename" />
<mvc:annotation-driven />

After this you can create a Spring RestController Class in the package defined above in component-scan.


text:
Q: React Native iOS Swift Error: Could not build Objective-C module 'React' Following the steps in the link doesn't help in integrating react native in existing project.
Link:
https://reactnative.dev/docs/integration-with-existing-apps
Configuration
Mac OS X - 10.15.6 (19G2021)
XCode - 12.1 (12A7403)
React Native Cli - 2.0.1
React Native - 0.63.4

package.json
{
  "name": "MyReactNativeApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "yarn react-native start"
  }
  "dependencies": {
    "react-native": "^0.63.4"
  }
}

Podfile
source 'https://github.com/CocoaPods/Specs.git'

# Required for Swift apps
platform :ios, '11.0'
use_frameworks!

# The target name is most likely the name of your project.
target 'MyReactNativeApp' do

  # Your 'node_modules' directory is probably in the root of your project,
  # but if not, adjust the `:path` accordingly
  pod 'React'

end

When I run pod install. I gives a warning.
[!] React has been deprecated

ChatarVer:MyReactNativeApp chatar.veer$ pod install
Analyzing dependencies
Downloading dependencies
Installing React (0.11.0)
Generating Pods project
Integrating client project
Pod installation complete! There is 1 dependency from the Podfile and 1 total pod installed.

[!] React has been deprecated
ChatarVer:MyReactNativeApp chatar.veer$

When I need to import React, it gives 2 error
Could not build Objective-C module 'React' - where I import React
'Layout.h' file not found - in RCTConvert.h

Screenshot:

I did change 'Allow non-modular includes in Framework Module' to YES but it didn't work.
I have observed whatever documentation is mentioned doesn't work smooth & has lots of issues.


text:
Q: Return keyword in query callback Is it necessary to write return keyword while using whereHas in laravel.
For eg. return $query->where('status', 1);
$posts = App\Post::whereHas('comments', function ($query) {
    $query->whereHas('content', function ($query){
       $query->where('status', 1);
    });
})->get();

Do we need to write return in every query callback?

A: No, you're modifying the query builder instance passed to your closure by calling $query->where('status', 1);.  Since objects are passed by reference and where() mutates this instance, there's no need to return anything.

A: There is no need. Also you can use whereHas with nested relationship.
Example:
$posts = App\Post::whereHas('comments.content', function ($query) {
    $query->where('status', 1);
})->get();

A: No. Because you have the same object (and modify it) inside every function. No need to return.


text:
Q: Unable to call refresh() or any of View class methods on created instance In my ExtJS 4.0 app, I have a view already created and initialized, but from one of my controllers, I'm trying to update it using refresh() after creating its instance within controller.
//Following code is within a controller.
var myView = this.getView('MyView').create();
console.log(myView); //this logs entire Map with methods and other members.
myView.refresh(); //doesn't work.

Basically, the logged myView object shows that data within the store is updated, but same is not reflected on the page, hence I tried calling refresh() on View object, but that throws an error saying that method is undefined.
What's wrong here?
P.S.: I'm new to ExtJS.

A: This may happen if your view is not rendered yet. Try this:
myView.on('afterrender', function (self) {
    self.refresh()
});


text:
Q: Silverlight sketchflow: Component screen change state on click I have a component screen which has 2 states: show and hide. When I click some button the component moves onto the stage. Now when you click the component I want it to move back out of the stage. With normal elements this works by using activate state but with component screens it doesn't seem to do anything.
Anybody know how to solve this?
XML:
The component inside my screen:
<local:googlemaps x:Name="googlemaps" Margin="97,0,97,-509" d:IsPrototypingComposition="True" Cursor="Hand" VerticalAlignment="Bottom" d:LayoutOverrides="Height" RenderTransformOrigin="0.5,0.5">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonDown">
            <pi:ActivateStateAction TargetState="hide"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <local:googlemaps.RenderTransform>
        <CompositeTransform/>
    </local:googlemaps.RenderTransform>
</local:googlemaps>

The component screen:
<UserControl
    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:pc="http://schemas.microsoft.com/prototyping/2010/controls"
    mc:Ignorable="d"
    x:Class="EurekaScreens.googlemaps"
    d:DesignWidth="606" d:DesignHeight="480" Height="480" Width="606">

    <Grid x:Name="LayoutRoot">
        <Rectangle Fill="#FF212121" Margin="10,8,0,0" Stroke="Black"/>
        <Rectangle Fill="#FF212121" Margin="0,0,4,3" Stroke="Black" HorizontalAlignment="Right" Width="602"/>
        <Image Margin="1,1,5,4" Source="google maps.jpg" Stretch="Fill"/>
        <pc:SketchRectangleSL HorizontalAlignment="Right" Height="30" Margin="0,0,15,11" Style="{StaticResource Rectangle-Sketch}" VerticalAlignment="Bottom" Width="87"/>
        <TextBlock HorizontalAlignment="Right" Margin="0,0,36,13" Style="{StaticResource SubtitleLeft-Sketch}" TextWrapping="Wrap" Text="CLOSE" VerticalAlignment="Bottom" FontSize="18.667" Height="23" Width="44"/>
    </Grid>
</UserControl>

A: Could you post the xaml for the component screen, and the screen containing it?  Does it work to click anywhere on the component?  I am thinking possibly that it has no background so doesn't receive click events. You could try assigning a background that is clear.
Otherwise, post the xaml and I'll see if I can help.
I'm not entirely sure why, but for some reason it seems like the mouse down event isn't getting to the behavior. When I wrap the component screen in a grid, and put the behavior on a grid, it seems to work properly:
<Grid HorizontalAlignment="Right" Margin="0,-2,-625,2" Width="606" Background="#00000000">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseLeftButtonUp">
                    <pi:ActivateStateAction TargetState="hide"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
            <local:Screen_2 x:Name="screen_2" Height="480" Width="606" d:IsPrototypingComposition="True" RenderTransformOrigin="0.5,0.5">
                <local:Screen_2.RenderTransform>
                    <CompositeTransform/>
                </local:Screen_2.RenderTransform>
            </local:Screen_2>
        </Grid>


text:
Q: How could this transistor be in saturation? For this RTL circuit (RTL inverter with active pull-up):

The textbook says that in the output high state, Qp is in saturation and the circuit looks like:

I wonder how this is possible?
$$Rcp = Rc/10$$ and usually $$R_B > R_C$$ so we expect that the voltage at the base is less than the voltage at the collector. And for saturation, we need $$V_{BC} = 0.6V$$

A: In the first schematic, only Qs is the (RTL) inverter, Qp and Qo are a classic (in the analog world) totem-pole and in fact the output stage looks a lot more like that of TTL.
If we consider what would be typical values [for TTL] for Rc+Rbp = 1.6K and Rcp = 130 ohm, then a high-quality (high-beta) transistor Qp will be saturated when the output is high. To see this, assume Vcc=5V and Vout = 4V. Then Ic of Qp will be at most 7.7mA (ignoring its Vce). And its Ib would be 0.3V/1.6k = 18.75uA. The resulting minimum beta for saturation is 41. So a transistor with beta of 100 will be [lightly] saturated (which is more often called soft saturation). This is what you want for high-speed switching. If the transistor is heavily (aka deeply) saturated it takes a long time to come out of it, so that's unsuitable for high-speed logic (but it's okay and actually desirable in other contexts like power BJTs, where you want to minimize Vce[sat] instead). By the way, the BJT soft saturation region is also called quasi-saturation. Here it is depicted in a textbook:

As you probably figured out, you can get any behavior from that circuit ranging from active mode to deep saturation, depending on the resistor values. If we decrease Rcp, it will go in the active region, if we increase it, it will become more [deeply] saturated.  However, the calculations you have done here seem to ignore the fact that Vo needs to be high. Here's a simulation, with a 2N3904, which has a standard/model beta of 300, and in which we vary the collector resistor from 1 ohm to 201 ohms:

And here is what happens if we additionally vary the beta of the transistor from 25 to 300: a higher beta transistor saturates with a lower Rc.

Finally, I have no idea what resistor assumptions are reasonable for the flavor of RTL that your textbook teaches. This totem-pole speedup (for RTL) is not something mentioned in Wikipedia's page on RTL, by the way. If you're curious about real RTL circuits, read for example the IBM manual linked on that page. (I personally am not interested enough in this topic to do that.)


text:
Q: How to underline links in the navbar using Bootstrap 3? I'm trying to apply custom CSS styling to the Bootstrap navbar, so that the link text is underlined on mouseover. I'd also like the underline to fade in.
Here is what I have so far: https://jsfiddle.net/xfddh0r5/
.navbar-default {
    background-color: #fff;
}
.navbar-default .navbar-nav > li {
    background-color: #fff;
}
.navbar-default .navbar-nav > li > a {
    color: #333;
    border-bottom: 1px solid transparent;
}
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus, .navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus {
    background-color: #fff;
    color: #439348;
    border-bottom: 1px solid #439348;
}

I've noticed two strange problems:

*

*The underline appears at the bottom of the navbar, rather than directly under the text.

*The link 'area' for the menu items seems to be too big. Ideally just the text would be a link.

Could anyone tell me why this is happening?
Many thanks!

A: You can reset the padding to 0 or decrease the values. And use margin to adjust the spacing again.
.navbar-default .navbar-nav > li > a {
  color: #333;
  border-bottom: 1px solid transparent;
  padding: 0; /*removing spacing*/
  margin: 14px; /*add spacing*/
}

A: The links have a lot of padding to make them easy to click on. If you want to apply a border to the text, you can put the text inside a span, and apply the style to that.
HTML:

Home

Item 1

Item 2

CSS:
.navbar-default .navbar-nav > li > a > span {
  border-bottom: 1px solid transparent;
}

You can accomplish the fade using CSS transitions:
.navbar-default .navbar-nav > li > a:hover > span {
  border-bottom-color: #439348;
  transition: border 1s linear;
}


text:
Q: Calling RenderScript from C / JNI I'm looking to replace the C atan2 function with something more efficient. RenderScript does offer atan2, including versions that take vectors.
The examples I found, demonstrates calling RenderScript from Java. Is it possible to call RS from C code ? an example would be great.
Thanks

A: It used to be possible, though RS support in the NDK has been dropped for some time now.  It may still be possible, but even the NDK samples no longer include RS samples.  Starting with Android 7 you could try to use "Single Source RenderScript", described here, which is supposed to be possible from C/C++ code.
The efficiency gains you may see using RS are due to a few possible reasons (which are very platform dependent):

*

*RS will parallelize operations over your data set.  In some cases the function you are calling (such as atan2) may parallelize the operation, if possible.

*Your RS code may be executed on a co-processor (such as a GPU or DSP).

*The RS provided intrinsics and library functions are highly optimized for the platform.  Using atan2 as an example again, it may be possible that the function is more optimized in the RS core than the standard C library as it could be using a co-processor or it could be using architecture specific optimized implementation (assembly).

All of that being said, your code can take an I/O hit when moving data between RS space (Allocation) back to the non-RS code.

A: I have found two examples; here is the one I got to build and run:
https://github.com/adhere/NDKCallRenderScriptDemo
I've been searching for documentation of the C++ API but haven't found it.


text:
Q: Using RPM install files to make decisions in the preinstall Is it possible to access/utilize install files in an RPM from within the preinstall section.
My rpm package contains files separated by type of destination host that I would like to pull variables from and make decisions on during the preinstall. The preinstall will remain generic while the files could contain different settings for different packages. I would also like to be able to abort the install based on certain conditions set up by those values.
This seems impossible given that the rpm hasnt unpacked the files yet, I think, but after looking around Im unable to find anything one way or the other.

A: I also believe it is impossible. I think you need a base package with those files you want to use in the preinstall, and a main package that requires the base. This way you will have the files you want in the preinstall phase.
Please note that you still cannot install different files based on data you found in the preinstall. At most you can delete unneeded files in the postinstall, but this is not a good practice. In this case it is better to create sub-packages, one for each type of host.


text:
Q: Simplify the math expression $M=(1-b)^{N}+(N-4)(1-b)^{N-1} b+ \sum^{N}_{i=1} 2^{2i-2} \Delta^2 (1-b)^{N-1}b-(1-2b)^2$ Can someone help me to further simplify the following expression? Here, $0<b<1$ and we can assume that $b$ is small. $\Delta$ is a constant. Thank you
$M=(1-b)^{N}+(N-4)(1-b)^{N-1} b+ \sum^{N}_{i=1} 2^{2i-2} \Delta^2 (1-b)^{N-1}b-(1-2b)^2$


text:
Q: Multiple edits to correct capitalisation Going through the /review/ list on SO it seems that this user suggested a number of edits which simply updated the first letter of the title to a capital letter. I approved 2 until I saw that there were a number of them and now I'm not sure if this counts as a pedantic edit.
In cases like this, should the edits be approved or rejected for being pedantic - as the edit doesn't really add value or clarification to the question.

A: Incorrect capitalization in the title of a question does not decrease its readers' ability to comprehend the question, nor does it in any way make detract from the value of the question. Therefore, I would classify this edit as pedantic and reject it.
These edits seem more like desperate attempts to gain reputation rather than sincere efforts to improve the quality of the question.

A: I actually consider even minor edits in the title to be a good idea, having titles with bad spelling or grammar stay around makes the site look worse. Having a frontpage with bad grammar and spelling just makes a site look unprofessional.
That said, the specific edits you mention are still bad edits. Not because they just fix the uppercase in the title, but because they leave all the other problems those posts have unedited. I would consider an edit that does nothing but correct the spelling of the title acceptable, but only if the post has no other problems. This situation is pretty rare, but it happens occasionally.


text:
Q: could you tell me what this error means? I just ran below R code but I am getting error msg... Could anyone help me how to make this code runable on my machine. Thanks.
Here's the command:
load(file = "c:\\abcdeXXX.RData")
And here's the resulting error message:
Error in if (!grepl("RD[AX]2\n", magic)) { : argument is of length zero

A: I suspect your file is empty.
The error message means that the argument magic has length zero.  If you read the source code for load, you will find the following line of code:
magic <- readChar(con, 5L, useBytes = TRUE)

Thus magic is the first 5 bytes of your file.  In other words, your file is empty.

A: it is possible that the RData file you are trying to open is damaged or incomplete. Can you open it on another machine?
Also worth noting, early versions of R cannot open RData files created by later versions of R. Although I would not expect a version mismatch to cause your error.


text:
Q: Compare table without join function I would like to match the first table, the second table. The first table must match the data in the second table, I gave the first pairing with. Therefore I can not use the function join.
I'm comparing the two tables, but the counting process takes more than 1 day due to the amount of data. How do I make this work in less time? I would appreciate your help.
Note: I can't join functions. Because I want to one to one matching. Please look at the picture.Click the picture
DECLARE @Sayac1 AS INT = ( SELECT COUNT(*) FROM #T1 );---50.000 data
DECLARE @Sayac2 AS INT = ( SELECT COUNT(*) FROM #T2 );---100.000 data
DECLARE @Siralama1 AS INT = 1;
DECLARE @Siralama2 AS INT = 1;
DECLARE @T1column1 VARCHAR(16), @T1column2 NUMERIC(25, 2), @T1column3 DATE;
DECLARE @T2column1 VARCHAR(16), @T2column2 NUMERIC(25, 2), @T2column3 DATE;
DECLARE @T2column4 INT;
DECLARE @T1column4 INT;

Goto1:

WHILE @Siralama1 <= @Sayac1
    BEGIN
        Goto2:
        WHILE @Siralama2 <= @Sayac2
            BEGIN
                SELECT @T2column1 = Column1, @T2column2 = Column2, @T2column3 = Column3, @T2column4 = Column4 FROM #T2 WHERE Siralama2 = @Siralama2;
                WHILE @T2column4 IS NULL
                    BEGIN
                        SELECT @T1column1 = Column1, @T1column2 = Column2, @T1column3 = Column3, @T1column4 = Column4 WHERE Siralama1 = @Siralama1;
                        WHILE @T1column1 = @T2column1 AND @T1column2 = @T2column2 AND @T1column3 >= @T1column3
                            BEGIN
                                UPDATE #T2
                                SET Column4 = @T1column4 WHERE Siralama2 = @Siralama2;
                                SET @Siralama1 = @Siralama1 + 1;
                                SET @Siralama2 = 1;
                                GOTO Goto1;
                            END;
                        SET @Siralama2 = @Siralama2 + 1;
                        GOTO Goto2;
                    END;
                SET @Siralama2 = @Siralama2 + 1;
            END;
        SET @Siralama1 = @Siralama1 + 1;
        SET @Siralama2 = 1;
    END;

A: I think you do want a join, inside an update statement.
update #T2
    set column4 = #T1.Column4
from #T2 inner join #T1
     on #T1.Column1 = #T2.Column1 and #T1.Column2 = #T2.Column2 and #T1.Column3 = #T2.Column3
where #T2.Column4 IS NULL

I think this will do pretty much what you've tried with your query. It will change T2.column4 to be T1.column4 for the row where the first 3 columns match.

A: I assume that you want to compare whether data in two tables match. If not what is the mismatch.
Therefore your are writing a  loop and comparing it.
I suggest you use some function such as Binary checksum (https://msdn.microsoft.com/en-IN/library/ms173784.aspx)
& go for a set based operation to
find out the differences instead of the current loop which is taking time.
For Starters, here is a sample :
create table t3 (Code int,Val varchar(50),Val1 varchar(20))
create table t2 (Code int,Val varchar(50),Val1 varchar(20))

insert into t2 Values (1,'20', '25')
insert into t2 Values (2,'50',50)

insert into t3 Values (1,'20',25)
insert into t3 Values (23,'5',50)

Select * from ( Select BINARY_CHECKSUM(val,val1) chk, * from  t3 ) a
full outer join (Select BINARY_CHECKSUM(val,val1) chk, *  from  t2 ) b on a.chk = b.chk


text:
Q: moving between section page using next and previous button in javascript In the same page I have multiple sections.
One section will be shown and this will happen using an active class.
In the same page I have li buttons 1, 2 and 3 and when I click on one of them the section related to it appears and the old one disappears. For that purpose I'm using Javascript.
Also in the same page I have a next and previous button. When I click on the next button the next section should appear and the old one should disappear.
And also the related li to the section should have the active class, the same thing for the previous: when I click on it it should go to the old section and the current should disappear and the li class should be active.
When I'm in the first section the  previous button should disappear and when I'm in the last section the next button should disappear.
How can I implement this behavior for the next and previous buttons in this way using Javascript?
Any Help Please!!?

let tab = document.querySelector(".nav li");
let tabs = document.querySelectorAll(".nav li");
let tabsArray = Array.from(tabs);
let section = document.querySelectorAll(".section");
let sectionArray = Array.from(section);
let nextButton = document.querySelector(".next");
let prevButton = document.querySelector(".previous");
let current = 0;

tabsArray.forEach((ele) => {
    ele.addEventListener("click", function (e) {
        tabsArray.forEach((ele) => {
            ele.classList.remove("active");
        });
        e.currentTarget.classList.add("active");

        sectionArray.forEach((sec) => {
            sec.classList.remove("active");
        });
        if(e.currentTarget.dataset.cont =='r1'){
           prevButton.classList.add("disable");
        }else{
          prevButton.classList.remove("disable");
  }
if (
  document.querySelector("#" + e.currentTarget.dataset.cont) ==
  sectionArray[sectionArray.length - 1]
) {
  nextButton.classList.add("disable");
} else {
  nextButton.classList.remove("disable");
}
        document.querySelector('#' + e.currentTarget.dataset.cont).classList.add("active");
    });
});
.section {
display: none;
}

.section.active{
display: block;
}

ul {
list-style: none;
margin:0;
padding: 0;
display: flex;
align-items: center;
}

ul li {
background: #ccc;
padding: 10px 15px;
margin-left: 6px;
border-radius: 50%;
cursor: pointer;
opacity: .5;
}

ul li.active{
opacity: 1 !important;
}

.next,
.previous {
padding: 15px 10px;
border-radius: 6px;
background: deepskyblue;
color: white;
border:0;
outline: none;
cursor: pointer;
width: 100px;
}

.next.disable,
.previous.disable{
  cursor: none;
  opacity: .5;
}

1

2

3

section 1

section 2

section 3

<button class="previous disable" id="previous">Previous</button>
<button class="next" id="next">Next</button>

A: It's advisable to have a collection of buttons and another for sections, connecting the two via the index, which needs to also be tracked. If we have all this, then going next is increasing the index, while going previous is decreasing the index. I'm not making previous and next disappear, even though the question asks me to do so. Instead I'm using the disable class. If we want to make them appear/disappear, then we can use the invisible class instead.

let currentSection = 0;
let sections = document.querySelectorAll(".section");
let sectionButtons = document.querySelectorAll(".nav > li");
let nextButton = document.querySelector(".next");
let previousButton = document.querySelector(".previous");
for (let i = 0; i < sectionButtons.length; i++) {
    sectionButtons[i].addEventListener("click", function() {
        sections[currentSection].classList.remove("active");
        sectionButtons[currentSection].classList.remove("active");
        sections[currentSection = i].classList.add("active");
        sectionButtons[currentSection].classList.add("active");
        if (i === 0) {
            if (previousButton.className.split(" ").indexOf("disable") < 0) {
                previousButton.classList.add("disable");
            }
        } else {
            if (previousButton.className.split(" ").indexOf("disable") >= 0) {
                previousButton.classList.remove("disable");
            }
        }
        if (i === sectionButtons.length - 1) {
            if (nextButton.className.split(" ").indexOf("disable") < 0) {
                nextButton.classList.add("disable");
            }
        } else {
            if (nextButton.className.split(" ").indexOf("disable") >= 0) {
                nextButton.classList.remove("disable");
            }
        }
    });
}

nextButton.addEventListener("click", function() {
    if (currentSection < sectionButtons.length - 1) {
        sectionButtons[currentSection + 1].click();
    }
});

previousButton.addEventListener("click", function() {
    if (currentSection > 0) {
        sectionButtons[currentSection - 1].click();
    }
});
.section {
display: none;
}

.section.active{
display: block;
}

.invisible {
    display: none;
}

ul {
list-style: none;
margin:0;
padding: 0;
display: flex;
align-items: center;
}

ul li {
background: #ccc;
padding: 10px 15px;
margin-left: 6px;
border-radius: 50%;
cursor: pointer;
opacity: .5;
}

ul li.active{
opacity: 1 !important;
}

.next,
.previous {
padding: 15px 10px;
border-radius: 6px;
background: deepskyblue;
color: white;
border:0;
outline: none;
cursor: pointer;
width: 100px;
}

.next.disable,
.previous.disable{
  cursor: none;
  opacity: .5;
}

1

2

3

section 1

section 2

section 3

<button class="previous disable" id="previous">Previous</button>
<button class="next" id="next">Next</button>

A: I hope I understand your question well and the solution below helps.
It is broken into small functions, the goal being that one function does one thing.

let tabs = document.querySelectorAll(".nav li");
let sections = document.querySelectorAll(".section");
let nextButton = document.querySelector("#nextBtn");
let prevButton = document.querySelector("#prevBtn");
let current = 0;

const toggleTabs = () => {
  tabs.forEach(function(tab) {
    tab.classList.remove('active');
  });
  tabs[current].classList.add("active");
  //console.log(current);
}

const toggleSections = () => {
  sections.forEach(function(section) {
    section.classList.remove('active');
  });
  sections[current].classList.add("active");
}

const togglePrev = () => {
  const method = current == 0 ? 'add' : 'remove';
  prevButton.classList[method]("disable");
}

const toggleNext = () => {
  const method = current == tabs.length - 1 ? 'add' : 'remove';
  nextButton.classList[method]("disable");
}

const goNext = () => {
  if (current < tabs.length - 1) {
    current++
  }
  toggleTabs();
  toggleSections();
  toggleNext();
  togglePrev();
}

const goPrev = () => {
  if (current > 0) {
    current--
  }
  toggleTabs();
  toggleSections();
  toggleNext();
  togglePrev();
}
.section {
  display: none;
}

.section.active {
  display: block;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
}

ul li {
  background: #ccc;
  padding: 10px 15px;
  margin-left: 6px;
  border-radius: 50%;
  cursor: pointer;
  opacity: .5;
}

ul li.active {
  opacity: 1 !important;
}

.next,
.previous {
  padding: 15px 10px;
  border-radius: 6px;
  background: deepskyblue;
  color: white;
  border: 0;
  outline: none;
  cursor: pointer;
  width: 100px;
}

.next.disable,
.previous.disable {
  cursor: none;
  opacity: .5;
}

1

2

3

section 1

section 2

section 3

<button class="previous disable" id="prevBtn" onclick="goPrev()">Previous</button>
<button class="next" id="nextBtn" onclick="goNext()">Next</button>

Here is a class-based solution with some CSS changes to center the content:

class TabbedContent {
  constructor() {
    this.tabs = document.querySelectorAll(".nav li");
    this.sections = document.querySelectorAll(".section");
    this.nextButton = document.querySelector("#nextBtn");
    this.prevButton = document.querySelector("#prevBtn");
    this.current = 0;
  }

  toggleTabs() {
    this.tabs.forEach(function(tab) {
      tab.classList.remove('active');
    });
    this.tabs[this.current].classList.add("active");
  }

  toggleSections() {
    this.sections.forEach(function(section) {
      section.classList.remove('active');
    });
    this.sections[this.current].classList.add("active");
  }

  togglePrev() {
    const method = this.current == 0 ? 'add' : 'remove';
    this.prevButton.classList[method]("disable");
  }

  toggleNext() {
    const method = this.current == this.tabs.length - 1 ? 'add' : 'remove';
    this.nextButton.classList[method]("disable");
  }

  goNext() {
    if (this.current < this.tabs.length - 1) {
      this.current++
    }
    this.toggleTabs();
    this.toggleSections();
    this.toggleNext();
    this.togglePrev();
  }

  goPrev() {
    if (this.current > 0) {
      this.current--
    }
    this.toggleTabs();
    this.toggleSections();
    this.toggleNext();
    this.togglePrev();
  }

}

const tabbedContent = new TabbedContent();
.container {
  max-width: 600px;
  margin: 0 auto;
  text-align: center;
}

.section {
  display: none;
}

.section.active {
  display: block;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
}

ul li {
  background: #ccc;
  padding: 10px 15px;
  margin-left: 6px;
  border-radius: 50%;
  cursor: pointer;
  opacity: .5;
}

ul li.active {
  opacity: 1 !important;
}

.next,
.previous {
  padding: 15px 10px;
  border-radius: 6px;
  background: deepskyblue;
  color: white;
  border: 0;
  outline: none;
  cursor: pointer;
  width: 100px;
}

.next.disable,
.previous.disable {
  cursor: none;
  opacity: .5;
}

1

2

3

section 1

section 2

section 3

  <button class="previous disable" id="prevBtn" onclick="tabbedContent.goPrev()">Previous</button>
  <button class="next" id="nextBtn" onclick="tabbedContent.goNext()">Next</button>

A: If you want to make the "previous"/"next" button disappear without changing the layout, then you can set those buttons to "visibility:hidden;" by default in CSS and change it to "visibility:visible;" when the relevant event is triggered.
Also you can use the "button" tag instead of the "li" tag for the top navbar as well.
Below is my code:

const sectionContent = ["r1", "r2", "r3"];
let currentSection = sectionContent[0];

const displayContent = (q, area) => {
    document.getElementById(q).classList.add("active");
    document.getElementById(q + "-button").classList.add("button-active");
    currentSection = sectionContent[area.indexOf(q)];
    const toNone = area.filter(e => e !== q);
    for (i in toNone) {
        document.getElementById(toNone[i]).classList.remove("active");
        document.getElementById(toNone[i] + "-button").classList.remove("button-active");
    }
    if (sectionContent.indexOf(q) == 0) {
        document.getElementById("previous").classList.remove("button-active");
        document.getElementById("next").classList.add("button-active");
    }
    else if (sectionContent.indexOf(q) == sectionContent.length - 1) {
        document.getElementById("previous").classList.add("button-active");
        document.getElementById("next").classList.remove("button-active");
    } else {
        document.getElementById("previous").classList.add("button-active");
        document.getElementById("next").classList.add("button-active");
    }
}

const displayR1 = () => displayContent("r1", sectionContent);
const displayR2 = () => displayContent("r2", sectionContent);
const displayR3 = () => displayContent("r3", sectionContent);

const displayNext = () => displayContent(sectionContent[sectionContent.indexOf(currentSection) + 1], sectionContent);
const displayPrevious = () => displayContent(sectionContent[sectionContent.indexOf(currentSection) - 1], sectionContent);
.container {
    display: grid;
    place-items: center;
}

.section {
display: none;
}

.section.active {
display: block;
}

.nav {
list-style: none;
margin:0;
padding: 0;
display: flex;
align-items: center;
}
.nav button {
background: #ccc;
padding: 10px 15px;
margin-left: 6px;
border-radius: 50%;
cursor: pointer;
opacity: .5;
border: none;
}

.next,
.previous {
padding: 15px 10px;
border-radius: 6px;
background: deepskyblue;
color: white;
border:0;
outline: none;
cursor: pointer;
width: 100px;
visibility: hidden;
}

.button-active {
opacity: 1 !important;
visibility: visible;
}

            <button class="button-active" id="r1-button" onclick="displayR1()">1</button>
            <button id="r2-button" onclick="displayR2()">2</button>
            <button id="r3-button" onclick="displayR3()">3</button>

section 1

section 2

section 3

            <button class="previous" id="previous" onclick="displayPrevious()">Previous</button>
            <button class="next button-active" id="next" onclick="displayNext()">Next</button>

A: tabsArray.forEach((ele) => {
    ele.addEventListener("click", function (e) {
        tabsArray.forEach((ele) => {
            ele.classList.remove("active");
        });
        e.currentTarget.classList.add("active");

        sectionArray.forEach((sec) => {
            sec.classList.remove("active");
        });
    // get the current click section
    // if the current section is 3
    // Then next button should be disabled
    // else if the current section is 1
    // Then prev button should be disabled

        document.querySelector('#' + e.currentTarget.dataset.cont).classList.add("active");
    });
});

Sorry not good at plain Javascript,
But for easy visualization
That should be the process
You may identify the current section by getting the data-cont attribute,
Using jQuery the code will be
$(ele).attr('data-cont') which will return any r1, r2, or r3
// Get the current data-cont value in li attribute
var currSection = $(ele).attr('data-cont')
// Disable previous button when currSection is r1
$('button.previous').prop('disabled', currSection == 'r1')
// Disable next button when currSection is r3
$('button.next').prop('disabled', currSection == 'r3')


text:
Q: need inputs to change the date pattern using python regsub I am using the below reg.sub to change the date format from yyy-mm-dd to dd-mm-yyy . But the new date format also comes in the original format and does not change.Can you please point me what I am missing here?
def dateextract1(dt):
return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})/', '\\3-\\2-\\1', dt)

dt1 = "2026-01-02"
print("Original date in YYY-MM-DD Format: ",dt1)
print("New date in DD-MM-YYYY Format: ",dateextract1(dt1))

=======================
Original date in YYY-MM-DD Format:  2026-01-02
New date in DD-MM-YYYY Format:  2026-01-02   [ I would expect : 02-01-2026]

A: Any reason for using RegEx for this? The Python datetime library has a pretty effective date formatter.


text:
Q: JQuery/Ajax/Class: removeClass() then addClass() is not working as intended inside ajax function I have two ajax functions that is using the same button. My intention is in my save_button class, add_group is there by default but what I want to do is when my Edit button is clicked, add_group will be removed and be replaced by update_group so that a different ajax function is used
Save Button:
<button type="submit" class="save_button add_group">Save</button>

Edit Button:
<button type="button" class="edit_group">Edit</button>

Ajax:
$(document).on('click', '.add_group', function(e) {
  e.preventDefault();
 (additional content) });

$(document).on('click', '.update_group', function(e) {
  e.preventDefault();
  (additional content )});

What I tried:
$(document).on('click', '.edit_group', function(e) {
  e.preventDefault();
  $(".save_button").removeClass("add_group").addClass("update_group"); });

This function seems to not work, the save button does not trigger the add or update if I use this function. asking for any advice on how to fix this.
(Goal: trigger removeClass and addClass when edit_button is clicked)

A: $(document).on('click', //....

Is really a poor choice for capturing events.  This requires the event to bubble up through every parent element to the document.  It's slow and can cause you massive headaches if you have any parent elements that capture elements (because they may cancel the bubbling of the event as well).  I'll demonstrate below a better solution.
Per the JQuery Documentation .on()

The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document element. In Internet Explorer 8 and lower, a few events such as change and submit do not natively bubble but jQuery patches these to bubble and create consistent cross-browser behavior.

Changing what a button does via class/bindings is also a poor choice because it's much harder to keep track of state on the object itself when it's not the container of what is happening.
I would highly recommend reading Philip Walton's (Engineer @ Google) - Decoupling Your HTML, CSS, and JavaScript.

$(".js-edit-button").on('click', function(e) {
  $(this).closest('.form')
    .removeClass('is-add')
    .addClass('is-update');
});

$(".js-save-button").on('click', function(e) {
  var $lastAcion = $(this).closest('.form')
    .find('.form-save-last-action-type');

  if ($(this).closest('.form').is('.is-add')) {
    $lastAcion.text('Add');
  }

  if ($(this).closest('.form').is('.is-update')) {
    $lastAcion.text('Update');
  }
});

.form.is-add .is-update {
  display: none;
}

.form.is-update .is-add {
  display: none;
}

Form is in Add Mode

Form is in Update Mode

  <button type="button" class="js-save-button">Save</button>
  <button type="button" class="js-edit-button">Edit</button>

None


text:
Q: Unable to locate unnamed iframes in capybara using the 0 index I have an iframe that is unnamed so I'm trying to use the solution here to access it: How do I find an unnamed I-Frame with Capybara but I continue to get the following error: Unable to locate frame: 0 (Selenium::WebDriver::Error::NoSuchFrameError)
The frame of interest is two frames deep so I have set up the code below but it fails with the aforementioned error; I also took a look into the source of the driver but the section I'm interested in that references the index is commented out: https://github.com/jnicklas/capybara/blob/master/lib/capybara/selenium/driver.rb could this mean that it has been deprecated?
require "capybara/dsl"

include Capybara::DSL

Capybara.run_server = false
Capybara.default_driver = :selenium
Capybara.default_selector = :xpath
Capybara.ignore_hidden_elements = false

visit "http://example.com"

within_frame 0 do
  within_frame 0 do
    imagelist = page.all("//div[contains(@class, 'panel')]//img")
    chosenimages = imagelist.map{ |link| link['src'] }
    imagechoices = chosenimages.map do |imagechoice|
    finalfilename = File.basename(imagechoice)
    puts finalfilename
    puts imagechoice
    end
  end
end

A: I figured this one out I actually was using the wrong index for the first within_frame the page in question had some hidden frames that I didn't take into account. +1 capybara and +1 stackoverflow.

A: Use this line to switch into frame.
switch_to.frame(index)


text:
Q: The "Optimize code" checkbox in Visual Studio. What exactly does it do? The Build tab of the Project Properties in Visual Studio 2005/2008 contains the "Optimize code".
The documentation states that it "... enables or disables optimizations performed by the compiler to make your output file smaller, faster, and more efficient."

*

*My question is why should I NOT have it on?

*Why is it not on by default?

*What does it actually do?

A: Wikipedia has an article on compiler optimization that covers many of the basic types of optimizations.
You don't want to create optimized debug builds.  Optimization affects the debugabbility of your code - some lines of code may be removed, some lines of code from different parts of a function or from different functions may be merged together, local variables may be folded together, and so on.  This means when debugging your current line can appear to jump around randomly due to the code being reorganized and inspecting local variables can be very misleading - the space for a local might be reused when it is no longer needed and appear to give a jibberish result.

A: *

*You wouldn't want this on for a debug built, as it makes stepping through code harder as the actual code that is running may not properly reflect what you have written (since some lines will be optimized out)

*It is not on by default for DEBUG builds for the above reason, it should be enabled by default on release builds

*It performs optimizations such as dynamic inlining and removing unneeded local variables. Any sort of optimization that can be decided upon at compile time.

A: Have a look at the answers to What is /optimize C# compiler key intended for? They answer your questions (especially Noldorin's answer).


text:
Q: android:onClick="openBrowser" doesn't work in XML The android:onClick="openBrowser" doesn't work when I clicked the text, however it work fine for other image such as Facebook, Twitter and Instagram. The link in valid and it can be clickable when I put the text below the image but doesn't when I change the position. Can anyone help me with this?
<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:src="@drawable/homepagel2"
    android:scaleType = "fitXY" />

<LinearLayout
    android:id="@+id/linearLayout4"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_centerHorizontal="true"
    android:orientation="horizontal"
    android:gravity="bottom"
    android:layout_alignParentBottom="true"
    android:layout_marginTop="60dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/logofacebook"
        android:tag="http://www.facebook.com"
        android:onClick="openBrowser"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/instagramlogo"
        android:tag="http://instagram/"
        android:onClick="openBrowser"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/twitter"
        android:tag="https://twitter.com"
        android:onClick="openBrowser"
        />
</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout5"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:orientation="horizontal">

    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginBottom="-90dp"
       android:textSize="25sp"
       android:text="@string/website"
       android:tag="http://www..../"
       android:onClick="openBrowser"
       android:textColor="#ffffff"/>

</LinearLayout>

A: Add android:clickable="true" to your TextView

A: By default, TextViews aren't clickable. I am not sure that you can perform a onClick event by using this xml attribute on textview without clickable attribute. Then, you can try to add this attribute:
android:clickable="true"

Or should make a click listener as below:
((TextView) findViewById(R.id.text1)).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        openBrowser(v);
    }
});

with this view:
<TextView
    android:id="@id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="-90dp"
    android:textSize="25sp"
    android:text="@string/website"
    android:tag="http://www..../"
    android:textColor="#ffffff" />

The click listener will automatically make it clickable, then the previous attribute will be useless.

A: This works for me
<TextView
            android:id="@+id/text1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:autoLink="all"
            android:text="@string/link_text_auto"
            />

source :http://android.okhelp.cz/linkify-text-link-url-in-textview-text-android-example/


text:
Q: How to run an electron app with arguments? My app is electron with a BrowserWindow loading a local page index.html.
I call npm run start a script to run electron main.js , the app opens and the html loaded.
Can I add an argument to the script that will load different html file into the BrowserWindow ?
In the main.js file the code is :
function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    webPreferences:{
      webSecurity:false
    },
    fullscreen : false });//, alwaysOnTop : true , kiosk : true })
  mainWindow.setMenu(null);
  // and load the index.html of the app.
  let url = `file://${__dirname}/index.html`; \\ index.html should be determined by argument passed at start.
  mainWindow.loadURL(url,loadOptions);

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
}

A: To pass the command line arguments to electron app:
./node_modules/.bin/electron main.js --arg1=value --arg2=value

It can be retrieved like this in the main.js:
import { app } from "electron";
app.commandLine.getSwitchValue("arg1");
app.commandLine.getSwitchValue("arg2");

A: The way of passing arguments will be same, the only thing you have to take care is path of electron. In package.json its written npm start will perform electron main.js. So you will have to execute this command explicitly and pass arguments with "proper path of electron" i.e ./node_modules/.bin/electron. Then the command will be
./node_modules/.bin/electron main.js argv1 argv2

and these arguments you can access by process.argv in main.js
and If wish you to access these parameters in your app then there are following things to do :
1.In your main.js define a variable like
     global.sharedObject = {prop1: process.argv}

2.In your app just include remote and use this sharedObject
    var remote = require('electron').remote,
      arguments = remote.getGlobal('sharedObject').prop1;

    console.log(arguments);

3.Output will be ["argv1", "argv2"]
Source : https://discuss.atom.io/t/how-to-pass-command-arguments-in-electron/17247

A: UninstallDisplayName

This lets you specify a custom name for the program's entry in the
  Add/Remove Programs Control Panel applet. The value may include
  constants. If this directive is not specified or is blank, Setup will
  use the value of [Setup] section directive AppVerName for the name.

"build": {
  "nsis": {
    "uninstallDisplayName": "Your app name..."
  }
}

Read more:
NSIS
UninstallDisplayName


text:
Q: Different regex behavior in Python 2.7 and Python 3.5 I have a simple code snippet to search a target word and preceding words:
# -*- coding: utf-8 -*-
import re
txt = u"Min bil är trasig. Det är det också förbundet med ett sjukhus"
tag = u"(förbundet)"
pat = u'(?:\\w+[ \\t,]+){0,2}'+ tag
res = re.finditer(pat,txt,re.IGNORECASE|re.MULTILINE)
for i in res:
    print i.group()

When I run this code using Python 2.7, I am getting only the word 'förbundet'.
When I run the same code using Python 3.5, I am getting  'det också förbundet'. This is, the expected behavior (get up to two words before the target). What is causing the error in Python 2.7?
In the real code, when I define the search pattern I cannot use the raw text format because, the search pattern is defined in a loop (that is I have to escape manually) where I go through a list of of targets words and I built a new search pattern for each target word.

A: You must pass the re.U / re.UNICODE flag in Python 2.x that is on by default in Python 3.x to make the shorthand character class Unicode aware. Replace the re.MULTILINE with re.U (the re.M flag looks redundant here since there is no ^ and $ in your pattern).
# -*- coding: utf-8 -*-
import re
txt = u"Min bil är trasig. Det är det också förbundet med ett sjukhus"
tag = u"(förbundet)" pat = ur'(?:\w+[ \t,]+){0,2}'+ tag
res = re.finditer(pat,txt,re.IGNORECASE|re.U)
for i in res:
    print i.group().encode("utf8")

See the Python 2.7.10 demo.
Note that using raw string literals can help you reduce double backslashes to single backslashes in the regex pattern.


text:
Q: Is there a way to show lock screen controls using AVAudioEngine and AVAudioPlayerNode? I am handling audio playback using AVAudioEngine and AVAudioPlayerNode in my app, and I want to implement remote controls. Background audio is configured and working.
Control center controls work, but the play/pause button does not update when I play/pause the music from inside the app. I am testing on a real device.
Control center screenshot
Here is my AVAudioSession setup code:
func setupAudioSession() {

    UIApplication.shared.beginReceivingRemoteControlEvents()

    do {
        try AVAudioSession.sharedInstance().setActive(true)
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    } catch let sessionError {
        print("Failed to activate session:", sessionError)
    }
}

MPRemoteCommandCenter setup:
func setupRemoteControl() {

    let commandCenter = MPRemoteCommandCenter.shared()

    commandCenter.playCommand.isEnabled = true
    commandCenter.playCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in
        self.audioPlayerNode.play()
        return .success
    }

    commandCenter.pauseCommand.isEnabled = true
    commandCenter.pauseCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in
        self.audioPlayerNode.pause()
        return .success
    }
}

Lock screen controls - never appeared.

A: So here is the solution to my problem, I was starting my AVAudioEngine together with its setup function called from viewDidLoad(), that was the issue, and i used .play()/.pause() methods on my AVAudioPlayerNode to manipulate the audio, however AVAudioPlayerNode does not emit master audio, outputNode of AVAudioEngine does.
So whenever you want to play/pause audio from inside your app or from command center, if you are using AVAudioEngine to handle audio in you application, don't forget to call .stop()/.start() methods on your AVAudioEngine. Lock screen controls should show up and play/pause buttons should update properly in command center/lock screen even without a single property set to MPNowPlayingInfoCenter.default().nowPlayingInfo.
MPRemoteCommandCenter setup:
func setupRemoteControl() {

    let commandCenter = MPRemoteCommandCenter.shared()

    commandCenter.playCommand.isEnabled = true
    commandCenter.playCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in
        try? self.audioEngine.start()
        return .success
    }

    commandCenter.pauseCommand.isEnabled = true
    commandCenter.pauseCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in
        self.audioEngine.stop()
        return .success
    }
}


text:
Q: Centering a form within a div I have a simple contact form within a div but I can't get it to center within the div. I have tried margins, padding, text-align:center but none of them work.
html: http://www.joekellywebdesign.com/churchsample/contact.html

Contact Form

    <form action="feedback.php" method="post">

                    Name:

                    <input type="text" name="fullname" id="tswname" size="25" />

                    Email address:

                    <input type="text" id="tswemail" name="email" size="25" />

                    Comments

                    <textarea rows="15" cols="35" name="comments" id="tswcomments"></textarea>

                    <input type="submit" value="Submit" />

    </form>

css: http://www.joekellywebdesign.com/churchsample/css/styles.css
/* rules for contact page */

#contactbottomleft {z-index:26; width:450px;height: 700px; background-color:#92B681; margin: 30px 0 0 0; float:left;position: relative;}

#contactbottomright { z-index:27; width:450px; height: 700px; margin: 30px 0 0 0px; background-color:#428C3E; float:right;position: relative;}

form {
    display: inline-block;
    text-align: center;
}

    /* end rules for contact page */

A: You could set a width to the form and then add margin: 0 auto; to the CSS. For example:
HTML:

    <form></form>

CSS:
form {
    margin: 0 auto;
    width: 300px;
}

NOTE: For this to work, you must remove display:inline-block from form.
JS Fiddle Example (using your HTML/CSS).

A: You must set a Width of Ancestor element and then add margin:0 auto to its child.
See demo


text:
Q: Contar frequência de ocorrências incluindo zeros Para o seguinte caso a contagem de x utilizando a função table irá retornar a frequência dos valores existentes. Gostaria de saber como retornar a contagem para o intervalo discreto de 1 a 12, incluindo os valores cuja frequência é zero.
set.seed(2)
x <- sample.int(12, 50, replace = TRUE)
table(x)

A: Para incluir os valores para os quais a frequência é zero, converta para factor com todos os níveis e aplique table.
table(factor(x, levels = 1:12))
#
# 1  2  3  4  5  6  7  8  9 10 11 12
# 6  6  5  3  3  8  5  5  5  0  2  2

O valor 10 tem uma frequência de zero mas está no resultado final, como pedido.

A: table usa a função tabulate, que retorna por padrão todos os intervalos. Pode usá-la diretamente:
set.seed(2)
x <- sample(12, 20, replace = TRUE)

table(x)
#> x
#>  1  2  3  5  6  7  9 10 11 12
#>  1  1  5  1  2  3  1  1  2  3

tabulate(x)
#>  [1] 1 1 5 0 1 2 3 0 1 1 2 3

Se precisa que retorne como um vetor nomeado:
setNames(tabulate(x), seq_len(max(x)))
#>  1  2  3  4  5  6  7  8  9 10 11 12
#>  1  1  5  0  1  2  3  0  1  1  2  3


text:
Q: Use Java Path Finder from another java project I want to use JPF (Java Path Finder) from another java project.
Steps that i have done:

*

*I have created a new Java project

*Referenced the jpf-core in build path.

*Created a java class(Test.java) printing Hello world (in my new project).

*Created a .jpf file (Test.jpf) in that i have mentioned,  target=Test.

*In the eclipse launch configuration i have mentioned
project = jpf-core
Main Class = gov.nasa.jpf.tool.RunJPF

My problem is If i place the same .java file and .jpf file in jpf-core/examples package in jpf-core project i am able to run the jpf file and get the results. But when i am trying to run the .jpf from another java project i am unable to do so. I am getting the following error
[SEVERE] can't find startup class: Test`
[SEVERE] error initializing startup classes (check 'classpath')

Please help me to resolve this.
Update:
Do i have to write any properties file mentioning the classpath of my Test class files? If i write so how do i link up them with jpf.properties?

A: I hope this is not too late.
I am using Eclipse Plugin for JPF.
To run the JPF from another java project. I need to create a jpf.properties file to setup the config. With eclipse plugin and it can be auto-generated when creating a JPF project. Inside the jpf.properties file, the .classpath and .sourcepath config need to be set to your testing file (always from build\XXX as JPF is loading java bytecode).
Then right click on the .jpf file and click "Verify" (eclipse plugin). Before hand, I need to tell the eclipse about the jpf-core directory. Just create a site.properties file and write "jpf-core = your JPFdirectory" will be done. Thank you.
As advised by the JPF authority, JPF is easier and faster with plug-in support.

A: Your other project needs to reference the project that contains the Test class. Otherwise it is obviously not on the classpath. Check the Project tab under Build-Path.


text:
Q: How to cache error net::ERR_CONNECTION_REFUSED on JavaScript Web Socket I'm working on JavaScript client websocket. Code work fine once I run both server program and my below client javascript.
   try {
        webSocket = new WebSocket(webSocketURL);
        webSocket.onopen = function(openEvent) {
            console.log("WebSocket OPEN: " + JSON.stringify(openEvent, null, 4));
        };
        webSocket.onclose = function (closeEvent) {
            console.log("WebSocket CLOSE: " + JSON.stringify(closeEvent, null, 4));
        };
        webSocket.onerror = function (errorEvent) {
            console.log("WebSocket ERROR: " + JSON.stringify(errorEvent, null, 4));
        };
        webSocket.onmessage = function (messageEvent) {
            var wsMsg = messageEvent.data;
            console.log("WebSocket MESSAGE: " + wsMsg);
            if (wsMsg.indexOf("error") > 0) {
                console.log (wsMsg.error);
            } else {
                console.log (wsMsg);
            }
        };
    } catch (exception) {
        console.error(exception);
    }

But, I got an error 'net::ERR_CONNECTION_REFUSED' that cached by webbrowser. But my code can not catch this error.
Regarding see error message from this picture https://ibb.co/bHSBw0G. Any advise or guidance would be greatly appreciated, Thanks.

A: I think ErrorEvent has non enumerable properties (only enumerable being isTrusted getter - not super useful). Try accessing property explicitly by doing something like:
webSocket.onerror = function (errorEvent) {
  console.log("WebSocket ERROR: " + errorEvent.message)
}


text:
Q: Медиа-запрос или аналог относительно родителя, а не вьюпорта или экрана Имеется вот такой блок:

Хотелось бы сделать так, чтобы при достаточности ширины он трансформировался в такой блок:

Как писать свойства - понятно: заменить инлайн-блоки на блоки, добавить отступы и т.д.
С запросами, на первый взгляд, тоже понятно. Пишем что-то типа:
.selector {
    свойства для телефонов
}

@media screen and (min-width: 768px) {
    .selector {
        свойства для планшетов и десктов
    }
}

Но как быть в случае, если этот блок встречается на разных страницах и в одном случае брейкпойнтом должно быть 768px, а в другом 1024px, например? Например, на одной странице есть сайдбар, уменьшающий пространство, а на другой нету.

Получается, что этот запрос нужно делать относительно родителя. Если, например, родитель 400+ пикселей, то применяем свойства выстраивающие элементы блока колонками.
Медиазапрос должен выглядеть как-то так:
@media (ширина контекста: 480px) { ... }

Подскажите, пожалуйста, есть ли возможность организовать медиазапросы таким образом?
Другими слова: я вижу, что этот блок должен трансформироваться, если есть свободных 400px, но как мне определить, что ширина родителя 400+? Медиазапросом я могу определить только ширину вьюпорта или экрана и она не всягда связана с шириной родителя.
Я пока что вижу два варианта:
а) На разных страницах проставлять нашему блоку разные классы, например
@media screen and (min-width: 768px) {
    .selector_unfold-on768 { ... }
}
@media screen and (min-width: 1024px) {
    .selector_unfold-on1024 { ... }
}

Но тогда придется дублировать одни и теже свойства (ну или убирать в миксины и инклюдить).
б) отказаться от медиа-запросов как таковых и пасть JS`ом.

A: Верно мыслите, тут либо через классы либо JS, ибо медиа запросы не умеют работать с DOM элементами

A: Подозреваю, что такое можно сделать с помощью flexbox.
Media-запросы работают только с viewport'ом.


text:
Q: How to display floating tool tip text on a polygon I have written a Java code to draw a polygon on an image. When I put my cursor inside the polygon it prints "Inside" otherwise "Outside". So the detection of the points inside the polygon is working fine.
But I want to implement the effect of setToolTipText inside the polygon i.e. at the time of mouse hover inside the polygon, it will show the floating text "Inside".
Similar to the effect in this image:
http://www.java2s.com/Code/Java/Swing-JFC/WorkingwithTooltipText.htm
What are the minimal changes to be made in the following code to get the desired effect?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.image.*;
import java.awt.Graphics.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

class page1 extends JFrame implements MouseListener,MouseMotionListener ,ActionListener
{
    JFrame f;
    JLabel l;
    JPanel p1;
    ImageIcon ii;
    Image img;
    int height;
    int width;
    Container c;
    int pixels[];
    PixelGrabber pg;
    JPanel panel;
    Graphics2D gg;
    Polygon pp1=new Polygon();
    boolean startHovercurrent,startHoverprev=false;

    page1()
    {
        f=new JFrame("Sample Page");
        ii=new ImageIcon("sample.jpg");
        img=ii.getImage();
        height=ii.getIconHeight();
        width=ii.getIconWidth();
        pixels=new int[ii.getIconWidth()*ii.getIconHeight()];
        pg=new PixelGrabber(img,0,0,ii.getIconWidth(),ii.getIconHeight(),pixels,0,ii.getIconWidth());
        try
        {
            pg.grabPixels();
        }
        catch(InterruptedException k)
        {
        }

        //add points of polygon
        pp1.addPoint(300,300);
        pp1.addPoint(380,300);
        pp1.addPoint(380,220);
        pp1.addPoint(300,220);

        l=new JLabel(ii,JLabel.CENTER);
        c=f.getContentPane();
        JDesktopPane desk = new JDesktopPane();
        JInternalFrame p = new JInternalFrame("Image Frame",false, false, true, false);
        JScrollPane scroll = new JScrollPane(l);
        p.setContentPane(scroll);
        p.setBounds(0, 0, 740, 600);
        desk.add(p);
        p.setVisible(true);
        l.addMouseListener(this);
        l.addMouseMotionListener(this);

        c.add(desk, BorderLayout.CENTER);
        f.setSize(1024,738);
        f.setVisible(true);

    }

    public static void main(String args[])
    {
        new page1();
    }
    public void mouseClicked(MouseEvent me)
    {
    }
    public void mouseEntered(MouseEvent me)
    {
    }
    public void mouseExited(MouseEvent me)
    {
    }
    public void mousePressed(MouseEvent me)
    {
    }
    public void mouseReleased(MouseEvent me)
    {
    }
    public void mouseMoved(MouseEvent me)
    {
        boolean contain1;
        int mx,my;
        gg=(Graphics2D)l.getGraphics();
        gg.setColor(new Color(255,0,0) );
        gg.fillPolygon(pp1);

        mx = me.getX();
        my = me.getY();

        //check if mouse cursor is inside polygon or not
        // do not print anything if next cursor position is in same state
        contain1=pp1.contains(mx,my);
        if (contain1) {
            startHovercurrent = true;
            if(startHovercurrent!=startHoverprev)
                System.out.println("Inside");

            startHoverprev=startHovercurrent;
         }
         else {
            startHovercurrent = false;
            if(startHovercurrent!=startHoverprev)
                System.out.println("Outside");

            startHoverprev=startHovercurrent;
         }
    }
    public void mouseDragged(MouseEvent me)
    {
    }
    public void actionPerformed(ActionEvent ae)
    {
    }
}

A: For this usage, How to Use Tool Tips suggests overriding the getToolTipText() method of the enclosing JComponent. This answer outlines the approach for JMapViewer and ChartPanel. In the example below, getToolTipText() simply returns the name of any Shape that contains() the triggering mouse event. For comparison, the JLabel at window's bottom gets a conventional too tip via setToolTipText().

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.ToolTipManager;

/**
 * @see https://stackoverflow.com/a/53609066/230513
 * @see https://stackoverflow.com/a/25944439/230513
 */
public class ShapeToolTip {

    private static class ShapePanel extends JPanel {

        private final List<Shape> list = new ArrayList<>();

        public ShapePanel() {
            Polygon p = new Polygon();
            p.addPoint(500, 100);
            p.addPoint(500, 400);
            p.addPoint(200, 400);
            list.add(p);
            list.add(new Ellipse2D.Double(100, 100, 200, 200));
            ToolTipManager.sharedInstance().registerComponent(this);
        }

        @Override
        public String getToolTipText(MouseEvent e) {
            for (Shape shape : list) {
                if (shape.contains(e.getX(), e.getY())) {
                    return shape.getClass().getName();
                }
            }
            return "Outside";
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.blue);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setStroke(new BasicStroke(2));
            for (Shape shape : list) {
                g2d.draw(shape);
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(640, 480);
        }
    }

    private void display() {
        JFrame f = new JFrame("ShapeToolTip");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new ShapePanel());
        JLabel title = new JLabel("Shape Tool Tip", JLabel.CENTER);
        title.setToolTipText("Title");
        title.setFont(title.getFont().deriveFont(Font.BOLD, 24));
        f.add(title, BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new ShapeToolTip()::display);
    }
}


text:
Q: Surviving Free Fall with the Help of Mr. Bernoulli What is the best strategy to survive a free fall naked out of a jetliner at cruising altitude (ignoring temperature)?
For instance, my strategy would be to streamline my fall so that my terminal velocity was very high. Then at some critical distance above the ground I would pitch upward and attempt to use my forward velocity to achieve lift. Presumably this would slow my fall to some survivable speed. (This is roughly what the space shuttle does after all.)
Would it work? And idea if it would be survivable?

A: I would guess you've heard that an airplane in a spin or some other critical state can dive to build up speed, then when it pulls out of the dive the increased speed increases the lift and can allow the pilot to regain control. You are presumably asking if the same idea can be used for a falling person.
The problem is that an aircraft wing is carefully designed to use forward velocity to achieve lift while a human body has no surfaces that can be used in this manner. The airflow around a falling person will simply be turbulent and will cause drag but no lift. Skydivers can control their flight to some degree but this is mainly by moving the drag with respect to their centre of mass, and while this can effectively rotate them it provides little or no lift in the aeronautical sense.


text:
Q: how to parse values from this XML records I have IEnumerable<XElement> rates with the following XML/ Data in it.
<results>
  <rate id="AUDEUR">
    <Name>AUD to EUR</Name>
    <Rate>0.6602</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.6604</Ask>
    <Bid>0.66</Bid>
  </rate>
  <rate id="AUDGBP">
    <Name>AUD to GBP</Name>
    <Rate>0.5391</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.5393</Ask>
    <Bid>0.5389</Bid>
  </rate>
  <rate id="AUDUSD">
    <Name>AUD to USD</Name>
    <Rate>0.9051</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.9054</Ask>
    <Bid>0.9048</Bid>
  </rate>
  <rate id="EURAUD">
    <Name>EUR to AUD</Name>
    <Rate>1.5147</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.5153</Ask>
    <Bid>1.5141</Bid>
  </rate>
  <rate id="EURGBP">
    <Name>EUR to GBP</Name>
    <Rate>0.8166</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.8167</Ask>
    <Bid>0.8165</Bid>
  </rate>
  <rate id="EURUSD">
    <Name>EUR to USD</Name>
    <Rate>1.3709</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.371</Ask>
    <Bid>1.3709</Bid>
  </rate>
  <rate id="GBPAUD">
    <Name>GBP to AUD</Name>
    <Rate>1.8549</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.8556</Ask>
    <Bid>1.8541</Bid>
  </rate>
  <rate id="GBPEUR">
    <Name>GBP to EUR</Name>
    <Rate>1.2246</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.2247</Ask>
    <Bid>1.2244</Bid>
  </rate>
  <rate id="GBPUSD">
    <Name>GBP to USD</Name>
    <Rate>1.6788</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.679</Ask>
    <Bid>1.6787</Bid>
  </rate>
  <rate id="USDAUD">
    <Name>USD to AUD</Name>
    <Rate>1.1049</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.1052</Ask>
    <Bid>1.1045</Bid>
  </rate>
  <rate id="USDEUR">
    <Name>USD to EUR</Name>
    <Rate>0.7294</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.7295</Ask>
    <Bid>0.7294</Bid>
  </rate>
  <rate id="USDGBP">
    <Name>USD to GBP</Name>
    <Rate>0.5957</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.5957</Ask>
    <Bid>0.5956</Bid>
  </rate>
</results>
    base {System.Xml.Linq.XContainer}: <results>
  <rate id="AUDEUR">
    <Name>AUD to EUR</Name>
    <Rate>0.6602</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.6604</Ask>
    <Bid>0.66</Bid>
  </rate>
  <rate id="AUDGBP">
    <Name>AUD to GBP</Name>
    <Rate>0.5391</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.5393</Ask>
    <Bid>0.5389</Bid>
  </rate>
  <rate id="AUDUSD">
    <Name>AUD to USD</Name>
    <Rate>0.9051</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.9054</Ask>
    <Bid>0.9048</Bid>
  </rate>
  <rate id="EURAUD">
    <Name>EUR to AUD</Name>
    <Rate>1.5147</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.5153</Ask>
    <Bid>1.5141</Bid>
  </rate>
  <rate id="EURGBP">
    <Name>EUR to GBP</Name>
    <Rate>0.8166</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.8167</Ask>
    <Bid>0.8165</Bid>
  </rate>
  <rate id="EURUSD">
    <Name>EUR to USD</Name>
    <Rate>1.3709</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.371</Ask>
    <Bid>1.3709</Bid>
  </rate>
  <rate id="GBPAUD">
    <Name>GBP to AUD</Name>
    <Rate>1.8549</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.8556</Ask>
    <Bid>1.8541</Bid>
  </rate>
  <rate id="GBPEUR">
    <Name>GBP to EUR</Name>
    <Rate>1.2246</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.2247</Ask>
    <Bid>1.2244</Bid>
  </rate>
  <rate id="GBPUSD">
    <Name>GBP to USD</Name>
    <Rate>1.6788</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.679</Ask>
    <Bid>1.6787</Bid>
  </rate>
  <rate id="USDAUD">
    <Name>USD to AUD</Name>
    <Rate>1.1049</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>1.1052</Ask>
    <Bid>1.1045</Bid>
  </rate>
  <rate id="USDEUR">
    <Name>USD to EUR</Name>
    <Rate>0.7294</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.7295</Ask>
    <Bid>0.7294</Bid>
  </rate>
  <rate id="USDGBP">
    <Name>USD to GBP</Name>
    <Rate>0.5957</Rate>
    <Date>2/17/2014</Date>
    <Time>12:07am</Time>
    <Ask>0.5957</Ask>
    <Bid>0.5956</Bid>
  </rate>
</results>

Based on this data I need to add the records in DB. The following values are required to add:

*

*id from <rate id="AUDEUR">, in this case it will be AUDEUR

*Rate from <Rate>0.6602</Rate>, in this case it will be 0.6602

*Date from <Date>2/17/2014</Date>
I have not much experienced with XML, can you please help me how I can get these values ?
Thanks

A: You can use Linq2Xml
XElement doc=XElement.Load(url);
var elements=doc.Elements("rate")
                .Where(x=>
                         x.Attribute("id").Value=="AUDEUR" &&
                         (double)x.Element("Rate")>=0.6602 &&
                         DateTime.Compare((DateTime)x.Element("Date"),DateTime.Parse("2/17/2014"))>=0
                      )
                .Select(e=>
                            new
                           {
                                Id=e.Attribute("id").Value,
                                Name=e.Element("Name").Value,
                                Rate=e.Element("Rate").Value....
                           }
                       );

Now you can iterate over elements like this
foreach(var elm in elements)
{
    elm.Name;
    elm.Rate;
}

A: I would create a class to handle rates:
class Rate
{
    public string Id { get; private set; }
    public decimal Value { get; private set; }
    public DateTime Date { get; private set; }

    // let's make the class immutable
    public Rate(string id, decimal value, DateTime date)
    {
        Id = id;
        Value = value;
        Date = date;
    }
}

and use LINQ to XML to parse the XML:
private static IEnumerable<Rate> GetRates(XElement source)
{
    return from r in source.Element("results").Elements("rate")
           select new Rate(
               (string)r.Attribute("id"),
               (decimal)r.Element("rate"),
               (DateTime)r.Element("date"));
}

I'm not sure why you said you had IEnumerable<XElement>, but assuming that's what you have, you can easily get rates from IEnumerable<XElement> by:
var data = rates.SelectMany(x => GetRates(x)).ToList();

it will give you List<Rate> which you can use to update your database.

A: Let's represent a rate record like class below:
public class RateRecord {
    public string Id { get; set; }
    public string Rate { get; set; }
    public string Date { get; set; }
}

And get the list of parsed rates:
var rateRecords = new List<RateRecord>();
foreach(var rate in rates) {
    rateRecords.Add(new RateRecord {
        Id = rate.Attribute("id").Value,
        Rate = rate.Element("Rate").Value,
        Date = rate.Element("Date").Value
    });
}

Also you can write a method for parsing:
public IEnumerable<RateRecord> ParseRates(IEnumerable<XElement> rates) {
    foreach(var rate in rates) {
        yield return new RateRecord {
            Id = rate.Attribute("id").Value,
            Rate = rate.Element("Rate").Value,
            Date = rate.Element("Date").Value
        };
    }
}


text:
Q: I can't find the industrial foregoing's manual for Minecraft 1.16.4 The recipe is supposed to be 1 paper and 1 of any wood. I cannot craft it, and in creative mode I cannot find it anywhere. I even figured out a new way to make it, (1 book and 1 Redstone Dust and 1 dust block)  but I still cannot craft it.
I also cannot find it in the Just Enough Items mod.

A: Check to see if the mod is actually installed by looking at the title screen and clicking the mods button. If there is no mods button, then that means there aren't any mods installed. If there is a mods button, click it and look at the list of mods. Industrial foregoing should be on there. If it is there, then I suggest deleting the mod, reinstalling it, and putting it back in your mods folder.

A: Make sure the industrial foregoing mod is installed and active for your minecraft version. If it is still not working I see no other reason than a wrong or broken mod.

A: I solved this problem.
Use Patchouli
https://www.curseforge.com/minecraft/mc-mods/patchouli


text:
Q: Write the output of a script to a file in hive I have a script with a set of 5 queries.I would like to execute the script and write the output to a file.What command should I give from the hive cli.
Thanks

A: sample Queries file (3 queries) :
ramisetty@aspire:~/my_tmp$ cat queries.q
show databases; --query1
use my_db;  --query2
INSERT OVERWRITE LOCAL DIRECTORY './outputLocalDir' --query3
select * from students where branch = "ECE";        --query3

Run HIVE:
ramisetty@aspire:~/my_tmp$ hive
hive (default)> source ./queries.q;
--output of Q1 on console-----

Time taken: 7.689 seconds

--output of Q2 on console -----

 Time taken: 1.689 seconds
____________________________________________________________
Total MapReduce jobs = 1
Launching Job 1 out of 1
Number of reduce tasks is set to 0 since there's no reduce operator
Starting Job = job_201401251835_0004, Tracking URL = http://localhost:50030/jobdetails.jsp?jobid=job_201401251835_0004
Kill Command = /home/ramisetty/VJDATA/hadoop-1.0.4/libexec/../bin/hadoop job  -kill job_201401251835_0004
Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 0
2014-01-25 19:06:56,689 Stage-1 map = 0%,  reduce = 0%
2014-01-25 19:07:05,868 Stage-1 map = 100%,  reduce = 0%, Cumulative CPU 2.07 sec
2014-01-25 19:07:14,047 Stage-1 map = 100%,  reduce = 0%, Cumulative CPU 2.07 sec
2014-01-25 19:07:15,059 Stage-1 map = 100%,  reduce = 100%, Cumulative CPU 2.07 sec
MapReduce Total cumulative CPU time: 2 seconds 70 msec
Ended Job = job_201401251835_0004
**Copying data to local directory outputLocalDir
Copying data to local directory outputLocalDir**
2 Rows loaded to outputLocalDir
MapReduce Jobs Launched:
Job 0: Map: 1   Cumulative CPU: 2.07 sec   HDFS Read: 525 HDFS Write: 66 SUCCESS
Total MapReduce CPU Time Spent: 2 seconds 70 msec
OK
firstname   secondname  dob score   branch
Time taken: 32.44 seconds

output file :
cat ./outputLocalDir/000000_0


text:
Q: COUNT QUERY IN DB2 In mainframe DB2, i have two tables TAB 1 and TAB 2. I have records in those tables like:
TAB 1:
AP_NBR  LOC_NBR
1000    1
1000    2
1000    3

TAB 2:
LOC_NBR ITM_ID
1   500
1   600
2   450
2   750

Her i need an output like below:
AP_NBR  COUNT(LOC_NBR)  COUNT(ITM_ID)
1000    3                     4

How to write COUNT query for this?
Can anyone please help me on this?

A: select t1.AP_NBR, count(distinct t1.LOC_NBR), count(distinct t2.ITM_ID)
from TAB1 t1 join TAB2 t2 on t1.LOC_NBR = t2.LOC_NBR
group by t1.AP_NBR

A: try this:
select * from
(select AP_NBR,COUNT(*) cnt_LOC_NBR from TAB1 group by AP_NBR)a,
(select COUNT(*) cnt_ITM_ID from TAB2 where LOC_NBR in
(select LOC_NBR from TAB1))b


text:
Q: Why setter and getter methods
Possible Duplicate:
Why use getters and setters?

I know this is very trivial. But why do we define private and then we use getter and setters. Is this more like for preventing the programmers from making mistakes on using private variables or methods? Or is it for security reasons. If for security reasons then what is the point of having getters or setters? I know that we can have restrictions inside getter and setter but those if clauses are mostly for preventing the mistakes not the privacy restrictions. E.g. we don't usually say for these members limit the access to this method with an if clause.
Thanks.

A: If one allows variables from a class to be edited by anyone, then Very Bad Things can happen.  (for instance, if an unwary user changes a denominator to zero, we could destroy the universe [or get a divide by zero error]).  Defining get() and set() methods allow you (the programmer) to define exactly how others can interact with your variables.

A: The practice of automatically, unthinkingly creating getX() and setX() methods for every variable is bad. It's mostly pointless, as you have observed.
But it's the unthinking part that's bad. Methods are infinitely better than exposed variables because, again, as you observed, you can control how the underlying data is accessed. If you think about what you're doing, and apply mutators and accessors as appropriate, they're a wonderful tool:

*

*You can restrict clients to only reading, but not writing to a variable.

*You can restrict the values of an integer to only positive values (for example).

*You can ensure that one variable is always equal to one-half the value of another (for example).

*You can ensure that, any time the value of a variable is changed, an event is sent to notify other clients.

*You can change the data type of an underlying variable, perform conversions in the public methods, and not break any clients.

*You can convert an object to a remote client for a server-side version of the same object, and again, the client code won't change.

*You can ensure strict memory ordering across threads by using synchronized accessors.

These are only some of the things you can do with mutators and accessors. By using them, you make your software easy to change and easy to maintain.

A: We use private fields and have getters and setters so those private fields can be accessed by other classes.  If I have two classes in a project, say Car.java and Driver.java, we want Driver objects to be able to access the private field "wheel" in Car.java (or else the Driver cannot drive the car).  But if the field is private, it can only be accessed with a getter method that returns the value of the field.  Setters allow outside classes to alter the values of fields.  You can avoid using getters and setters by making your fields public (or protected, where appropriate) instead of private.

A: it allows you to control access to things.....  by encapsulating access to a piece of data, you are free to change where that data lives, or even you may make it computable.  ie, rather than returning a value of a field, you do some calculation.
But,  as good as getters and setters are, if you use them too much, then its a sign you aren't getting a object to do the work you need it to.

A: There are one more benefit, if you use the getters and setters, it allows a subclass to override how to access the information with a method and more flexibility.

A: With the help of an example let me explain the point. Suppose we have the following class:
class User {
    private String username;
    private String password;
}

Now in a team project where multiple programmers are working. Programmer A has developed the User class and programmer B has to work on the GUI interface. The policy decided is that the password field cannot be less than 5 characters. But unless you have not made the data fields private both A and B have to always check the validity of the new password being assigned to the password field.
Now suppose after making them private you implement the following setter method:
public boolean setPassword( String temp ) {
    if( temp.length() >= 5 ) {
        this.password = temp;
        return true;
    }
    else {
        return false;
    }
}

This way only A has to code it once and B has to just use it without worrying about the policy. This always encourages the DRY (Don't repeat yourself) rule.

A: Setter amd Getter Method basically used to restrict to make any changes by the other person. In Java language we are providing Data Hiding concept. This is achieved due to get and set method.


text:
Q: Синхронизация пакетов в проектах - NetBeans. Существуют две программы. Сервер - под комп, и клиент игры на андроиде. Проекты в нетбинсе. В каждом проекте есть пакет - server или client, в которых содержатся классы, необходимые только клиенту/серверу, и + в каждом проекте есть пакет common, который содержит классы общие (идентичные для обоих проектов). Вопрос: как синхронизировать эти пакеты? Возможно, стоит вывести эти классы в библиотеку?
A: Непонятно, а зачем синхронизировать? И главное что синхронизировать? Объектные коды? Так они для сервера и клиента все равно разные. Серверные коды работают под стандартный JVM, а телефонные под Dalvik VM - они на уровне байткодов все равно несовместимы.
Так что имеет смысл разве что синхронизировать исходники: заведите исходники под контроль версий и пропишите статическую функцию в серверной и клиентской части которая возвращает текущую версию. При запуске можно в рантайме проверять версии сервера и клиента и в случае необходимости писать нечто интеллектуальное типа: "устаревшая версия"...
Update
А что разве Netbeans разучился собирать несколько проектов из одного дерева исходников? В общем загоните все исходники под 3 каталога, скажем: src/server, src/common, src/client. Далее создаете проект для сервера в качестве исходников используете каталоги src/server и src/common. Аналогично проект для клиента: src/common и src/client


text:
Q: How can I only allow up to one year from today's date to be selected from datepicker? Right now I have my calendar working and set up so that paste dates are disabled according from today's date. How can I also disable dates after 365 days from the current date?
fiddle: https://jsfiddle.net/ts8acmow/1/
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
 if(dd<10){
        dd='0'+dd
    }
    if(mm<10){
        mm='0'+mm
    }

today = yyyy+'-'+mm+'-'+dd;
document.getElementById("start").setAttribute("min", today);

A: It is really the same principle, but for the max attribute.
Here is how you could do it:

function fmt(dt) {
    return dt.toLocaleDateString("se"); // shortcut: Sweden locale has YYYY-MM-DD format
}

var today365 = new Date();
today365.setDate(today365.getDate()+365);

var start = document.getElementById("start");
start.setAttribute("min", fmt(new Date()));
start.setAttribute("max", fmt(today365));
<input type="date" id="start">


text:
Q: Nested quotes not working in HTML I'm trying to use the card validator (Twitter validator) in twitter. I have my code in the variable called content all my other code is working, but the twitter meta tags. I have the quotes of the tags like \" but when I do this the twitter validator doesn't show my card properly.
If I remove the \ then the rest of my code doesn't work properly. Is there a way to escape the quote so that the twitter card validator will accept it and read the meta tags.
HTML code:

        Image link: <input type="text" id="img">
        Content: <input type="text" id="content">
        <button onclick="makePage()">click</button>

Javascript code. The html is in the content variable.
function makePage(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState==4 && xmlhttp.status==200)
        alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = '<meta name="twitter:card" content="summary_large_image"><meta name="twitter:site" content="@nytimes"><meta name="twitter:creator" content="@SarahMaslinNir"><meta name="twitter:title" content="Parade of Fans for Houston's Funeral"><meta name="twitter:description" content="NEWARK - The guest list and parade of limousines with celebrities emerging from them seemed more suited to a red carpet event in Hollywood or New York than than a gritty stretch of Sussex Avenue near the former site of the James M. Baxter Terrace public housing project here."><meta name="twitter:image" content="">';
xmlhttp.open("GET","makePage.php?content=" + content,true);
xmlhttp.send();}

My PHP code (I'm dynamically making pages):
<?php
    $content = $_GET["content"];
    $file = "" . uniqid() . ".html";
    file_put_contents($file, $content);
    echo $file;
?>

The error the Twitter validator is giving:
INFO:  Page fetched successfully

INFO:  8 metatags were found

WARN:  Not whitelisted

I know that it says 'Not whitelisted', but my website is white listed (it works on the main page). I'm sure this is being caused due to the nested quotes.

A: You need to URL Encode your query string content so the xmlhttp.open should be:
var content = '<meta name="twitter:card" content="summary_large_image"><meta name="twitter:site" content="@nytimes"><meta name="twitter:creator" content="@SarahMaslinNir"><meta name="twitter:title" content="Parade of Fans for Houston's Funeral"><meta name="twitter:description" content="NEWARK - The guest list and parade of limousines with celebrities emerging from them seemed more suited to a red carpet event in Hollywood or New York than than a gritty stretch of Sussex Avenue near the former site of the James M. Baxter Terrace public housing project here."><meta name="twitter:image" content="">';
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://www.michelem.org/ddd.php?content=" + encodeURIComponent(content), true);
xmlhttp.send();