text:
Q: globalhost and localhost server simultaneously i m running a website from a global webserver and a wants to store a data from a form to my localhost (like wamp) too........ is it possible.....

A: Use cookie.

A: You will need to explain a lot more if you want anyone to be able to help you.
What is a "global webserver"? What kind of site or web application are you running on it? What does your form do? What data do you want to save? And what do you want to do with it?
To get you started, here's some advice on how to ask questions in technical forums. It's a bit long, and somewhat harsh, but still recommended reading.
http://catb.org/esr/faqs/smart-questions.html


text:
Q: How to use FlycoPageIndicator in AndroidFragment? Currently am trying to make an app introduction with Fragments, I successfully created it. Here is the screenshot of the fragment app introduction and I didn't uploaded all the 3 screenshots:
My app
First question: How to implement flycopageIndicator in it like this:
PageIndicator
Is there any other easy way to do it?
Second Question: I saw in some app that when I swipe the fragment the next is converted to finish how to do that?
Third Question: I want to blur the image of my app. I know its possible in Java, but how in my code?
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private FlycoPageIndicaor mFlycoPageIndicaor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), "ONE");
    adapter.addFragment(new TwoFragment(), "TWO");
    adapter.addFragment(new ThreeFragment(), "THREE");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager)
    {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

}
}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            xmlns:tools="http://schemas.android.com/tools"
            android:background="@color/primary"
            android:orientation="vertical"

            tools:context="com.example.vishal.myapplication.MainActivity">

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
                                   android:id="@+id/viewpager"
                                   android:layout_width="fill_parent"
                                   android:layout_height="fill_parent"
                                   android:layout_alignParentBottom="true"></android.support.v4.view.ViewPager>

<LinearLayout
    android:id="@+id/linearLayoutAppInfoButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_weight="0.1"
    android:gravity="center"
    android:orientation="horizontal"
    android:weightSum="1">

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="@android:color/transparent" />

    <Button
        android:id="@+id/btnGuest"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:background="@android:color/transparent"
        android:paddingBottom="5dp"
        android:paddingTop="5dp"
        android:text="Login"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/white"
        android:textStyle="normal" />
</LinearLayout>

OneFragment.java
public class OneFragment extends android.support.v4.app.Fragment {

public void OneFragment(){

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.one_fragment, container, false);
}}

one_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/one_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.vishal.myapplication.OneFragment">

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:textColor="@color/white"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="232dp"
    android:id="@+id/textView3"/>

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/image1"
    android:scaleType="centerCrop"
    android:layout_toStartOf="@+id/textView3"
    android:id="@+id/imageView2"
    android:layout_alignParentEnd="true"/>

TwoFragment.java and ThreeFragment.java have same code as OneFragment.java
two_fragment.xml and three_fragment.xml have same code as one_fragment.xml with different drawable images

redpajama_set_name: RedPajamaStackExchange


text:
Q: rsync OpenIndiana repository on local server I was looking for a repository from OpenIndiana but everything what I found is this: http://wiki.openindiana.org/oi/Making+a+LAN+mirror+of+global+package+repositories.
I would like to sync OpenIndiana repo on a local server. How can I sync it?
For example, for CentOS 7 I use something like this:
 rsync rsync://ftp.nluug.nl/centoslinux/7/ /mnt/mirrors/stage/centos/7/ /mnt/bin/centos7.exclude

Can I do something like this for OpenIndiana too?

A: It's in the link you provided:
rsync the package repository contents and/or updates
The whole repository can be updated (or even fetched right away, skipping the downloadable tarballs part) from the origin servers, but note that your repository would then include revisions for many releases of OpenIndiana (147-151a4 as of now) and take over 8GB of disk in size.
:; rsync -zavPHK pkg-origin.openindiana.org::pkgdepot-dev /export/pkg/dev/

Source


text:
Q: Error Can't use pyhive to connect to Hive Database This is the code  use to connect to our hive database , it ran fine a week back but now it seems to be be failing to even open a session and get a cursor to execute the queries. The issue was temporarily fixed when i explicitly added a cursor.close() method but now it's back again. I am unable to access the hive database using python
I have tried using pyhs2 and pyhive both the libraries fail to connect to the hive database. Nothing on the cluster has changed so far. what could the reason for this be ?
I know Hive is not a relational DB so the concept of cursors doesn't make sense but Is there any way the the Hive database remembers the cursors created using the pyhive library ?? if so how can i delete the currently unused cursors ??
Here is the code and exception it raises upon execution
from pyhive import hive
import contextlib

class Hive():
    def __init__(self,host="[hostnamehere]",db="default",port="10000",auth="KERBEROS",kerberos_service_name="hive"):
        self.host = host
        self.db = db
        self.port = port
        self.auth = auth
        self.kerberos_service_name = kerberos_service_name

    def connect(self):
        return(hive.connect(host=self.host, port=self.port, database=self.db, auth=self.auth, kerberos_service_name=self.kerberos_service_name))

    def query_one(self,sql):
        with contextlib.closing(self.connect()) as connection:
            with contextlib.closing(connection.cursor()) as cursor:
                cursor.execute(sql)
                result = cursor.fetch_one()
                cursor.close()
        return(result)

if __name__ == "__main__":
    connector = Hive()
    print("running query")
    print(connector.query_one("SELECT * FROM [tablenamehere]"))

    raise OperationalError(response)
pyhive.exc.OperationalError: TOpenSessionResp(status=TStatus(statusCode=3, infoMessages=['*org.apache.hive.service.cli.HiveSQLException:Failed to open new session: java.lang.RuntimeException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient:13:12', 'org.apache.hive.service.cli.session.SessionManager:openSession:SessionManager.java:289', 'org.apache.hive.service.cli.CLIService:openSession:CLIService.java:199', 'org.apache.hive.service.cli.thrift.ThriftCLIService:getSessionHandle:ThriftCLIService.java:427', 'org.apache.hive.service.cli.thrift.ThriftCLIService:OpenSession:ThriftCLIService.java:319', 'org.apache.hive.service.cli.thrift.TCLIService$Processor$OpenSession:getResult:TCLIService.java:1257', 'org.apache.hive.service.cli.thrift.TCLIService$Processor$OpenSession:getResult:TCLIService.java:1242', 'org.apache.thrift.ProcessFunction:process:ProcessFunction.java:39', 'org.apache.thrift.TBaseProcessor:process:TBaseProcessor.java:39', 'org.apache.hadoop.hive.thrift.HadoopThriftAuthBridge$Server$TUGIAssumingProcessor:process:HadoopThriftAuthBridge.java:562', 'org.apache.thrift.server.TThreadPoolServer$WorkerProcess:run:TThreadPoolServer.java:286', 'java.util.concurrent.ThreadPoolExecutor:runWorker:ThreadPoolExecutor.java:1149', 'java.util.concurrent.ThreadPoolExecutor$Worker:run:ThreadPoolExecutor.java:624', 'java.lang.Thread:run:Thread.java:748', '*java.lang.RuntimeException:java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient:15:2', 'org.apache.hadoop.hive.ql.session.SessionState:start:SessionState.java:547', 'org.apache.hive.service.cli.session.HiveSessionImpl:open:HiveSessionImpl.java:144', 'org.apache.hive.service.cli.session.SessionManager:openSession:SessionManager.java:281', '*java.lang.RuntimeException:Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient:21:6', 'org.apache.hadoop.hive.metastore.MetaStoreUtils:newInstance:MetaStoreUtils.java:1566', 'org.apache.hadoop.hive.metastore.RetryingMetaStoreClient::RetryingMetaStoreClient.java:92', 'org.apache.hadoop.hive.metastore.RetryingMetaStoreClient:getProxy:RetryingMetaStoreClient.java:138', 'org.apache.hadoop.hive.metastore.RetryingMetaStoreClient:getProxy:RetryingMetaStoreClient.java:110', 'org.apache.hadoop.hive.ql.metadata.Hive:createMetaStoreClient:Hive.java:3510', 'org.apache.hadoop.hive.ql.metadata.Hive:getMSC:Hive.java:3542', 'org.apache.hadoop.hive.ql.session.SessionState:start:SessionState.java:528', '*java.lang.reflect.InvocationTargetException:null:25:4', 'sun.reflect.NativeConstructorAccessorImpl:newInstance0:NativeConstructorAccessorImpl.java:-2', 'sun.reflect.NativeConstructorAccessorImpl:newInstance:NativeConstructorAccessorImpl.java:62', 'sun.reflect.DelegatingConstructorAccessorImpl:newInstance:DelegatingConstructorAccessorImpl.java:45', 'java.lang.reflect.Constructor:newInstance:Constructor.java:423', 'org.apache.hadoop.hive.metastore.MetaStoreUtils:newInstance:MetaStoreUtils.java:1564', '*org.apache.hadoop.hive.metastore.api.MetaException:GC overhead limit exceeded:30:4', 'org.apache.hadoop.hive.metastore.RetryingHMSHandler::RetryingHMSHandler.java:82', 'org.apache.hadoop.hive.metastore.RetryingHMSHandler:getProxy:RetryingHMSHandler.java:91', 'org.apache.hadoop.hive.metastore.HiveMetaStore:newRetryingHMSHandler:HiveMetaStore.java:6463', 'org.apache.hadoop.hive.metastore.HiveMetaStoreClient::HiveMetaStoreClient.java:206', 'org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient::SessionHiveMetaStoreClient.java:76', '*java.lang.OutOfMemoryError:GC overhead limit exceeded:0:-1'], sqlState=None, errorCode=0, errorMessage='Failed to open new session: java.lang.RuntimeException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient'), serverProtocolVersion=7, sessionHandle=None, configuration=None)


text:
Q: Spring Security in GWT I tried spring security with GWT, its redirecting to login perfectly.
I stopped the server and started again and tried to access the URL.
Application doesn't show the login page. It directly going to home page.
Is this how the security works, how to make it work. User name, password and roles are configured in spring configuration files.
web.xml
<!-- web.xml -->

<web-app>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/gwtsecuritydemo-security.xml
            /WEB-INF/gwtsecuritydemo-base.xml
        </param-value>
    </context-param>

    <!-- Spring Security Filter Chain -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

    <!-- Servlets -->
    <servlet>
        <servlet-name>greetServlet</servlet-name>
        <servlet-class>au.com.securitydemo.gwt.maven.sample.server.GreetingServiceImpl</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>greetServlet</servlet-name>
        <url-pattern>/gwtsecuritydemo/greet</url-pattern>
    </servlet-mapping>

    <!-- Default page to serve -->
    <welcome-file-list>
        <welcome-file>gwtsecuritydemo.html</welcome-file>
    </welcome-file-list>

</web-app>

and
spring configuration.
<!-- Spring Config -->

<http auto-config="true">
    <intercept-url pattern="/*" access="ROLE_USER" />
</http>

<authentication-manager alias="authenticationManager">
    <authentication-provider>
        <user-service>
            <user authorities="ROLE_USER" name="guest" password="guest" />
        </user-service>
    </authentication-provider>
</authentication-manager>

Thanks,
Bennet.

A: You server preserved sessions during restart or you configured "remember-me cookie".
To be sure, remove relevant cookies (usually JSESSIONID and REMEMBER_ME) from your browser and reload the page.


text:
Q: SEARCH and FETCH IMAP Command I am developing a application to read email using IMAP protocol from my email server (Not google)
below are the sample codes. I am connecting to the server using TCPclient and now stuck on writing IMAP command
First
    c SEARCH NOT SEEN

SEARCH NOT SEEN does not actually retrieve the email which is not read. I just open my outlook and update my folder, it will update all mail to SEEN. How can I get the UID of email which is not read.
Second
    d FETCH 50 BODY.PEEK[HEADER.FIELDS (From To Subject)]

I am able to fetch the "FROM TO SUBJECT" of the email with UID 50. However, how can I retrieve the body of the email.

A: Use UID SEARCH, SEARCH returns seqnos, not uids, UID SEARCH returns UIDs.


text:
Q: Не работает phpthumbof Почему у меня при выводе [[+img:phpthumbof=w=300&h=300&zc=1]] выдает unknown
Вывожу поля через migx, без фильтра все окей, добавляю фильтр ":phpthumbof=`w=300&h=300&zc=1" перестает работать.

A: Проблема была в том, что я использовал вывод здесь

[[getImageList? &tvname=object-gallery-photo &tpl=@CODE:

   &docid=[[*id]]
  &limit=10 ]]

А создав чанк и уже там применив фильтр все получилось. Видимо в phpThumbOf нет возможности использовать в данном виде.


text:
Q: How does a vector buffer work? I am trying to code a type of buffer and I tried to find the source code of the buffer function in the ArcGIS and QGIS files in order to understand how it works in depth when it comes to creating buffer around a complex polygons. I would like to know how the vertex are generated and how the arcs close to the edge are created for optimal coverage.
If anyone has in depth knowledge of the source code of a buffer tool without too many external references to other functions, that would greatly help.

A: JTS probably has nice code in https://sourceforge.net/p/jts-topo-suite/code/HEAD/tree/trunk/jts/java/src/com/vividsolutions/jts/operation/buffer/
GEOS is a C port of JTS:
https://github.com/libgeos/geos/tree/main/src/operation/buffer
Most other open tools are build upon these. PostGIS and Shapely for example both use GEOS in the background.
QGIS also seems to be based on GEOS, at least https://github.com/qgis/QGIS/blob/master/src/core/geometry/qgsgeometry.h and https://github.com/qgis/QGIS/blob/master/src/core/geometry/qgsgeometry.cpp look like that to me.


text:
Q: conditionally dropping rows from a pandas dataframe I'm trying to conditionally drop rows of from a pandas dataframe and running into trouble. For example, I want to drop the second and third rows from the dataframe in the example below.
import pandas as pd

df = pd.DataFrame([
    [12, 10, 7, 0],
    [11, 0, 0, 3],
    [0, 0, 0, 0],
    [0, 6, 7, 5],
    [4, 11, 3,4],
    [5, 2, 5, 0]],
    columns=["num1", "num2","num3","num3"])

I've tried:
df.loc[~(df['num2','num3']==0).all(axis=1)]

but get the error "TypeError: only integer scalar arrays can be converted to a scalar index"
I've also tried this per a suggestion below and gotten unexpected output:

A: Try
df.loc[(df['num2']!=0) & (df['num2']!=0)]

A: Use ne with all as:
df = df.loc[df[['num2','num3']].ne(0).all(axis=1)]
print(df)
   num1  num2  num3  num4
0    12    10     7     0
3     0     6     7     5
4     4    11     3     4
5     5     2     5     0

Here is the screenshot of my execution:


text:
Q: Email System in PHP using PHPMailer Hi i am currently implementing an email system for a customer in php. I'm having a bit of trouble in figuring out something. Here's a sample code:
   $mail = new PHPMailer();  // create a new object
   $mail->IsSMTP(); // enable SMTP
   $mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
   $mail->SMTPAuth = true;  // authentication enabled
   $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
   $mail->Host = 'smtp.gmail.com';
   $mail->Port = 465;
   $mail->Username = "***missing part***";
   $mail->Password = "***missing part***";
   $mail->SetFrom($from, $from_name);
   $mail->Subject = $subject;
   $mail->Body = $body;
   $mail->AddAddress($to);

My customer already created a business email account on gmail for this website. My question is should i put this business email and password in these missing parts? Anyone could help me please? Thanks.

A:
whose username and password should i put there?

If you want to use GMail, you need to put in the username and password that belong to the GMail account you want to send the message from.
.... which is why sending E-Mail through GMail is a bit of an imperfect solution IMO - you put your personal Google login data, with which you can access everything you do on Google, into a script on a server. It's not great practice security-wise.
It might be more feasible to create a SMTP account on the client's web site, and use that. That has the additional advantage that you can use a email@clients-domain-name.com sender address.

A: you must post the username and password so we can help you.. LOL, just kidding. You should put there the username and password of the account that would be sending the email. In this case, probably your webpage's gmail account.

A: Often web hosts don't use authentication for their web servers to send email using their smtp servers, i would suggest contacting the people who host the website and ask them about using their smtp servers.
Using gmail (if you can from a script) might end up with the rather annoying reply thing that you get from gmail where the reply address is a gmail account.
e.g. from mrKoz@gmail.com on behalf of mr@koz.com which doesn't look awesome :)


text:
Q: Prove that $H=\{i,(12),(34),(12)(34)\}$ forms a non-cyclic subgroup of $S_4$.
We have to prove  that $H=\{i,(12),(34),(12)(34)\}$ forms a non-cyclic
  subgroup of $S_4$.

It is seen that there is no element of order $4$ in $H$. So,  $H$ is non-cyclic. But How can I show $H$ is a subgroup of $G$. Is there any shortcut method?

A: Labeling, $a=(12)$, $b=(34)$. You have $a$ and $b$ commute ($ab=ba$) and $a^2=b^2=i$. From the previous facts, it's not difficult to see that $H=\{i,a,b,ab\}$ is closed under the group operation, so it is a subgroup. In fact $H$ is isomorphic to $\mathbb{Z}/2\mathbb{Z}\times\mathbb{Z}/2\mathbb{Z}$ by the map given by $a\mapsto (1,0)$ and $b\mapsto (0,1)$.

A: Yes. It's enough to show it is closed (it is almost obvious here), since $H$ is finite; see here.


text:
Q: v4 material ui autocomplete is not resting value? I have the following advanced autocomplete logic in the past I used key to re render the whole component after submitting a form that is located else where any idea how to rest it the proper way ? my problem is I need to find a way to connect a value in to it a value that is connected to state some how and when my form will submit and the value will rest, (rest value will be triggered during submitting) so the autocomplete value will rest as well any idea how to integrate value using state in to this logic ?

const options = [{name : 'some option' , optionType : 'some type', tool : 'some tool'}, ...]

<Autocomplete
      id='advancedselect'
      ref={refAutocomplete}
      options={options.sort((a, b) => -b.optionType.localeCompare(a.optionType))}
      groupBy={(option: any) => option.optionType}
      getOptionLabel={(option) => option.name}
      renderOption={(option) => (
        <React.Fragment>
          <div style={{ width: '12vw', maxWidth: 75, marginRight: 10, padding: 0 }}>
            <IconsOption img={option.tool} />
          </div>
          {option.name}
        </React.Fragment>
      )}
      //value={val}
      //onChange={(event) => setVal(event.currentTarget)}
      //getOptionSelected={(option, value) => option.name === value.name}
      PaperComponent={({ children }) => <Paper className={classes.backDrop}>{children}</Paper>}
      PopperComponent={(props: any) => <Popper open={open.open} anchorEl={open.anchorEl} {...props} className={classes.popper} placement='bottom'></Popper>}
      onClose={() => setOpen({ /*anchorEl: null,*/ ...open, open: false })}
      onOpen={(event: any) => {
        const { currentTarget } = event;
        setOpen({
          anchorEl: currentTarget,
          open: true,
        });
      }}
      onInputChange={handleAutoComplete}
      className={classes.root}
      renderInput={(params) => (
        <TextField
          name='field'
          error={err.exercise ? true : false}
          onChange={handleTextField}
          {...params}
          InputLabelProps={{ shrink: false }}
          label={!text.length && !selected.stateOptions? `Selectd Opitons !!` : ' '}
          onBlur={restTextOnBlurCond}
          autoComplete='off'
        />
      )}
    />


text:
Q: How can i manipulate the page while it is rendering? I want to change some elements text when page is leaving the server (page_render, endRequest etc.).
How can i get access to the page and how can i find the elements to change their values, texts?

A: You can do so by using a HttpModule. This sits in the pipeline and can do pre- and postprocessing.
For example take a look at this whitespaceremover.

A: Besides HttpModules, you can also override the 'Render' method (or do this in a basepage to make it reusable).
protected override void Render(HtmlTextWriter writer )
{
    StringWriter stringWriter = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

    base.Render(htmlWriter);

    string html = stringWriter.ToString();

    // do stuff with the html

    writer.Write(html);
}

A: There are a number of options and which one suites you will depend largely on what the actual goal is.

*

*Handle the PreRender event of a Page and adjust any elements you want to in this event. Ideally you would put this in a base class that is inherited by all the pages that require this processing. This gives you access to the actual page model and control tree.

*Setup a filter that will give you direct access to the response stream. You can implement this in 2 ways, either as a separate HttpModule that installs the filter or you can install the filter directly from the Global.asax. Which route you choose depends on how reusable you need this, with the HttpModule being the most reusable.

Here is a nice article Modifying the HTTP Response Using Filters


text:
Q: "After all 7 8 9" joke? I know that it is very important to be aware of "hidden meanings" of words and phrases. (Especially if the meaning is sexual.) That is why I love Stephen Colbert's "The Word" segments and usually spend some time to "decipher" all the puns
But I am really stuck with the recent one. Particularly I cannot understand the "After all 7 8 9" line here. From the reaction of the audience I can tell that it is something pretty funny.  And from the context I feel that it is something pretty dirty...
I really don't want to be misunderstood by saying bunch of numbers. So can someone explain what is going on here, so I can avoid that?

A: read it as

Seven ate Nine

:)


text:
Q: problems while reading with pyserial So I'm trying to communicate with with a zigbee module connected to a serial port by using AT (sometimes refered as Hayes) commands.
My problem is I can't figure out how to correctly read its answers with the pyserial module of Python (I'm using Python 2.7 on an embedded device).
Sometime the script manage to perfectly read the module's responses and sometimes it just returns a suite of 'A' characters.
Here is a sample output :

Opening serial /dev/ttyS2 ...
  /dev/ttyS2 is open...
Enter command or 'exit' : AT
------------- Response -------------
AT
  OK
Enter command or 'exit' : ATI
------------- Response -------------
   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaAaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Enter command or 'exit' :

I really don't understand what's happening here but I think it's probably because I use the pyserial module incorrectly. I've already tried to use the inWaiting() command to read only the bytes contained in the input buffer but this function always returns zero and the readline() command don't seems to work either so I just read packets of 1024 bytes.
Here's the code I've written so far :
import serial, time, os

def sendAtCommand(command):

    # responseArray = []
    # i = 0

    try:
        # print('Number of bytes waiting in input buffer before write : '+str(ser.inWaiting())) -> always zero...

        if ser.inWaiting():
            # flush input buffer, discarding all its contents
            print('flushing input buffer ...')
            ser.flushInput()
            # flush output buffer, aborting current output
            # ser.flushOutput()

        try:
            ser.write(command.encode('ascii')+'\r')
            #ser.write(command+'\r')
            #time.sleep(5)
        except SerialTimeoutException as e:
            print(repr(e))

        response = ser.read(size=1024)
        # print('Number of bytes waiting in input buffer after write : '+str(ser.inWaiting())) -> always zero
        # while ser.inWaiting():
            # print('Reading response ... '+str(i))
            # responseArray.append(ser.readline(eol='\r\n'))
            # i += 1
            # time.sleep(0.2)

        print('------------------------------------')
        print('------------- Response -------------')
        print('------------------------------------')
        print(response)
        # for line in responseArray:
            # print(line)
        print('------------------------------------')

        time.sleep(1)

    except KeyboardInterrupt as e:
        print('Closing serial '+port+' before interrupting ...')
        ser.close()
        exit()

VERSION = '0.02'
firstStart = True

port = '/dev/ttyS2'
baudrate = 19200
bytesize = 8
parity = 'N'
stopbits = 1
timeout = 1
xonxoff = False
rtscts = False
dsrdtr = False
write_timeout = None
inter_byte_timeout = None

try:
    os.system('cls' if os.name == 'nt' else 'clear')
    print('')
    print('PySerial version : '+serial.VERSION)
    firstStart = False

    print('')
    print('Opening serial '+port+' ...')
    ser = serial.Serial(port, baudrate, bytesize, parity, stopbits, timeout,
    xonxoff, rtscts, write_timeout, dsrdtr, inter_byte_timeout)
except ValueError as e:
    print(repr(e))
except SerialException as e:
    print(repr(e))

if ser.isOpen():
    print(ser.name + ' is open...')
    print('')

while True:

    try:
        cmd = raw_input('Enter command or \'exit\' : ')

        if cmd == 'exit':
            ser.close()
            exit()
        else:
            sendAtCommand(cmd)
    except KeyboardInterrupt as e:
        print('Closing serial '+port+' before interrupting ...')
        ser.close()
        exit()

A: Ok so first, thank you all for your answers. Finally I've figured out how to resolve this issue.
I don't know why but the problem was that I powered the telegesis zigbee board by using it's UART vcc pin (connected to the Linkit 7688 3v3 pin).
Now, I just connect the GND, Tx and Rx of both board and use an external source for power and it works perfectly. Please refer to the picture below if you have the same issue with the same material.
Don't use the VCC pin boxed in red, you must power the board using an external power source through the x2 socket.
(Sorry all for the poor quality of my english)

EDIT :
Ah and now I don't read random packets of 1024 bytes anymore, I use a separate thread for this as you can see below :
class readSerial(Thread):
    """This thread waits for data in the serial input buffer"""
    """This is a new subclass of the Thread class (cf. Python 2.4+ threading module"""

    def __init__(self, serialObject):
        """Overrides the __init__(self [,args]) method to add additional arguments"""
        Thread.__init__(self)
        self.serialObject = serialObject
        self.daemon = True
        self.start()

    def run(self):

        ser = self.serialObject

        data = ''

        ser.reset_input_buffer()
        ser.reset_output_buffer()

        while True:
            try:
                if ser.in_waiting > 0:
                    data = ser.read(ser.in_waiting)

                    print('msg received : ')
                    print('')
                    print(data.decode('ascii'))

                if 'UCAST' in data.decode('ascii'):
                    zigbeeRequest(data.decode('ascii')[26:], ser)

                    ser.reset_input_buffer()

                    data = ''
                if 'BCAST' in data.decode('ascii'):
                    zigbeeRequest(data.decode('ascii')[26:], ser)

                    ser.reset_input_buffer()

                    data = ''

                time.sleep(1)
            except Exception as e:
                print(repr(e))

Then just put
readThread = readSerial(ser)

in your main programm after you have opened your serial connection.
I hope this can be useful for someone even if I know well it isn't perfect programming (don't catch exceptions like I do...)


text:
Q: MySQL и заглавная "И" Работаю с MySQL таблицей, для всей таблицы при создании указано CHARACTER SET=utf8mb4 COLLATE=utf8mb4_bin. Кириллица обрабатывается вся успешно, за исключением заглавной "И".
mysql> select count(*) from bashorg where rstr="Гы";
+----------+
| count(*) |
+----------+
|        1 |
+----------+
1 row in set (0,00 sec)

mysql> select count(*) from bashorg where rstr="Иа";
ERROR 1267 (HY000): Illegal mix of collations (utf8mb4_bin,IMPLICIT) and (cp1251_general_ci,COERCIBLE) for operation '='
mysql> select count(*) from bashorg where rstr="И";
ERROR 1267 (HY000): Illegal mix of collations (utf8mb4_bin,IMPLICIT) and (cp1251_general_ci,COERCIBLE) for operation '='

Откуда такая дискриминаия в отношении одной бувы "И"?

A: Оказалось, что на сервере установлена кодировка соединений "cp1251".
Для исправления ошибки можно либо изменить конфигурацию сервера, либо в начале каждой сессии выполнять
set character set utf8mb4;


text:
Q: New to MATLAB, having some trouble solving systems differential equations I need to numerically solve
$$\frac{\mathrm dx}{\mathrm dt} = y - x^3$$
$$\frac{\mathrm dy}{\mathrm dt} = -x - y^3$$
with initial conditions $x_0,y_0 = 1,0$ for $t$ from $1$ to $100$.
I don't know how to do this.
I'd also like to plot this along with some other functions and don't know how to plot multiple functions on one plot. The specific functions are
$$A = x^2 + y^2$$
and
$$B = 1/t$$
I'm quite new to MATLAB, so I need some help.

A: Let $z = [x,y]$, observe $z' = [x',y'] = [z(2)-z(1)^3,-z(1)-z(2)^3]$.
Your initial condition is $z_0 = [x_0,y_0] = [1,0]$
The trick is now we have a vector $z$ and we know its derivative $z'$ and initial values, we can certainly solve it (numerically).
Matlab solvers like ode45 or ode23 can easily tackle this, or you can write your own solver using Euler's method and so on.
Example Code
f = @(t,z)[z(2)-z(1)^3,-z(1)-z(2)^3];
[t z] = ode45(f,[1 100],[1 0]);
Remember now your $z$ vector contains both $x$ and $y$.
$z(:,1)$ will give you $x$ vector in correspondence to $t$ vector and $z(:,2)$ will give the $y$ vector
You can for example
plot(t,z(:,1))
to see how x evolve along t or
plot(t,z(:,2))
to see how y evolve along t. Or
plot(z(:,1),z(:,2))
to see the phase plot.

Regarding plotting against $A$ and $B$, I think you might have misunderstood the problem. We have x(t) and y(t) and we solved them, this is different from solving z(x,y,t). Don't get them confused.
Your A(x(t),y(t)) is basically a parametrized curve in 2 dimension (z against t). You can plot by
A = @(x,y) x.^2+y.^2;
plot(t,A(z(:,1),z(:,2));
And your B has nothing to do x(t) and y(t), it only depends on t, so again a 2 dimension plot.
B = @(t) 1./t;
plot(t,B(t));
To plot them on the same graph you can do either
plot(t,A(z(:,1),z(:,2),t,B(t));
or
plot(t,A(z(:,1),z(:,2)); hold on; plot(t,B(t)); hold off;


text:
Q: Tag wiki excerpt for R repeatedly edited to add hyperlink Following several discussion on meta regarding hyperlinks in tag wiki excerpts, I've suggested an edit to remove the hyperlink in r excerpt.
Unfortunately, the hyperlink returned, in an unanimously approved suggestion:

So the question is, should this edit be undone? Should I suggest another edit equal to my previous one?
obs: Relevant link: exerpt history.

A: Probably because the hyperlinks get rendered when reviewing the suggested edit (it's even rendered in the revision history, as you can see), but don't actually get rendered in the popup box. People are less likely to notice or think about the problem when reviewing.
I've undone the edit. It's obviously incorrect since it looks horrid in that popup.


text:
Q: Can I let my website down usign godaddy I create a website using web builder in godaddy.
But Now I want that website be unreachable so the status should not be 200.
Is there a way to do this?
Thanks in advance

A: Yes, just call GoDaddy tech support and ask them to do this. They'll walk you through step by step.
One option would be to set your domain to a Parked page. That would still retain your web builder creation to be used at a later time.


text:
Q: Successfully codesigned and notarized app getting unable to verify developer when running I have a fully codesigned .app which is successfully notarized. However when running the app on someones computer. They get the error

"App" cannot be opened because the developer cannot be verified.

When running spctl -avv App.app it returns
App.app: accepted
source=Notarized Developer ID
origin=Developer ID Application: **

And running codesign -vv --deep-verify App.app it returns
App.app: valid on disk
App.app: satisfies its Designated Requirement

Is there anything I am missing or can run that could expose what's wrong with my signed app?

A: I found the issue. I have a framework in the .app that I codesign. Gatekeeper doesn't show anything wrong when I notarize it. However, when I didn't code sign the included framework, and then submitted to notarize, it came back with errors.
I simply codesigned what the errors were, instead of everything and that fixed the issue. Now the app runs fine on other devices!


text:
Q: Unmet dependencies, Installing ROS indigo, ros-indigo-desktop-full I am trying to install ROS Indigo on a Oracle VM VirtualBox machine, however, i came across this issue. When i try to run the command sudo apt-get install ros-indigo-desktop-full i get this message

Reading package lists... Done
  Building dependency tree
  Reading state information... Done
  Some packages could not be installed. This may mean that you have
  requested an impossible situation or if you are using the unstable
  distribution that some required packages have not yet been created
  or been moved out of Incoming.
  The following information may help to resolve the situation:
  The following packages have unmet dependencies:
   ros-indigo-desktop-full : Depends: ros-indigo-desktop but it is not going to be installed
                             Depends: ros-indigo-perception but it is not going to be installed
                             Depends: ros-indigo-simulators but it is not going to be installed
                             Depends: ros-indigo-urdf-tutorial but it is not going to be installed
   unity-control-center : Depends: libcheese-gtk23 (>= 3.4.0) but it is not going to be installed
                          Depends: libcheese7 (>= 3.0.1) but it is not going to be installed
  E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.

To mention, I am following the instructions from http://wiki.ros.org/indigo/Installation/Ubuntu and have done all steps from 1.1 to 1.4 and as is seems i have some dependency issue i tried installing additional system dependencies mentioned in point 1.4 sudo apt-get install xserver-xorg-dev-lts-trusty mesa-common-dev-lts-trusty libxatracker-dev-lts-trusty libopenvg1-mesa-dev-lts-trusty libgles2-mesa-dev-lts-trusty libgles1-mesa-dev-lts-trusty libgl1-mesa-dev-lts-trusty libgbm-dev-lts-trusty libegl1-mesa-dev-lts-trusty
Still, i get an error message

Reading package lists... Done
  Building dependency tree
  Reading state information... Done
  E: Unable to locate package xserver-xorg-dev-lts-trusty
  E: Unable to locate package mesa-common-dev-lts-trusty
  E: Unable to locate package libxatracker-dev-lts-trusty
  E: Unable to locate package libopenvg1-mesa-dev-lts-trusty
  E: Unable to locate package libgles2-mesa-dev-lts-trusty
  E: Unable to locate package libgles1-mesa-dev-lts-trusty
  E: Unable to locate package libgl1-mesa-dev-lts-trusty
  E: Unable to locate package libgbm-dev-lts-trusty
  E: Unable to locate package libegl1-mesa-dev-lts-trusty

I also tried using sudo apt-get install libgl1-mesa-dev-lts-trusty
but this does not work either as it gives me yet another error message

Building dependency tree
  Reading state information... Done
  E: Unable to locate package libgl1-mesa-dev-lts-trusty

How can i solve this issue and continue installation?


text:
Q: Javascript: Sorting an array of objects based on a timestamp property doesn't sort one element correctly I am trying to sort an array which contains arrays of
two elements of the form [[string, object], [string, object], ...]. Each object has a property named: currentStatusTimestamp. I am trying to sort the internal arrays based on this property. It seems that all the elements are sorted correctly except one element which stays always at the first position of the array.
You can view an example describing the problem below.
Unsorted:
Unsorted array
Sorted:
Sorted array
The first element at each line of the images corresponds to arr[0] (string) and the second to the arr[1].currentStatusTimestamp.
I have tried to sort the arrays with two different functions, but neither seem to work.
You may find the two functions below:
const sortByCurrentStatusTimestamp2 = (array) => {
array.sort((a,b) => {
    return (Number(a[1].currentStatusTimestamp) < Number(b[1].currentStatusTimestamp)) ? 1 : ((Number(b[1].currentStatusTimestamp) > Number(a[1].currentStatusTimestamp)) ? -1 : 0);} );}

const sortByCurrentStatusTimestamp = (array) => {
array.sort((a, b) => {
    return Number(a[1].currentStatusTimestamp) < Number(b[1].currentStatusTimestamp);
});}

The code which calls the functions is displayed below:
sortByCurrentStatusTimestamp2(entriesArray);

or
sortByCurrentStatusTimestamp(entriesArray);

You may find the code used to display the output which is shown in the images, below:
for (let e of entriesArray) {
console.log(e[0],e[1].currentStatusTimestamp);}

sortByCurrentStatusTimestamp2(entriesArray);

for (let e of entriesArray) {
console.log(e[0],e[1].currentStatusTimestamp);}

A: The JS .sort function requires a comparator that returns a negative number, zero, or a positive number.   Your second returns a boolean.
Your first function fails because you do (a < b) ? 1 : (b > a) ? -1 : 0, but the two comparisons are equivalent, i.e. you got the second comparison the wrong way around.
It normally suffices to just return the difference between the two numeric values:
.sort((a, b) => +a[1].currentStatusTimestamp - +b[1].currentStatusTimestamp);

This will give the results in ascending order.   Swap a and b to reverse that.


text:
Q: Spring Boot @Async method executing synchronously This is very similar to the other question here: Spring Boot @Async method in controller is executing synchronously. However my @Service method annotated with @Async is still executing synchronously. I've tried all methods from different forums to no use. Hopefully someone could help me figure out why. A simple spring boot project as below doesn't work.
AsyncConfiguration.java
@Configuration
@EnableAsync
public class AsyncConfiguration(){}

SomeService.java
@Service
public class SomeService() {
  @Async
  public void doSomething() {
    try {
      Thread.sleep(5000L);
    } catch (Exception ignore){}
  }
}

SomeController.java
@Controller
public class SomeController() {

  @Inject SomeService someService;

  @RequestMapping(value="/", method=RequestMethod.POST)
  public String doStuff() {
    someService.doSomething();
    return "mytemplate";
  }
}

A: Here is a simple example with @Async. Follow these steps to get @Async to work in your Spring Boot application:
Step 1: Add @EnableAsync annotation and Add TaskExecutor Bean to Application Class.
Example:
@SpringBootApplication
@EnableAsync
public class AsynchronousSpringBootApplication {

    private static final Logger logger = LoggerFactory.getLogger(AsynchronousSpringBootApplication.class);

    @Bean(name="processExecutor")
    public TaskExecutor workExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix("Async-");
        threadPoolTaskExecutor.setCorePoolSize(3);
        threadPoolTaskExecutor.setMaxPoolSize(3);
        threadPoolTaskExecutor.setQueueCapacity(600);
        threadPoolTaskExecutor.afterPropertiesSet();
        logger.info("ThreadPoolTaskExecutor set");
        return threadPoolTaskExecutor;
    }

    public static void main(String[] args) throws Exception {
  SpringApplication.run(AsynchronousSpringBootApplication.class,args);
 }
}

Step 2: Add Method which executes an Asynchronous Process
@Service
public class ProcessServiceImpl implements ProcessService {

    private static final Logger logger = LoggerFactory.getLogger(ProcessServiceImpl.class);

    @Async("processExecutor")
    @Override
    public void process() {
        logger.info("Received request to process in ProcessServiceImpl.process()");
        try {
            Thread.sleep(15 * 1000);
            logger.info("Processing complete");
        }
        catch (InterruptedException ie) {
            logger.error("Error in ProcessServiceImpl.process(): {}", ie.getMessage());
        }
    }
}

Step 3: Add an API in the Controller to execute the asynchronous processing
@Autowired
private ProcessService processService;

@RequestMapping(value = "ping/async", method = RequestMethod.GET)
    public ResponseEntity<Map<String, String>> async() {
        processService.process();
        Map<String, String> response = new HashMap<>();
        response.put("message", "Request is under process");
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

I have also written a blog and a working application on GitHub with these steps. Please check:
http://softwaredevelopercentral.blogspot.com/2017/07/asynchronous-processing-async-in-spring.html

A: Sorry for my English.
The same problem happened to me.
The solution was to add
@Autowired
private SomeService someService;

In the Controller class, in this way it allows the class to contain the Beam Configurations associated with "SomeService", thus being able to execute the asynchronous method perfectly.
Here is a project with a functional asynchronous method:
https://github.com/JColmenares/async-method-api-rest.git


text:
Q: Unable to retrieve all enabled Change Tracking Databases I'm trying to retrieve all Change Tracking databases by using:
Select *
from sys.change_tracking_databases

I already enabled for all my databases, but the query only returns the current data which I'm using or return 0 row if I'm using master database.
What did I do wrong, or do I need to config anything else?

A: This should work. And if it doesnt you havent done it correct

You can also select properties on your database and go to Change Tracking option which is right below option field. There you can see if Change Tracking = True

SELECT d.name AS 'Database Name', t.*
FROM sys.change_tracking_databases t
INNER JOIN sys.databases d ON d.database_id = t.database_id


text:
Q: Marklogic entity property versus relationship for an effective Mastering I have a question around best practices in the design of entities in MarkLogic.
When we design a property under an entity, it can have classic types or also other entity types.
Example:
Entity A
|-id (string)
|-property1 (string)
|-property2 (string)
|-property3 (Entity B)
Entity B
|-id (string)
|-property1 (string)
|-property2 (string)
In designing relationships between entities, using different tools provided by Marklogic, to link entities we have different manners and I'd like to have your recommendation on when to use external entity as a property and when to use only a relationship
This is extremely important as I personally found that using entities as properties helps a lot in the mastering step and harmonization more than relationship
Any thoughts?


text:
Q: Why am I getting this error "Azure Error: InvalidTemplateDeployment"? I am trying to create a virtual machine in Azure cli. Following is the command
az vm create --resource-group user-bgfbaowgiqxc --name VmName --image CentOS --admin-username azureuser --admin-password AdminPassword@1 --size Basic_A1 --generate-ssh-keys

I have tried changing size to Standard_B1s and standard_B1ms but still getting the same error. I have just started learning azure.

A: From provided information can not make out exactly for which parameter this error had thrown. but you can use below provided ps to create VM.

*

*Create resource group

*Execute below command in azure cli (End of each command add backticks `)
New-AzVm
-ResourceGroupName "Here enter your resource group name"
-Name "VM name"
-Location "East US"
-VirtualNetworkName "VN name"
-SubnetName "Subnet VM"
-SecurityGroupName "SG name"
-PublicIpAddressName "IP name"
-OpenPorts 80,3389

*Post executing above command, CLI will prompt you to enter user name and password for VM.

*Your VM will be ready in couple of minutes.

Source


text:
Q: Static methods or not? I need to develop a small CMS using PHP, and right now I'm trying to figure out the structure.
The CMS will be generated using a set of functions. Things like database functions, caching thingies, internationalization and stuff like this.
I was thinking to do it like this:

*

*make the functions non-static methods part of a big "site" class; that way I could run multiple instances of that class. Not sure I would need to do that though..

*or split the functions into separate classes with static methods
The main problem here is that the CMS should be able to manage multiple small sites, not just one. So either I make all methods static and add a "site switch" function, or make them normal objects which I instantiate based on the site which I want to manage
Which of these would be the best option?

A: Static methods are generally bad practice. They introduce a lot of potential issues.
1) They introduce hidden dependencies. Code which arbitrarily calls foo::bar() has a dependency on foo and cannot run without foo being defined. The object using foo::bar() will construct correctly but won't be usable if foo is not defined.
2) Statics are globals. Global state is very bad, anything can change the code and its state is unknown. You sacrifice the power and control achieved by OOP encapsulation by using static methods.
3) It's impossible to substitute the functions for a different version
4) It makes unit testing impossible.
For more detailed information and code examples, see this article and this article

A: I'd definitely suggest using static classes for this job.  Going this route will create a pseudo namespace for all of your functions so you don't have to worry about conflicting function names, etc, and it also prevents you from having to pass around an instance of your helper class just to call one of your helper functions.


text:
Q: How to automate installation process of any windows software application I want to automate the installation process of any windows .exe/application software.
For example: I have "npp.7.Installer.x64" .exe file and I want to install this .exe/application through any scripting or tool instead of manual process.
I had tried with "AutoIT" tool but I am unable to achieve the results.
Please suggest me a appropriate way. Thanks in advance.

A: I have write code in python command line with administration permission and write below lines:
app = Application().start(r"D:\npp.7.Installer.x64.exe")
Above code successfully pop the Installation window of notepad.


text:
Q: I get a bash syntax error message every time I open Terminal I've been getting this error for the past couple of months and I wonder if it's a major issue, and how do I fix it?
When I open terminal on my Mac I get this bash error:
~bash: /Users/admin/.bash_profile: line 1: syntax error near unexpected token 'fi'
~bash: /Users/admin/.bash_profile:line 1: 'if which rbenv > /dev/null; than eval "$(rbenv init -)"; fi'

Anybody know what's going on?

A: Open the Terminal.app and type the following line at your prompt
sed -i '' 's/than/then/' .bash_profile

You do have a .bash_profile in your home directory.

A: To add a little information to fd0's terse answer.
First, you do indeed have a file .bash_profile in admin's home folder - you just can't see it as all files with a name that starts . are invisible. In the Terminal type ls -A and you will see them all.
Second, your problem is that something or someone has added a line to the file containing a syntax error. The than should be then as it is part of an if-then statement. Open the file in your favourite text editor (if you don't have one then newcomers seem to find nano usable so nano .bash_profile in Terminal should do it) and change the line.


text:
Q: OpenXava Entity security How could I show entities based on logged in user role? So if user logged in with admin role he will get access to all system elements and if he logged in as user he will get a subset of the system.
Thanks

A: With OpenXava you can choose to produce a portlets based application or a normal webapp war, then you have two options here: 1).- Deploy you portlets' war into some portlet container like Liferay and then take advance of Liferay security schemas and other features of Liferay.
On the other hand, if you choose a webapp war you could take a look to this (not free) add-on http://www.openxava.org/naviox ... or then you could implement your security layer taking advance of some tool like Spring Security, here is a minuteproject blog entry with an extended example http://minuteproject.blogspot.com/2012/02/adding-spring-security-to-openxava.html .... I have not tested this last example, in fact I had some problems when I tried to integrate Spring in other OpenXava project for ActiveMQ JMS (and then I did follow other way) ... but maybe it could work if you follow the same steps and do that for Spring  Security into your OpenXava application.


text:
Q: Why does my LSTM autoencoder model couldn't detect outliers? I am trying to build a LSTM Autoendoer for anomaly detection.
But the model seems not work for my data.
Here is the normal data that I use it for training.

And here is abnormal data that I use it for validation.

If model works, its loss should be high at #200000~#500000.
Unfortunately, here is the result I put the valid data to the model:

In the abnormal interval, the loss still low.
Here is my code of training model.
I would greatly appreciate it if you kindly give me any suggestions.
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit(healthy_data)
data_scaled = scaler.transform(healthy_data)
data_broken_scaled = scaler.transform(broken_data)

timesteps=32
data = data_scaled
dim = 1
data.shape = (-1,timesteps,dim)

lr = 0.0001
Nadam = optimizers.Nadam(lr=lr)

model = Sequential()
model.add(LSTM(50,input_shape=(timesteps,dim),return_sequences=True))
model.add(Dense(dim))

model.compile(loss='mae', optimizer=Nadam ,metrics=['mse'])

EStop = EarlyStopping(monitor='val_loss', min_delta=0.001,patience=150, verbose=2, mode='auto',restore_best_weights=True)

history = model.fit(data,data,validation_data=(data,data),epochs=3000,batch_size=72,verbose=2,shuffle=False,callbacks=[EStop]).history

pred_broken = model.predict(data_broken_scaled)
loss_broken = np.mean(np.abs(pred_broken-data_broken_scaled),axis=1)
fig, ax = plt.subplots(figsize=(20, 6), dpi=80, facecolor='w', edgecolor='k')
ax.plot(range(0,len(loss_broken)), loss_broken, '-', color='red', animated = True, linewidth=1)

A: I Think, it may better to use Fourier transform to detect anomaly in frequency view.
I means, the train and test data will be converted to frequency domain via Fourier transform. Also I recommend to use Time-windows.
Most AI will act better if they have enough good train data. Your anomaly points should be labeled to 1(by pre-processing step of the data) and it should have high frequency at your time-step(time-windows).
In short, I think your train data may not sufficiently representative for anomaly now.


text:
Q: One javascript function works outside a loop-file, other doesn't BBpress uses loop-single-reply.php and content-single-topic.php to display a page inside a topic. I've edited both files for some extra functionality.
Everything works as it should but I can't stop wondering why I have to place one javascript function inside the loop-single-reply.php file to work while I can place the other in content_single_topic.php
This is the code I'm working with, loop-single-reply.php:
<button class="button-best-like" onClick="return shareMeta('<?php echo $correct_link; ?>', '<?php echo $fb_excerpt; ?>', 'fb-image-<?php echo $reply_id; ?>'); ga('send','event','Facebook','share','like', 0)">
<i class="fa fa-facebook-official" aria-hidden="true" title="Share on Facebook"></i>
</button>

<script>
function shareMeta(link, description, replyId) {
    var title           = '<?php echo $fb_title; ?>';
    var replyImages     = document.getElementById(replyId).getElementsByTagName('img');
    var defaultImage    = '/uploads/2017/12/Hero-image.jpg';
    var result;
    if (replyImages.length > 0) {
        for(var i=0, l=replyImages.length; i<l; i++) {
            if(replyImages[i].height >= 200 && replyImages[i].width >= 200) {
                result = i;
                break;
            }
        }
        if (result == null) {
            var image = defaultImage;
        } else {
            var image = replyImages[result].src;
        }
    } else {
        var image = defaultImage;
    }
    shareOverrideOGMeta(link, title, description, image);
}
</script>

And the content-single-topic.php code
<script>
function shareOverrideOGMeta(overrideLink, overrideTitle, overrideDescription, overrideImage) {
    FB.ui({
        method: 'share_open_graph',
        action_type: 'og.likes',
        action_properties: JSON.stringify({
            object: {
                'og:url': overrideLink,
                'og:title': overrideTitle,
                'og:description': overrideDescription,
                'og:image': overrideImage
            }
        })
    });
}
</script>

When I try to place the shareMeta function inside content-single-topic.php everything stops working. So I have to place it inside loop-single-reply.php to work. But in this case the function is printed 15 times, which seems a bit
unnecessary.
How come? Is there a better way?
Keep in mind this is my first attempt at javascript so there is probably a better way.


text:
Q: XML Serializable IQueryable/Expression Tree Is there any classes built in to .NET that will convert an expression tree or an IQueryable<T> to XML?

A: Not directly, no.  IQuerable<T> is an interface, and as such, there can be many implementations behind it, each of them serializing differently.
That said, you could try and serialize the Expression that the IQueryable interface (the base of IQueryable<T>) exposes through the Expression property.
The problem there is that the Expression class and it's subclasses are not serializable, so you would have to create a structure that is a mirror of the Expression class (and all of its subclasses, and there are many) and then serialize that.  Fortunately, there is the Expression Tree Serialization project on MSDN which might help you.
Even then, you still won't have things like provider information, etc.  This may or may not impact what you are trying to do.
However, if all you need is to set the expression tree on an existing IQueryable<T> implementation, this should suffice.


text:
Q: Is it possible to have two labels for an axis using Show function? I use this code
P1 := RegionPlot[0 <= Cos[y x] <= 1/2, {y, 0, 3}, {x, 0, 5},
  PlotStyle -> LightBlue,
  FrameLabel -> {{Style[Rotate["F", 270 Degree], 15],
     None}, {Style["y", 15], None}}, BaseStyle -> 15]

P2 := RegionPlot[0 <= Cos[-y x] <= 1/2, {y, 0, 3}, {x, 0, -5},
  PlotStyle -> LightBlue,
  FrameLabel -> {{Style[Rotate["G", 270 Degree], 15],
     None}, {Style["y", 15], None}}, BaseStyle -> 15]

Show[{P1, P2}, PlotRange -> All]

and the result is

But here, it only shows one of the FrameLabel; Is it possible to ask Mathematica to give both labels using Show? We can do it by other commands, but this is not my original function, and I want to know is it possible to do it by using Show or not? like this

A: P1 = RegionPlot[0 <= Cos[y x] <= 1/2, {y, 0, 3}, {x, 0, 5},
   PlotStyle -> LightBlue,
   FrameLabel -> {{None, None}, {Style["y", 15], None}},
   BaseStyle -> 15];

P2 = RegionPlot[0 <= Cos[-y x] <= 1/2, {y, 0, 3}, {x, 0, -5},
   PlotStyle -> LightBlue];

You can add the labels using the options Epilog, PlotRangeClipping and ImagePadding:
Show[P1, P2, PlotRange -> All,
 Epilog -> {Text[Style["F", 15], {-.15, 3}],
   Text[Style["G", 15], {-.15, -3}]},
 PlotRangeClipping -> False,
 ImagePadding -> {{50, 5}, {50, 5}}]

Alternatively, you can use Legended to add the labels:
Legended[Show[P1, P2, PlotRange -> All],
 {Placed[Style["F", 15], {0, .82}], Placed[Style["G", 15], {0, .3}]}]


text: Q: How to make a datetime column the index in a pandas dataframe? I am working on a code where data is called from a CSV file; it turns the dates in a column called indexDatetime to datetime. It is supposed to set that column to be the index. But when I use .set_index('indexDatetime'), the index does not change.


text:
Q: column to span \paperwidth in beamer footline In the following code
\documentclass{beamer}
\makeatletter
\setbeamertemplate{footline}{
  \leavevmode
    \begin{beamercolorbox}[wd=\paperwidth, ht=4ex, left]{author in head/foot}%
      \usebeamerfont{author in head/foot}
      \begin{tabular}{|p{0.5\paperwidth}|p{0.5\paperwidth}|}
        entry00 & entry01
      \end{tabular}
    \end{beamercolorbox}%
}
\makeatother

\begin{document}
\begin{frame}
  frame contents
\end{frame}
\end{document}

I try to create a table in a beamer footline to span the width of a beamer frame. The result is not satisfactory as I cannot see the rightmost margin of the table:

How to fix the solution?

A: There were just two things wrong with your code:

*

*There was an extra implicit space after \hbox{. I fixed it by adding a % after it.

*The 0.5\paperwidth is the width of the text. It does not include the \tabcolsep, which separates the text from the vertical rules. I have set it to zero to make the column with exactly 0.5\paperwidth.

Also, as you noted yourself, there is no apparent need for the \hbox, so I removed it
The code:
\documentclass{beamer}
\makeatletter
\setbeamertemplate{footline}{
  \leavevmode
  \begin{beamercolorbox}[wd=\paperwidth, ht=4ex, left]{author in head/foot}
    \usebeamerfont{author in head/foot}
    \setlength{\tabcolsep}{0pt}
    \begin{tabular}{|p{0.5\paperwidth}|p{0.5\paperwidth}|}
      entry00 & entry01
    \end{tabular}
  \end{beamercolorbox}%
}
\makeatother

\begin{document}
\begin{frame}
  frame contents
\end{frame}
\end{document}

Another option to the second problem is to reduce the width of the column by 2\tabcolsep to make it fit, like this:
\documentclass{beamer}
\makeatletter
\setbeamertemplate{footline}{
  \leavevmode
  \begin{beamercolorbox}[wd=\paperwidth, ht=4ex, left]{author in head/foot}
    \usebeamerfont{author in head/foot}
    \begin{tabular}{|p{\dimexpr0.5\paperwidth-2\tabcolsep}|p{\dimexpr0.5\paperwidth-2\tabcolsep}|}
      entry00 & entry01
    \end{tabular}
  \end{beamercolorbox}%
}
\makeatother

\begin{document}
\begin{frame}
  frame contents
\end{frame}
\end{document}

The second option looks better because the text doesn't run over the vertical rule. But if you must have the text running in 0.5\paperwidth then the first one is what you want.

A: I would not use a table to place different fields besides each other in the footline. In normal beamer themes, this effect is achieved by simply placing several beamercolorboxes besides each other:
\documentclass{beamer}

\makeatletter
\setbeamertemplate{footline}{%
  \leavevmode%
  \hbox{%
  \begin{beamercolorbox}[wd=.5\paperwidth,ht=2.25ex,dp=1ex,center]{author in head/foot}%
    \usebeamerfont{author in head/foot}\insertshortauthor\expandafter\ifblank\expandafter{\beamer@shortinstitute}{}{~~(\insertshortinstitute)}
  \end{beamercolorbox}%
  \begin{beamercolorbox}[wd=.5\paperwidth,ht=2.25ex,dp=1ex,center]{title in head/foot}%
    \usebeamerfont{title in head/foot}\insertshorttitle
  \end{beamercolorbox}%
    }%
  \vskip0pt%
}
\makeatother

\author{names}
\title{title}

\begin{document}
\begin{frame}
  frame contents
\end{frame}
\end{document}

Depending on what you are actually going to add to the footline, the hackthefootline might be a simple alternative:
\documentclass{beamer}
\usepackage[twocols]{hackthefootline}

\author{names}
\title{title}

\begin{document}
\begin{frame}
  frame contents
\end{frame}
\end{document}


text:
Q: Backing up audit data with growisofs We've had a problem occur when writing to DVD+Rs and DVD-Rs using growisofs on Redhat Enterprise Linux 5.0. What we're trying to do is backup audit data that we've stored, which is basically one .zip file for each day's worth of audit data. The .zip files are relatively small, generally only a few megabytes each. We receive the following error message from growisofs when writing to a DVD+R or DVD-R:

:-( unable to pread64(2) primary volume descriptor: Input/output error
you most likely want to use -Z option.

growisofs also exits with an exit code of 150. According to a Debian mailing list post I read (link no longer working) growisofs returns errno+128, so this appears to correspond with errno=22, which is EINVAL (Invalid argument).
The primary volume descriptor is definitely there as we have already initialized the DVD with -Z. The first thing we do is growisofs -Z, followed by one growisofs -M command per file. The error usually happens on the second file we write--i.e., the DVD is initialized with -Z, we write one .zip file successfully, and then the second .zip file yields this error message.
A simple workaround is to physically eject the DVD and then re-insert it at which point the DVD works again and we are able to write the rest of the files. That's less than ideal, though. The error is not consistent but it is quite frequent and ejecting seems to always fix the problem.
Here are the commands we use to write to the DVD:
growisofs -Z /dev/dvd -rJ -use-the-force-luke=notray blank.iso

for each FILE:
    growisofs -M /dev/dvd -rJ -use-the-force-luke=notray "$FILE"

Here's sample output from dvd+rw-mediainfo /dev/dvd, if it helps:

INQUIRY:                [TEAC    ][DV-W28EC        ][1.0B]
GET [CURRENT] CONFIGURATION:
 Mounted Media:         1Bh, DVD+R
 Media ID:              RITEK/F16
 Current Write Speed:   8.0x1385=11080KB/s
 Write Speed #0:        8.0x1385=11080KB/s
 Write Speed #1:        6.0x1385=8310KB/s
 Write Speed #2:        4.0x1385=5540KB/s
 Write Speed #3:        2.4x1385=3324KB/s
 Speed Descriptor#0:    00/2295103 R@8.0x1385=11080KB/s W@8.0x1385=11080KB/s
 Speed Descriptor#1:    00/2295103 R@6.0x1385=8310KB/s W@6.0x1385=8310KB/s
 Speed Descriptor#2:    00/2295103 R@4.0x1385=5540KB/s W@4.0x1385=5540KB/s
 Speed Descriptor#3:    00/2295103 R@2.4x1385=3324KB/s W@2.4x1385=3324KB/s
READ DVD STRUCTURE[#0h]:
 Media Book Type:       00h, DVD-ROM book [revision 0]
 Legacy lead-out at:    2295104*2KB=4700372992
READ DISC INFORMATION:
 Disc status:           appendable
 Number of Sessions:    21
 State of Last Session: empty
 "Next" Track:          21
 Number of Tracks:      21

Any ideas on what is causing this problem or how to fix it?

A: CD/DVD burner handling on Linux has always been flaky, without much developer or vendor interest in fixing the problems. DVD+R's got the worst of it.
If your drive is the type that can un-eject, do an "eject disk" and "eject -t disk" after each writing operation. I never dared user growisofs to grow an ISO filesystem, just to write to DVD+Rs when dvdrecord/cdrecord stopped working on DVD+R. Both with growisofs and cdrecord, I usually had to eject / uneject to get a freshly written disk to work.

A: I was having this problem with Ubuntu 9.04 and growisofs 7.1 and it turned out to be the file that I was trying to back up was not accessible. I would suggest checking to be sure that $FILE exists and has proper permissions before passing it to growisofs. I assume that the message ":-( unable to pread64(2) primary volume descriptor: Input/output error you most likely want to use -Z option." is probably a bug since the problem was with the source file and not the destination media.

A: Short answer - Strace it. I'm not denying that any of the above responses are correct in their cases - but I had it happen because I did not have write permissions to the DVD drive. Then it happened again because I didn't have permission to access the underlying SCSI Generic device (/dev/sg1). So in short - it looks like this is a very generic error that could have many root causes.


text:
Q: Como estender o comprimento de Widgets dentro de um QScrollArea? Estou buscando construir um formulário de perguntas em Qt. Como há várias perguntas a serem respondidas, é necessário permitir a rolagem do formulário, e por isso utilizei uma QScrollArea. As perguntas são todas respondidas em uma escala Likert, então eu ajustei o alinhamento do layout que as contém para a esquerda e espacei as opções manualmente. Ou seja, tudo está alinhado à esquerda. Também implementei um estilo colorido alternado, apenas para tornar mais agradável para o usuário a diferenciação das perguntas ao rolar o formulário.
Eis a seguir uma imagem do MCVE que eu preparei (e que se encontra a seguir). O principal problema é que eu não consigo fazer com que esse "zebrado" se estenda até o fim do formulário (na direita, indicado na caixa azul na imagem). Há também o espaço que parece uma margem, na esquerda (indicado na caixa vermelha).

Para resolver o problema principal, eu já tentei alterar as restrições de tamanho dos layouts filhos (usando setSizeConstraint) e até mesmo adicionar um alargador (stretch) após a última opção (como se pode observar na linha de código marcada com comentário), mas nenhuma dessas opções funciona. E para o problema secundário, bom, eu já tentei alterar as margens via folha de estilos (conforme está no código) e até usar o método setMargin da própria classe QWidget, mas nada funciona.
O que funciona para o problema principal é definir um tamanho mínimo ou fixo para o container das opções (o objeto em pRow), mas eu não posso usar essa opção porque a janela pode ter o tamanho ajustado pelo usuário (ou conforme as dimensões da tela disponíveis a ele). Também porque ele não resolve o problema secundário, e eu não desejaria capturar evento de redimensionamento da janela pra ajustar o tamanho manualmente - já que aí eu perco a vantagem de se usar layouts.
Alguma sugestão?
Código do MCVE
#include <QApplication>
#include <QWidget>
#include <QRadioButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFrame>
#include <QLabel>
#include <QRadioButton>
#include <QScrollArea>

#define STYLE_SHEET "                               \
                    QWidget#plainArea               \
                    {                               \
                        background-color: #ffffff;  \
                        padding: 0px 0px 0px 0px;   \
                        margin: 0px 0px 0px 0px;    \
                        border-width: 0px;          \
                    }                               \
                                                    \
                    QLabel#headerTitle              \
                    {                               \
                        font-size: 25px; }          \
                    }                               \
                                                    \
                    QLabel#questionTitle            \
                    {                               \
                        font-size: 20px;            \
                    }                               \
                                                    \
                    QRadioButton#optionTitle        \
                    {                               \
                        font-size: 16px;            \
                    }                               \
                                                    \
                    QWidget#highlightedrow          \
                    {                               \
                        background-color: #efd3d2;  \
                    }                               \
                    "

QWidget* createQuestionnaire(QWidget *pParent)
{
    QWidget *pQuestionnaire = new QWidget(pParent);
    pQuestionnaire->setObjectName("plainArea");
    pQuestionnaire->setLayout(new QVBoxLayout());
    pQuestionnaire->layout()->setAlignment(Qt::AlignTop);

    // Cabeçalho
    QLabel *pTitle = new QLabel("Por favor, responda às perguntas a seguir.", pQuestionnaire);
    pTitle->setObjectName("headerTitle");
    pQuestionnaire->layout()->addWidget(pTitle);

    QFrame *pLine = new QFrame(pQuestionnaire);
    pLine->setFrameStyle(QFrame::HLine);
    pLine->setLineWidth(4);
    pQuestionnaire->layout()->addWidget(pLine);
    static_cast<QBoxLayout*>(pQuestionnaire->layout())->addSpacing(10);

    // Scroll Area
    QScrollArea *pScroll = new QScrollArea(pQuestionnaire);
    pScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    pScroll->setObjectName("plainArea");
    pScroll->setLayout(new QVBoxLayout());
    pQuestionnaire->layout()->addWidget(pScroll);

    QWidget *pArea = new QWidget(pQuestionnaire);
    pArea->setObjectName("plainArea");
    pArea->setLayout(new QVBoxLayout());
    pArea->layout()->setSizeConstraint(QLayout::SetMinAndMaxSize);

    pScroll->setWidget(pArea);

    // Questões
    QStringList lFruits = {
        "Abacate", "Amora", "Ameixa", "Acerola", "Abacaxi", "Açaí",
        "Banana", "Bacuri", "Buriti", "Butiá", "Bacaba", "Carambola",
        "Cajá", "Caju", "Cereja", "Cacau", "Caqui", "Cupuaçu", "Damasco",
        "Figo", "Framboesa", "Fruta Pão", "Graviola", "Goiaba", "Goiaba Branca",
        "Groselha", "Guaraná", "Grumixama", "Guariroba", "Ingá", "Ibapó",
        "Itu", "Ingá Dedo", "Ingá Branco", "Jaca", "Jabuticaba", "Jambo",
        "Jenipapo", "Jatobá", "Kiwi", "Laranja", "Limão", "Lima Doce",
        "Lixia", "Melancia", "Mamão", "Melão", "Maracujá", "Manga",
        "Macadâmia", "Maçã", "Mangaba", "Mexerica", "Nectarina", "Noz",
        "Nêspera", "Olho-De-Boi", "Pera", "Pêssego", "Pitaya", "Pitanga",
        "Pinha", "Pinhão", "Pitomba", "Pocã", "Quina", "Rabutan", "Romã",
        "Sapoti", "Sapucaia", "Salok", "Saputá", "Tangerina", "Tomate",
        "Tamarindo", "Toranja", "Taiúva", "Uva", "Uxi", "Uvaia", "Umbu",
        "Veludo", "Wampi", "Xixá"
    };

    QStringList lOptions = { "detesto", "gosto pouco", "gosto", "gosto muito", "adoro" };

    for(int i = 0; i < lFruits.size(); i++)
    {
        QWidget *pRow = new QWidget(pQuestionnaire);
        pArea->layout()->addWidget(pRow);

        if(i % 2)
            pRow->setObjectName("highlightedrow");

        pRow->setLayout(new QVBoxLayout());
        QLabel *pQuestion = new QLabel(QString("%1 - Você gosta de %2?").arg(i+1).arg(lFruits.at(i)), pRow);
        pQuestion->setObjectName("questionTitle");
        pRow->layout()->addWidget(pQuestion);

        QWidget *pOptions = new QWidget(pRow);
        pRow->layout()->addWidget(pOptions);
        pOptions->setLayout(new QHBoxLayout());
        pOptions->layout()->setAlignment(Qt::AlignLeft);

        static_cast<QBoxLayout*>(pOptions->layout())->addSpacing(60);
        foreach(QString sOption, lOptions)
        {
            QRadioButton *pButton = new QRadioButton(sOption, pOptions);
            pButton->setCursor(Qt::PointingHandCursor);
            pButton->setObjectName("optionTitle");
            pOptions->layout()->addWidget(pButton);
            static_cast<QBoxLayout*>(pOptions->layout())->addSpacing(20);
        }
        static_cast<QBoxLayout*>(pOptions->layout())->addStretch(); // <--- Stretch não funciona!
    }

    return pQuestionnaire;
}

int main(int argc, char** argv)
{
    QApplication oApp(argc, argv);

    QWidget *pWindow = new QWidget();
    pWindow->setObjectName("plainArea");
    pWindow->setStyleSheet(STYLE_SHEET);
    pWindow->setWindowTitle("MCVE para o SOPT");

    pWindow->setLayout(new QVBoxLayout());
    pWindow->layout()->addWidget(createQuestionnaire(pWindow));

    pWindow->show();
    pWindow->resize(800, 600);
    return oApp.exec();
}

P.S.: Ah, como eu odeio o QScrollArea do Qt, viu. rs

A: Já descobri como resolver a ambos os problemas.
O problema principal se deve ao fato de que o QScrollArea não trabalha bem com uma widget interna que contenha widgets filhas organizadas em layout se não for permitido à widget do scroll ajustar seu tamanho automaticamente. Para isso, basta definir como true o valor da propriedade widgetResizable.
O bacana é que isso não está nada claro descrição principal da documentação. Lá na documentação consta apenas o seguinte:

The view can be made to be resizable with the setWidgetResizable() function.

Ao ler isso eu imaginei que o uma widget resizable seria... resizable e portando não precisaria do Scroll! (afinal, como o exemplo da documentação é de imagens, eu imaginei que elas seriam escalonadas para o tamanho do view port ao invés de apresentar as barras de rolagem). Mas não, essa propriedade é o que permite que a widget possa aumentar e diminuir de tamanho conforme ela mesma decidir. Honestamente, não entendi o motivo para alguém precisar usar essa propriedade como falso e usar uma área de rolagem, mas enfim...
Para o problema secundário, foi simplesmente mais fácil definir as margens em 0 para todos os componentes via código com o método setMargin da classe de layout, e não via folha de estilos.
O código final, que resulta na tela a seguir, é apresentado em seguida.
Tela:

Código:
#include <QApplication>
#include <QWidget>
#include <QRadioButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFrame>
#include <QLabel>
#include <QRadioButton>
#include <QScrollArea>

#define STYLE_SHEET "                               \
                    QWidget#plainArea               \
                    {                               \
                        background-color: #ffffff;  \
                    }                               \
                                                    \
                    QLabel#headerTitle              \
                    {                               \
                        font-size: 25px; }          \
                    }                               \
                                                    \
                    QLabel#questionTitle            \
                    {                               \
                        font-size: 20px;            \
                    }                               \
                                                    \
                    QRadioButton#optionTitle        \
                    {                               \
                        font-size: 16px;            \
                    }                               \
                                                    \
                    QWidget#highlightedrow          \
                    {                               \
                        background-color: #efd3d2;  \
                    }                               \
                    "

QWidget* createQuestionnaire(QWidget *pParent)
{
    QWidget *pQuestionnaire = new QWidget(pParent);
    pQuestionnaire->setObjectName("plainArea");
    pQuestionnaire->setLayout(new QVBoxLayout());
    pQuestionnaire->layout()->setAlignment(Qt::AlignTop);
    pQuestionnaire->layout()->setMargin(0);

    // Cabeçalho
    QLabel *pTitle = new QLabel("Por favor, responda às perguntas a seguir.", pQuestionnaire);
    pTitle->setObjectName("headerTitle");
    pQuestionnaire->layout()->addWidget(pTitle);

    QFrame *pLine = new QFrame(pQuestionnaire);
    pLine->setFrameStyle(QFrame::HLine);
    pLine->setLineWidth(4);
    pQuestionnaire->layout()->addWidget(pLine);
    static_cast<QBoxLayout*>(pQuestionnaire->layout())->addSpacing(10);

    // Scroll Area
    QScrollArea *pScroll = new QScrollArea(pQuestionnaire);
    pScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    pScroll->setObjectName("plainArea");
    pScroll->setLayout(new QVBoxLayout());
    pQuestionnaire->layout()->addWidget(pScroll);

    QWidget *pArea = new QWidget(pQuestionnaire);
    pArea->setObjectName("plainArea");
    pArea->setLayout(new QVBoxLayout());
    pArea->layout()->setSizeConstraint(QLayout::SetMinAndMaxSize);
    pArea->layout()->setMargin(0);

    pScroll->setWidget(pArea);
    pScroll->setWidgetResizable(true);

    // Questões
    QStringList lFruits = {
        "Abacate", "Amora", "Ameixa", "Acerola", "Abacaxi", "Açaí",
        "Banana", "Bacuri", "Buriti", "Butiá", "Bacaba", "Carambola",
        "Cajá", "Caju", "Cereja", "Cacau", "Caqui", "Cupuaçu", "Damasco",
        "Figo", "Framboesa", "Fruta Pão", "Graviola", "Goiaba", "Goiaba Branca",
        "Groselha", "Guaraná", "Grumixama", "Guariroba", "Ingá", "Ibapó",
        "Itu", "Ingá Dedo", "Ingá Branco", "Jaca", "Jabuticaba", "Jambo",
        "Jenipapo", "Jatobá", "Kiwi", "Laranja", "Limão", "Lima Doce",
        "Lixia", "Melancia", "Mamão", "Melão", "Maracujá", "Manga",
        "Macadâmia", "Maçã", "Mangaba", "Mexerica", "Nectarina", "Noz",
        "Nêspera", "Olho-De-Boi", "Pera", "Pêssego", "Pitaya", "Pitanga",
        "Pinha", "Pinhão", "Pitomba", "Pocã", "Quina", "Rabutan", "Romã",
        "Sapoti", "Sapucaia", "Salok", "Saputá", "Tangerina", "Tomate",
        "Tamarindo", "Toranja", "Taiúva", "Uva", "Uxi", "Uvaia", "Umbu",
        "Veludo", "Wampi", "Xixá"
    };

    QStringList lOptions = { "detesto", "gosto pouco", "gosto", "gosto muito", "adoro" };

    for(int i = 0; i < lFruits.size(); i++)
    {
        QWidget *pRow = new QWidget(pQuestionnaire);
        pArea->layout()->addWidget(pRow);

        if(i % 2)
            pRow->setObjectName("highlightedrow");

        pRow->setLayout(new QVBoxLayout());
        QLabel *pQuestion = new QLabel(QString("%1 - Você gosta de %2?").arg(i+1).arg(lFruits.at(i)), pRow);
        pQuestion->setObjectName("questionTitle");
        pRow->layout()->addWidget(pQuestion);

        QWidget *pOptions = new QWidget(pRow);
        pRow->layout()->addWidget(pOptions);
        pOptions->setLayout(new QHBoxLayout());
        pOptions->layout()->setAlignment(Qt::AlignLeft);

        static_cast<QBoxLayout*>(pOptions->layout())->addSpacing(60);
        foreach(QString sOption, lOptions)
        {
            QRadioButton *pButton = new QRadioButton(sOption, pOptions);
            pButton->setCursor(Qt::PointingHandCursor);
            pButton->setObjectName("optionTitle");
            pOptions->layout()->addWidget(pButton);
            static_cast<QBoxLayout*>(pOptions->layout())->addSpacing(20);
        }
    }

    return pQuestionnaire;
}

int main(int argc, char** argv)
{
    QApplication oApp(argc, argv);

    QWidget *pWindow = new QWidget();
    pWindow->setObjectName("plainArea");
    pWindow->setStyleSheet(STYLE_SHEET);
    pWindow->setWindowTitle("MCVE para o SOPT");

    pWindow->setLayout(new QVBoxLayout());
    pWindow->layout()->addWidget(createQuestionnaire(pWindow));
    pWindow->layout()->setMargin(0);

    pWindow->show();
    pWindow->resize(800, 600);
    return oApp.exec();
}


text:
Q: Why does Xamarin ListView Cahcing Strategy show "Ambiguous Reference"? Below is a screenshot of a page in the "core" project. When adding CachingStrategy="RecycleElement", I receive an

"Ambiguous Reference" error.

Hovering over it does not give any additional information on how to fix it, neither does ReSharper.

A: ReSharper is simply unable to see that property because it does not really exist or at least ReSharper is not able to detect it (read that paragraph for Xamarin saying this). Xamarin Forms does some tricky stuff (I think they use PInvoke or a compiler trick but cannot quite remember), when the code gets compiled, in order to change your ListView code when that property is specified and ReSharper is not aware that it is going on. Hopefully ReSharper will fix this in an update though I am not sure if they ever will.

A: You can specify RecycleElement in the ListView constructor instead using x:Arguments
<ListView ...>
  <x:Arguments>
    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
  </x:Arguments>
</ListView>

A: When use the above method shows
"Error CS0234 The type or namespace name 'CachedListView' does not exist in the namespace 'Xamarin.Forms' (are you missing an assembly reference?)" is it nesseary to add x:Arguments? or is it nessasary to give reference as
xmlns:local ="clr-namespace:TestProject.Data"

A: Just add class
public class CachedListView : ListView
{
    public CachedListView() : base(ListViewCachingStrategy.RecycleElement) { }
}

And in Xaml use CachedListView instead ListView.


text:
Q: Non linear regression using Xgboost I have a dataframe with 36540 rows. the objective is to predict y HITS_DAY.
#data
https://github.com/soufMiashs/Predict_Hits

I am trying to train a non-linear regression model but model doesn't seem to learn much.
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.20, random_state=42)
data_dmatrix = xgb.DMatrix(data=x,label=y)

xg_reg = xgb.XGBRegressor(learning_rate = 0.1, objectif='reg:linear', max_depth=5,
                          n_estimators = 1000)

xg_reg.fit(X_train,y_train)
preds = xg_reg.predict(X_test)
df=pd.DataFrame({'ACTUAL':y_test, 'PREDICTED':preds})

what am I doing wrong?

A: You're not doing anything wrong in particular (except maybe the objectif parameter for xgboost which doesn't exist), however, you have to consider how xgboost works. It will try to create "trees". Trees have splits based on the values of the features. From the plot you show here, it looks like there are very few samples that go above 0. So making a test train split random will likely result in a test set with virtually no samples with a value above 0 (so a horizontal line).
Other than that, it seems you want to fit a linear model on non-linear data. Selecting a different objective function is likely to help with this.
Finally, how do you know that your model is not learning anything? I don't see any evaluation metrics to confirm this. Try to think of meaningful evaluation metrics for your model and show them. This will help you determine if your model is "good enough".
To summarize:

*

*Fix the imbalance in your dataset (or at least take it into consideration)

*Select an appropriate objective function

*Check evaluation metrics that make sense for your model

From this example it looks like your model is indeed learning something, even without parameter tuning (which you should do!).
import pandas
import xgboost

from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score

# Read the data
df = pandas.read_excel("./data.xlsx")

# Split in X and y
X = df.drop(columns=["HITS_DAY"])
y = df["HITS_DAY"]

# Show the values of the full dataset in a plot
y.sort_values().reset_index()["HITS_DAY"].plot()

# Split in test and train, use stratification to make sure the 2 groups look similar
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.20, random_state=42, stratify=[element > 1 for element in y.values]
)

# Show the plots of the test and train set (make sure they look similar!)
y_train.sort_values().reset_index()["HITS_DAY"].plot()
y_test.sort_values().reset_index()["HITS_DAY"].plot()

# Create the regressor
estimator = xgboost.XGBRegressor(objective="reg:squaredlogerror")

# Fit the regressor
estimator.fit(X_train, y_train)

# Predict on the test set
predictions = estimator.predict(X_test)
df = pandas.DataFrame({"ACTUAL": y_test, "PREDICTED": predictions})

# Show the actual vs predicted
df.sort_values("ACTUAL").reset_index()[["ACTUAL", "PREDICTED"]].plot()

# Show some evaluation metrics
print(f"Mean squared error: {mean_squared_error(y_test.values, predictions)}")
print(f"R2 score: {r2_score(y_test.values, predictions)}")

Output:

Mean squared error: 0.01525351142868279
R2 score: 0.07857787102063485


text:
Q: Replace text inside textarea with js. Why only works first time? I want to replace the text inside a textarea when a button is pressed.
For some reason this only works the first time the button is clicked. How to fix this?
<button id = "the_button">replace text</button> <br>

<textarea id = "textarea"></textarea>

JS:
 $("#the_button").click(function(e) {
       $("#textarea").html("hello world");
});

js fiddle: http://jsfiddle.net/FU4gL/

A: Change
$("#the_button").click(function(e) {
    $("#textarea").html("hello world");
});

to:
$("#the_button").click(function(e) {
    $("#textarea").val("hello world");
});

A: It should be:
$("#the_button").click(function(e) {
  $("#textarea").val("hello world");
});

Fiddle: http://jsfiddle.net/rrikesh/HEPwj/


text:
Q: Hiding divs whenever a new one opens I have a website with two options represented by  tags, chairs and tables. This is the HTML that displays the div whenever a  tag is clicked on.

Living Room

chairs

tables

20 oak logs

20 oak logs

The javascript which handles that function is here:

So what I am trying to do, is that when one of the options are pressed, everything else is hidden and only the div that is assigned that specific  tag will be displayed. When a new  tag is clicked, the old one will be hidden and the new on will be displayed.
I have tried adding a document.getElementsByClassName('refresh').style.display='none'; in hope that every class with "refresh" attached to it, will be put on display:none but this does not work somehow. The outcome is that after a link is clicked, the div is shown. After a new link is clicked, that div is shown too without hiding the old div. Hope you have some suggetions, thanks in advance.
UPDATE:
var length = document.getElementsByClassName('refresh').length;
                for(var i=0; i<length;i++){
                    document.getElementsByClassName('refresh')[i].style.display='none';
                }
                function tables() {
                    document.getElementById('tables').style.display='inline';
                }
                function chairs() {
                    document.getElementById('chairs').style.display='inline';
                }

A: document.getElementsByClassName('refresh') will return you the array of elements.
function tables() {
      hideElements();
      document.getElementById('tables').style.display='inline';
  }
  function chairs() {
      hideElements();
      document.getElementById('chairs').style.display='inline';
  }
  function hideElements(){
    var length = document.getElementsByClassName('refresh').length;
    for(var i=0; i<length;i++){
        document.getElementsByClassName('refresh')[i].style.display='none';
    }
  }


text:
Q: How to get a link that do nothing I have created a search engine using Angular and Bootstrap. I have created different results tab as shown in image  Tabs . Right clicking on tab does not show the option of a link as we get on any link.
link on right click
Currently I am using
 tag and bootstrap to create the tabs of different result section. Here is the code for that

All

Images

Videos

News

            Settings

Search settings

Customization

            Tools

Context Ranking

Sort by Date

Advanced Search

After clicking on the link everything is handled by the functions which get executed on click event. All I want to do that is make that a link, so that user can open it in new tab and state of the app should not change at all. How that is possible? I have tried to do that using routing but things became more complicated. i also followed some answers from here Make a HTML link that does nothing (literally nothing) but they do not work. Please help. I have tried all the answers from there opening link in new tab just disturbs the state of URL.

A: Using  will make the page scroll to the top.
Use javascript:void(0):

Clicking here does nothing

Or equivalently, use javascript:;:

Clicking here does nothing

Or, with HTML5, just omit the href attribute:

Clicking here does nothing

You can use event.preventDefault() to prevent the default action of the link from being taken.

Valid Link

<button id='hitMe'>Disable link</button>

<button id="enable">Enable link</button>

A: By clicking the button, no more links will be followed.
Like this you still have the hover destination preview. Like google.de etc...

document.getElementById('hitMe').onclick = function() { // button click
  [...document.querySelectorAll('a')].forEach(function(el){
    el.onclick = function( e ) { // all 'a'
      return false;
    }
  });
};
Valid Link

<button id='hitMe'>Disable link.</button>

A: use

javascript:;

as href attribute
and add

event.preventDefault()

onclick method.
Click me


text:
Q: Subject to permlink convertion in bash I'm trying to convert user input, which is a subject for a blog entry into a permlink, which is used as URL and file system path.
I managed to do it using:

echo 'This is a used input, containing junk!!!! öäü' | tr -dc '[:alnum:] ' | tr '[:upper:]' '[:lower:]' | tr -s ' ' '-' | sed -e 's/ö/oe/' | sed -e 's/ü/ue/' | sed -e 's/ä/ae/' | sed -e 's/ß/ss/'

Output: this-is-a-used-input-containing-junk-oau
The code absolutely works!
But is there a nicer way to do this without the need to pass the string through this much subcommands?
Task to perform on the string

*

*convert to lowercase

*replace space with "-"

*no multiple "-"

*no special characters, umlauts (covering German umlauts is sufficient, covering all would be a plus)

A: It looks like you're transliterating characters. iconv can handle this:
$ echo 'ö ä ü ß' | iconv -f utf-8 -t ascii//TRANSLIT
oe ae ue ss

This requires your locale to be set to de_DE.UTF-8 (or something similar) to get the results you expect (from your question & profile, I've made the assumption you're dealing with German text).
To set this for just the iconv command, use something like:
$ echo 'ö ä ü ß' | LC_ALL=de_DE.UTF-8 iconv -f utf-8 -t ascii//TRANSLIT

It's also possible you're not using UTF-8 but ISO-8859-1 or ISO-8859-15; consider switching to UTF-8 if possible, or adjust the -f parameter accordingly.
Unfortunately, GNU tr (ie. Linux systems) is stuck in the 7-bit ASCII days(!), and doesn't support converting the case of anything other than a to z (it uses the "xor with 0x20 trick").
Since you are converting your string to 7-bit ascii anyway, we can use tr after iconv for it to work as expected:
echo 'ö ä ü ß' | iconv -f utf-8 -t ascii//TRANSLIT | \
    tr '[:upper:]' '[:lower:]'

I don't see a problem with the other 2 tr invocations; they all do something different. Convert uppercase to lowercase, remove repeating characters, and remove whitespace.
Combining it in one "smart" command might look good now, but maybe not so good for the guy or gal who has to maintain it in 3 years time :-)
Putting it all together, and adding some line breaks, we end up with:
$ echo 'ö ä ü ß' | \
    iconv -f utf-8 -t ascii//TRANSLIT | \
    tr '[:upper:]' '[:lower:]' | \
    tr -dc '[:alnum:] ' | \
    tr -s ' ' '-'

A: You can shorten sed some to:
echo 'This is a used input, containing junk!!!! öäü' | tr -dc '[:alnum:] ' | tr '[:upper:]' '[:lower:]' | tr -s ' ' '-' | sed 's/ö/oe/;s/ü/ue/;s/ä/ae/;s/ß/ss/'

A: Let say you have the following line
This is a used input, *%$^$^%$[]             containing junk!!!! öäü  ÄÜßÖ

using sed command as follows:
sed -r 's/[ ]+/-/g;s/[^[:alnum:]-]+//g;s/-+/-/g;y/üöäÄÜÖß/uoaauob/;s/.*/\l&/g'

trying the above string with this command
 echo 'This is a used input, *%$^$^%$[]             containing junk!!!! öäü  ÄÜßÖ' |sed -r 's/[ ]+/-/g;s/[^[:alnum:]-]+//g;s/-+/-/g;y/üöäÄÜÖß/uoaauob/;s/.*/\l&/g'

results
this-is-a-used-input-containing-junk-oau-aubo

Note: All upper case characters (including upper case umlauts) are lower case as requested.

A: With perl :
#!/usr/bin/perl
use strict; use warnings;
use utf8;
binmode $_, ":utf8" for qw/STDOUT STDIN STDERR/;
use Text::Iconv;
my $converter = Text::Iconv->new("UTF-8", "ascii//TRANSLIT");

while (my $line = <>) {
    $line = $converter->convert($line);
    $line = lc $line;
    $line =~ s/[[:punct:]]//g;
    $line =~ s/\s/_/g;
    print $line;
}

USAGE:
echo 'This is a used input, containing JUNK!!!! öäü' | ./script.pl

OUTPUT:
this_is_a_used_input,_containing_junk_oeaeue