text:
Q: How to remove listview item when the condition is false? I am working on a follow system on flutter.What i want to do is,when the condition is shown false,i want to give a function that does not show  posts[index] item . How can i do it?
PageView.builder(
        scrollDirection: Axis.vertical,
        itemBuilder: (context,index) {
          return FutureBuilder<User>(
              future: callUser(posts[index].author),
              builder: (context, snapshot) {
                if (snapshot.hasError) print(snapshot.error);
                return snapshot.hasData ? (posts[index].isfollowed(snapshot.data.id, user) == true ? Scaffold(...) : //RemoveIndexCondition)  :
Center(child: CircularProgressIndicator(backgroundColor: Colors.pink,valueColor: new AlwaysStoppedAnimation<Color>(Colors.pinkAccent)));
              });
        },
        itemCount: posts.length)

A: Use your code as it is, and add Container() after the :.
yourConditionisTrue ? Scaffold(...) : Container();

A: It is hard to read your code - most IDEs or editors like VS Code will automatically format it to make it read able :)
Here is a version of your code which is nicely formatted. Also I moved the Scaffold moved outside the PageView, as it seemed better. Now what is your requirement?
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('PageView Test'),
      ),
      body: PageView.builder(
          scrollDirection: Axis.vertical,
          itemBuilder: (context, index) {
            return FutureBuilder<User>(
              future: callUser(posts[index].author),
              builder: (context, snapshot) {
                if (snapshot.hasError) print(snapshot.error);
                return snapshot.hasData
                    ? (posts[index].isfollowed(snapshot.data.id, user) == true
                        ? Center(child: Text("Followed"))
                        : Center(child: Text("Not Followed")))
                    : Center(
                        child: CircularProgressIndicator(
                            backgroundColor: Colors.pink,
                            valueColor: new AlwaysStoppedAnimation<Color>(
                                Colors.pinkAccent)));
              },
            );
          },
          itemCount: posts.length),
    );
  }

In order to only show pages for followed posts you can filter the posts list before constructing the PageView:
  Future<List<Post>> followedPosts(List<Post> posts, User user) async {
    var followed = <Post>[];
    for (var post in posts) {
      var postUser = await callUser(post.author);
      if (post.isfollowed(postUser.id, user)) {
        followed.add(post);
      }
    }
    ;
    return followed;
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('PageView Test'),
      ),
      body: FutureBuilder<List<Post>>(
        future: followedPosts(posts, user),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);
          return snapshot.hasData
              ? PageView.builder(
                  itemCount: snapshot.data.length,
                  scrollDirection: Axis.vertical,
                  itemBuilder: (context, index) {
                    return Center(child: Text("Followed"));
                  },
                )
              : Center(
                  child: CircularProgressIndicator(
                      backgroundColor: Colors.pink,
                      valueColor: new AlwaysStoppedAnimation<Color>(
                          Colors.pinkAccent)));
        },
      ),
    );
  }


text:
Q: Reading screen's resolution with QTP In the initialization of my script I would have to read the resolution of the screen so I know how to resize the browser's window size.
Any ideas?
Thanks in advance!

A: Here's some code that can get the resolution for either the primary monitor or all multiple monitors.
Additionally, the last function returns a boolean for whether you have multiple monitors or not.
'*******************************************************************
'TotalScreenWidth & TotalScreenHeight
'by Michael Innes
'October 2012

'Intended for getting the total resolution when you have multiple monitors
'Returns the width and the height (respectively) across all the screens.
Function TotalScreenWidth()
    TotalScreenWidth = Window("regexpwndtitle:=Program Manager").GetROProperty("width")
End Function

Function TotalScreenHeight()
    TotalScreenHeight = Window("regexpwndtitle:=Program Manager").GetROProperty("height")
End Function

'*******************************************************************
'ScreenWidth & ScreenHeight
'by Michael Innes
'October 2012

'Retrieves the width and height (respectively) of the primary screen (the screen that the taskbar is on)
'This only works if the taskbar is at the bottom of the screen
Function ScreenWidth()
    ScreenWidth = Window("object class:=Shell_TrayWnd").GetROProperty("width")
End Function

Function ScreenHeight()
    ScreenHeight = Window("object class:=Shell_TrayWnd").GetROProperty("height") + Window("object class:=Shell_TrayWnd").GetROProperty("y")
End Function

'*******************************************************************
'MultipleMonitors
'by Michael Innes
'October 2012

'Returns a boolean that determines if the computer has multiple monitors attached.

'This only works if the taskbar is at the bottom of the left-most screen.
'If the taskbar is on the right-most monitor, this function will incorrectly report the multiple monitors as being False.
Function MultipleMonitors()
    MultipleMonitors = Eval((screenWidth <> TotalScreenWidth) OR (screenHeight <> TotalScreenHeight))
End Function

A: This is actually quite straight forward, find the desktop window and get its dimensions.
width = Window("text:=Program Manager").GetROProperty("width")
height = Window("text:=Program Manager").GetROProperty("height")
Print width & ", " & height

This works for single monitors, I haven't checked what happens when you have multiple monitors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing axis titles for autoplot Using autoplot from ggfortify to create diagnostic plots:
library(ggplot2)
library(ggfortify)

mod <- lm(Petal.Width ~ Petal.Length, data = iris)
autoplot(mod, label.size = 3)

Is it possible to change the axis and plot titles (easily)? I'd like to translate them.

A: The function autoplot.lm returns an S4 object (class ggmultiplot, see ?`ggmultiplot-class`). If you look at the helpfile, you'll see they have replacement methods for individual plots. That means you can extract an individual plot, modify it, and put it back. For example:
library(ggplot2)
library(ggfortify)

mod <- lm(Petal.Width ~ Petal.Length, data = iris)
g <- autoplot(mod, label.size = 3) # store the ggmultiplot object

# new x and y labels
xLabs <- yLabs <- c("a", "b", "c", "d")

# loop over all plots and modify each individually
for (i in 1:4)
    g[i] <- g[i] + xlab(xLabs[i]) + ylab(yLabs[i])

# display the new plot
print(g)

Here I only modified the axis labels, but you change anything about the plots individually (themes, colors, titles, sizes).

A: The solutions proposed by @user20650 are interesting and elegant.
Here is a less elegant solution based on myautoplot, a modified version of autoplot. I hope it can help you.
Download the myautoplot funtion here and save it in your working directory with the name myautoplot.r.
Then, use the following code:
library(ggplot2)
library(ggfortify)

source("myautoplot.r")
mod <- lm(Petal.Width ~ Petal.Length, data = iris)

####
# Define x-labels, y-labels and titles
####
# Residuals vs Fitted Plot
xlab_resfit <- "Xlab ResFit"
ylab_resfit <- "Ylab ResFit"
title_resfit <- "Title ResFit"

# Normal Q-Q Plot
xlab_qqplot <- "Xlab QQ"
ylab_qqplot <- "Ylab QQ"
title_qqplot <- "Title QQ"

# Scale-Location Plot
xlab_scaleloc <- "Xlab S-L"
ylab_scaleloc <- "Ylab S-L"
title_scaleloc <- "Title S-L"

# Cook's distance Plot
xlab_cook <- "Xlab Cook"
ylab_cook <- "Ylab Cook"
title_cook <- "Title Cook"

# Residuals vs Leverage Plot
xlab_reslev <- "Xlab Res-Lev"
ylab_reslev <- "Ylab Res-Lev"
title_reslev <- "Title Res-Lev"

# Cook's dist vs Leverage Plot
xlab_cooklev <- "Xlab Cook-Lev"
ylab_cooklev <- "Ylab Cook-Lev"
title_cooklev <- "Title Cook-Lev"

# Collect axis labels and titles in 3 lists
xlab_list <- list(resfit=xlab_resfit, qqplot=xlab_qqplot,
      scaleloc=xlab_scaleloc, cook=xlab_cook, reslev=xlab_reslev,
      cooklev=xlab_cooklev)
ylab_list <- list(resfit=ylab_resfit, qqplot=ylab_qqplot,
      scaleloc=ylab_scaleloc, cook=ylab_cook, reslev=ylab_reslev,
      cooklev=ylab_cooklev)
title_list <- list(resfit=title_resfit, qqplot=title_qqplot,
      scaleloc=title_scaleloc, cook=title_cook, reslev=title_reslev,
      cooklev=title_cooklev)

# Pass the lists of axis labels and title to myautoplot
myautoplot(mod, which=1:6, xlab=xlab_list,
                           ylab=ylab_list,
                           title=title_list)

A: library(ggplot2)
library(ggfortify)

mod <- lm(Petal.Width ~ Petal.Length, data = iris)
autoplot(mod,which=c(1:6), ncols=2)    #total 6 plots in two columns
#change axes label & title of plot 1. similarly by changing 'which' parameters count you can label other plots.
autoplot(mod,which=1) +
  labs(x="x-axis label of fig1", y="y-axis label of fig1", title="Fig1 plot")

Kindly don't forget to let us know if it helped :)


text:
Q: Toolbar appears on bottom of the screen and not at top my MDtoolbar appear at the bottom of the screen and not appearing at the top.. I am using python 3.7
from kivymd.app import MDApp
from kivy.lang import Builder

screen_main="""
Screen :
    BoxLayout:
        orientation : "vertical"
        MDToolbar :
            title : "KSFE"

"""
class KSFEApp(MDApp):
    def build(self):
        scr = Builder.load_string(screen_main)
        return scr

if __name__ == '__main__':
    KSFEApp().run()

A: You can add another widget to the BoxLayout (which you probably will do anyways).
For example:
from kivymd.app import MDApp
from kivy.lang import Builder

screen_main = """
Screen:

    BoxLayout:
        orientation: "vertical"

        MDToolbar:
            title: "KSFE"

        MDLabel:
"""

class KSFEApp(MDApp):

    def build(self):
        scr = Builder.load_string(screen_main)
        return scr

if __name__ == '__main__':
    KSFEApp().run()


text:
Q: set Editview watchers only when the input from user? I have 2 fields: dollars and yen.
When i change the dollars field i want to show the converted num in the yen field,and vice versa.
my problem is this:
If i have 2 fields with watchers like:
addTextChangedListener(new TextWatcher()...)

and both doing things to each other the app crashes because when i do a small change on 1 num in the dollars the watcher on the dollars and the yen is working which cause the crash... my solution right now is bad, i remove the listener from the yen when i change the dollars (and when done put the listener back).
Is there any way to only watch for a change via input and not by the default TextWatcher? (if the field changes but not via input, don't do nothing)

A: You can still use TextWatcher#onTextChanged but add a hasFocus() check, so that you only modify the other field if this field has the focus (being updated by user).
    mDollarsText.addTextChangedListener(new TextWatcher() {
        ...
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (mDollarsText.hasFocus()) {
                // show amount in yen
                if (s == null || s.length() == 0) {
                   mYenText.setText("0");
                } else {
                   mYenText.setText(convertDollarsToYen(mDollarsText.getText().toString());
                }
            }
        }
        ...
    });

    mYenText.addTextChangedListener(new TextWatcher() {
        ...
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (mYenText.hasFocus()) {
                // show amount in dollars
                if (s == null || s.length() == 0) {
                   mDollarsText.setText("0");
                } else {
                   mDollarsText.setText(convertYenToDollars(mYenText.getText().toString());
                }
            }
        }
        ...
    });

I'm assuming here that you already have a convenience method for converting dollars<->yen.

A: You can use a boolean Flag and View onFocusChangeListener to achieve it.


text:
Q: "Build step 'Invoke top-level Maven targets' marked build as failure" error Good day! I would like to ask about the error that I'm encountering in Jenkins:

*

*"Build step 'Invoke top-level Maven targets' marked build as failure"

I'm trying to run a selenium script (with JMeter script inside) in Jenkins. I'm getting a BUILD SUCCESS in console output in Jenkins but it marks the job failed because of that error. Kindly see below the console output:
Running TestSuite
Start: 11/04/2016 5:19:29 PM
RawConfigFileScenario3 is created
11/04/2016 5:19:49 PM [PASSED] No Error encountered on the Jmeter Script
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 23.962 sec - in TestSuite

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 48.165 s
[INFO] Finished at: 2016-11-04T17:19:50+08:00
[INFO] Final Memory: 14M/137M
[INFO] ------------------------------------------------------------------------
Build step 'Invoke top-level Maven targets' marked build as failure
Finished: FAILURE

I also tried to run the same script in Eclipse and I'm getting a SUCCESS result. Please see below the logs:
Running TestSuite
Start: 11/04/2016 4:26:26 PM
RawConfigFileScenario3 is created
11/04/2016 4:26:41 PM [PASSED] No Error encountered on the Jmeter Script
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 17.739 sec - in TestSuite

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 37.743 s
[INFO] Finished at: 2016-11-04T16:26:41+08:00
[INFO] Final Memory: 13M/136M
[INFO] ------------------------------------------------------------------------

I would like to ask for your guidance regarding this matter. Thank you in advance for the answers. :)

A: i have encounter this problem. and i just change the sdk configuration from java8 to java7.
hope this can help you.


text:
Q: Joint Probability Density :How does one find the upper and lower bound values in Integration? If the joint probability density of X and Y is given by
$$f(x,y)= \begin{cases}
24xy  && \text{ for } 0 <x<1,0<y<1,x+y<1\\
 0 && \text{elsewhere}\\
\end{cases}$$
$\text{Find } P(X+Y < \frac{1}{2}).$
So for this question one must first draw a graph to show the values

There after one must solve through integration. The problem that I have is determining the lowerbound and upperbound for this problem.
$$\int \int 24xy\text{ dxdy}$$
Also I might have asked this before but for more clarification "elsewhere" basically means the complement?

A: Generally you have two options for $X + Y<0.5$, $0<X<1$, $0<Y<1$. Note that Clearly neither $X$ nor $Y$ can be more than 0.5 because both $X$ and $Y$ are positive and their sum is less than 0.5.
1) Fix $X=x \in [0,0.5]$, then you have $Y+x<0.5$ which means that $Y<-x +0.5$. You also know that $Y>0$. So, $0<Y<-x +0.5$
$$\int_{x=0}^{0.5} \int_{y=0}^{-x+0.5} 24xy\text{ dxdy}$$
2) Fix $Y=y \in [0,0.5]$, then you have $y+X<0.5$ which means that $X<-y +0.5$. You also know that $X>0$. So, $0<X<-y +0.5$
$$\int_{y=0}^{0.5} \int_{x=0}^{-y+0.5} 24xy\text{ dxdy}$$.

A: You have a nice picture of your region.
Do you want to integrate by $x$ first or $y$ first.  In this case, it doesn't matter at all, the region and the function are symmetric.
Lets say we want to integrate with respect to $y$ first and $x$ second.  That seems more traditional.
Draw a line through your region parallel to the $y$ axis (if we were going to integrate with respect to $x$ first we would draw it parallel to the $x$ axis).
What are the endpoints of that line?
One endpoint is $y = 0.$
The other one... it is on the line $x+y = \frac 12$
After we we integrate with respect to $y,$ and apply our limits, we want the $y$'s to disappear.  How do we express the line with $y$ as a function of $x$?
$y = \frac 12 - x$
That is our upper limit!
Now for the $x$ limits.  That is a little easier.  What are the extreme values of $x$? $0, \frac 12$


text:
Q: How to set a 2 custom icon in dataview with bootstrap theme I have the same problem as in this post with one additional complication. I need to put two icons in my dataView, and have them horizontal not vertical.
I can get the icons in there but they do not look correct, as I need them to be horizontally aligned:

 <xe:this.facets>
            <xp:panel xp:key="icon">
                <xp:div id="div1">
                    <xp:this.styleClass>
                        <![CDATA[#{javascript:return "glyphicon glyphicon-arrow-up pull-left"}]]>
                    </xp:this.styleClass>
                    <xp:eventHandler event="onclick" submit="true"
                        refreshMode="complete">
                        <xp:this.action><![CDATA[#{javascript://Do stuff here}]]></xp:this.action>
                    </xp:eventHandler>
                </xp:div>
                <xp:div id="div2">
                    <xp:this.styleClass>
                        <![CDATA[#{javascript:return "glyphicon glyphicon-arrow-down pull-right"}]]>
                    </xp:this.styleClass>
                    <xp:eventHandler event="onclick" submit="true"
                        refreshMode="complete">
                        <xp:this.action><![CDATA[#{javascript://Do stuff here}]]></xp:this.action>
                    </xp:eventHandler>
                </xp:div>
            </xp:panel>
    </xe:this.facets>

A: Since those are divs, they're going to be display: block by default. I'd suggest either adding something like style="display: inline" to the <xp:div/>s or changing them to <xp:panel tagName="i"/>.


text:
Q: Scrolling a Scroll Area in Qt I just have a Scroll Area widget that consists of several Qlabels .
take a look at the situation:

I tried to to do the following but it didn't work out, its doesn't scroll ...
#include "form1.h"
#include "form.h"
#include "ui_form.h"
#include "ui_form1.h"
#include<QScrollArea>
#include<QScrollBar>

Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);
    ui->scrollAreaWidgetContents->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    ui->scrollAreaWidgetContents->resize(ui->scrollArea->size().width() ,ui->scrollArea->size().height());
    ui->scrollArea->setWidgetResizable(true);
    ui->scrollArea->setWidget(ui->scrollAreaWidgetContents);
    ui->scrollAreaWidgetContents->adjustSize();

}

Please Can you tell me what am doing wrong or what am not understanding ??
please be specific , I would appreciate it...

A: Did you apply a layout to the QScrollArea?
In the designer, select the QScrollArea and then click on one of the layout buttons (or press CTRL-L). This may not give you exactly what you want, but if things can then scroll, you know that the layout is the problem.


text:
Q: Django: Accessing a model's field through a another model So I have 2 models:
class Product(models.Model):
    BANANA = 'BAN'
    PRODUCT_CHOICES = (
        (BANANA, 'Banana'),
    )

    name = models.CharField(choices=PRODUCT_CHOICES, max_length=255, default=BANANA)
    shelf_life = models.IntegerField(null=True, blank=True)

class PurchasedOrder(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    purchased_date = models.DateTimeField(auto_now_add=True)
    expired = models.BooleanField(default=False)

GOAL: To get all my purchased orders that are not expired and its purchased date is less than the time now and the product's shelf life.
I tried the following sudo code ish, and I would like to know how to access this PurchasedOrder's product shelf life, as Purchase Order has a Foreign key to Product. I could create some of for loop, but there must be a way to access the product's shelf life field though the PurchaseOrder.
PurchasedOrder.objects.filter(
    expired=False,
    purchased_date__lt=F(datetime.now() - product__shelf_life),
)

I will appreciate your help <3

A: This answer should solve it for you if you're using PostgreSQL.
from datetime import timedelta
from django.utils import timezone

now = timezone.now()
PurchasedOrder.objects.filter(
    expired=False,
    purchased_date__lt=now - timedelta(days=1)*F("product__shelf_life"),
)


text:
Q: Concrete5 Custom Tables Display Data I have a C# programming and WordPress background, but have been unable to get the latest version of WP to accomplish what I need to do. Because of this, I have turned to Concrete5 (version 8.5.4).
I have three custom tables that have been imported into the Concrete5 MySQL database. Now I want to search for partial name or city/state or region/state. The PHP code is already created, all I need to do is create the search and display page using Concrete5.
Because Concrete5 support and tutorials are not as prevalent as those for WP, I am coming up empty in this attempt. Any resource suggestions for developing a search and display page for data residing in custom tables?


text:
Q: android: how to show ProgressDialogFragment in MainActivity I got some problem on code below, when i build the app it show error at the MainActivity side. Below is the code:
ProgressDialogFragment.java
public class ProgressDialogFragment extends DialogFragment
{

    public static ProgressDialogFragment newInstance() {
        ProgressDialogFragment frag = new ProgressDialogFragment ();
        return frag;
    }

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

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        ProgressDialog dialog = new ProgressDialog(getActivity(), getTheme());
        dialog.setTitle(getString(R.string.updatename_loading_title));
        dialog.setMessage(getString(R.string.updatename_loading_message));
        dialog.setIndeterminate(true);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        return dialog;
    }

}

MainActivity.java
public void doPositiveClick(DialogFragment dialog) {
                Dialog dialogView = dialog.getDialog();
                EditText editName = (EditText) dialogView.findViewById(R.id.editName);
                String updateName = editName.getText().toString().trim();
                    login.setName(updateName);
                    new HttpAsyncTask().execute(uNameUrl);
                    dialogView.dismiss();
            }

        private class HttpAsyncTask extends AsyncTask<String, Void, String> {

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                   progressDialog.show(MainActivity.getFragmentManager(),"loading");
                }

                @Override
                protected String doInBackground(String... urls) {

                    // Do Action Here
                }
    }

I want to show loading after submit, but got error at line below:
progressDialog.show(MainActivity.getFragmentManager(),"loading");

Error Message below show after i build the app.
Error:(216, 45) error: non-static method getFragmentManager() cannot be referenced from a static context

How can i fix this?
Thanks
@Edit
I fixed the first error, i just forgot to add this on ProgressDialogFragment.java
@Override
    public void show(FragmentManager manager, String tag) {
        if (manager.findFragmentByTag(tag) == null) {
            super.show(manager, tag);
        }
    }

for prevent duplicate dialog when rotate the mobile.
Now it got second error
Error:(40, 5) error: method does not override or implement a method from a supertype
Error:(43, 18) error: no suitable method found for show(android.app.FragmentManager,String)
        method DialogFragment.show(android.support.v4.app.FragmentManager,String) is not applicable
        (argument mismatch; android.app.FragmentManager cannot be converted to android.support.v4.app.FragmentManager)
        method DialogFragment.show(FragmentTransaction,String) is not applicable
        (argument mismatch; android.app.FragmentManager cannot be converted to FragmentTransaction)

A: You are call outer class method in inner class, you should change MainActivity.getFragmentManager() to MainActivity.this.getFragmentManager()

A: I fixed the problem:
ProgressDialogFragment.java
public class ProgressDialogFragment extends DialogFragment
{

    public static ProgressDialogFragment newInstance() {
        ProgressDialogFragment frag = new ProgressDialogFragment ();
        return frag;
    }

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

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        ProgressDialog dialog = new ProgressDialog(getActivity(), getTheme());
        dialog.setTitle(getString(R.string.updatename_loading_title));
        dialog.setMessage(getString(R.string.updatename_loading_message));
        dialog.setIndeterminate(true);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        return dialog;
    }

}

MainActivity.java
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        ProgressDialogFragment progressDialog = new ProgressDialogFragment();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show(getFragmentManager(), "loading");
        }

        @Override
        protected String doInBackground(String... urls) {

            return UpdateData(MainActivity.this, urls[0], login);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            progressDialog.dismiss();
            startActivity(new Intent(getApplicationContext(), MainActivity.class));
            finish();
              Log.d("posted", result);
            Toast.makeText(getBaseContext(), "Display Name Successful Changed!", Toast.LENGTH_LONG).show();
        }
    }

First Question about
Error:(216, 45) error: non-static method getFragmentManager() cannot be referenced from a static context

I fixed by @Gennadii Saprykin and handrenliang with below code:
progressDialog.show(MainActivity.getFragmentManager(),"loading");

to
progressDialog.show(MainActivity.this.getFragmentManager(),"loading");

The second error :
Error:(216, 27) error: no suitable method found for show(android.app.FragmentManager,String) method DialogFragment.show(android.support.v4.app.FragmentManager,String) is not applicable (argument mismatch; android.app.FragmentManager cannot be converted to android.support.v4.app.FragmentManager) method DialogFragment.show(FragmentTransaction,String) is not applicable (argument mismatch; android.app.FragmentManager cannot be converted to FragmentTransaction)

is fixed by @handrenliang with below:
used android-v4 DialogFragment, but your activity is not v4, you can import non v4 DialogFragment in your ProgressDialogFragment.
import android.support.v4.app.DialogFragment;

to
import android.app.DialogFragment;

and last error that crash, i just move the dialog declaration from MainActivity Class to inside HttpAsyncTask Class.
ProgressDialogFragment progressDialog = new ProgressDialogFragment();

Thanks @Gennadii Saprykin and @handrenliang
For the help.


text:
Q: Unit testing Mybatis response using mockito and junit I have below piece of code in my project.
@Qualifier("EmployeeServiceMapper")
EmployeeServiceMapper mapper;

public EmployeeResponse getEmployeeData(String id,String department){

       EmployeeResponse response = new EmployeeResponse();

       Map<String,Object> requestMap = new HashMap<>();
       requestMap.put("id", id);
       requestMap.put("dept", department);

       //connect to db stored procedure
       mapper.getEmployeesList(requestMap);

       //List from cursor response
       response.setEmpList((List<Employee>) requestMap.get("employeesList"));
       response.setDeptInfo((Department) requestMap.get("departmentDetail"));

       return response;

    }

Mapper Interface:
public interface EmployeeServiceMapper {
    void getEmployeesList(Map<String,Object> map);
}

Junit:
I would like to write unit test cases like checking if the data is populated in both empList and deptInfo. I am not sure how to write with Mockito. Can someone kindly help pls
@Test
void testEmployeeData(){

    doNothing().when(mapper).getEmployeesList(anyMap());

    //how can I mock the mapper responses here i.e., requestMap.get("employeesList"))

}


text:
Q: lighttpd and vtiger setup I am trying to setup vTiger CRM with lighttpd, but I have faced some problems.
I have configured a postgreSQL database devoted to vTiger.
I have downloaded the source and copied that in my /var/www/vtigercrm
when I try to access localhost/vtigercrm, php warns me with some errors like:
Warning: include(config.inc.php): failed to open stream: No such file or directory in /var/www/html/vtigercrm/config.php on line 21

Warning: include(): Failed opening 'config.inc.php' for inclusion (include_path='.:/usr/share/php') in /var/www/html/vtigercrm/config.php on line 21

Warning: include_once(include/Webservices/Relation.php): failed to open stream: No such file or directory in /var/www/html/vtigercrm/index.php on line 14

and warnings go on!
and at last a fatal error destroys everything:
 Fatal error: require_once(): Failed opening required 'include/logging.php' (include_path='.:/usr/share/php') in /var/www/html/vtigercrm/include/database/PearDatabase.php on line 16

IT IS SOLVED
For others who may have the same problem, it is a good idea to change error displaying settings in php.ini file to E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_WARNING & ~E_NOTICE while you are installing vTiger. Then you can revert the changes.
It is due to the fact that if you send something to browser output, you cannot manipulate the headers anymore; sending output is done by error_display while installation wizard tries to modify some http headers.


text:
Q: How to sort data by using for loop? I am wondering that how to use a loop (may be a for loop) to sort data like following.
      [,1]
 [1,]  179
 [2,]  160
 [3,]  136
 [4,]  227
 [5,]  217
 [6,]  168
 [7,]  108
 [8,]  124
 [9,]  143
[10,]  140

I tried to use a loop like this:
for (i in 1:nrow(v)) {
for (j in i+1:nrow(v)) {
if (v[i] > v[j]) {
v[i] <- v[j]
}
else {
v[i] <- v[i]
}
}
}
v

But finally a error message turned out :/
Error in if (chickwts[i, 1] > chickwts[j, 1]) { :
  missing value where TRUE/FALSE needed

I know that this is very simple by using order to do it, but as a beginner of R, I am curious how to do this by loop.  Hope someone can help.  Thank you!

A: The short answer is don't, because sort.list implements a number sorting algorithms more efficiently using internal, well optimised  code.
You need to decide on the sorting method you wish to use.
See this wikipedia artile  for a good summary.
Each of the sorting algorithms have psuedocode which can be translated to R
Here is an implementation of a bubbleSort, implementing the pseudocode from here
procedure bubbleSort( A : list of sortable items )
   repeat
     swapped = false
     for i = 1 to length(A) - 1 inclusive do:
       /* if this pair is out of order */
       if A[i-1] > A[i] then
         /* swap them and remember something changed */
         swap( A[i-1], A[i] )
         swapped = true
       end if
     end for
   until not swapped
end procedure

In R this would look something like
set.seed(1)
A <- sample(10)
A

##  [1]  3  4  5  7  2  8  9  6 10  1

n <- length(A)

repeat {
    swapped = FALSE
    for (i in 2:length(A)) {
        newA <- A
        if (A[i - 1] > A[i]) {
            newA[i - 1] <- A[i]
            newA[i] <- A[i - 1]
            A <- newA
            swapped <- TRUE
        }
    }
    if (!swapped) {break}
}
# ta da!
A

##  [1]  1  2  3  4  5  6  7  8  9 10


text:
Q: Div contents don't float left as they should I have the following markup for a div of content that's being dynamically pulled from a .json file:

And the following CSS that applies to this div:
div.table_container {
        background-color: #a9c7e1;
        width: 100%;
    }

    p.table_img_p {
        background-color: #0090c3;
        color: #FFFFFF;
        margin: 0;
        padding: 0.5em;
    }

    .table_img_list {
        padding: 0.5em;
    }

@media only screen and (min-width: 720px){
    div.subSection {
        width: 100%;
    }

    div.subSection_content {
        width: 100%;
    }

    div.table_container {
        width: 50%;
        float: left;
    }
}

And here's what's it giving me instead of floating the divs to the left. It treats the elements within that div as individual divs. >.< Clearing anything at all doesn't help. Suggestions?

And here's the output code (HTML). Nothing odd going on in CSS.

One way that toxicity can be measured is by its specific effect on an organ or organs. The kidneys and liver are most commonly associated with toxicity because of their primary roles in metabolism, detoxification, and excretion. However, all body organs can be affected including the skin, brain, heart, lungs, and gastrointestinal organs.

Symptoms of Liver Damage

Jaundiced skin or eyes

Abdominal pain

Nausea

Discolored or bloody waste secretions

Fatigue

Anorexia

Symptoms of Kidney Damage

Hypertension

Nausea

Edema

Fatigue

Anorexia

Change in urine output

Chest pain and shortness of breath

What's wanted: on mobile it should be 1 column (two blue boxes one under the other), and on larger views it should be two columns (two blue boxes next to each other). I've done styling of this kind of thing many times before and never had such difficulty styling it. Just looking for suggestions on what is going on that it doesn't want to float on "1 line" next to each other.

A: Add `float:left' in css as follows
    div.subSection_content {
            width: 100%;
            float:left;
        }

complete code:-
div.table_container {
            background-color: #a9c7e1;
            width: 100%;
        }

        p.table_img_p {
            background-color: #0090c3;
            color: #FFFFFF;
            margin: 0;
            padding: 0.5em;
        }

        .table_img_list {
            padding: 0.5em;
        }

    @media only screen and (min-width: 720px){
        div.subSection {
            width: 100%;
        }

        div.subSection_content {
      width: 100%;
      float: left;
        }

        div.table_container {
            width: 50%;
            float: left;
        }
    }

A: NOTE: OP has updated question with visual example since this answer was provided.
You haven't given a clear definition of what you'd like to achieve but I'll take a stab at it.
I'm going to assume the following:

*

*That the light blue DIV should be under the darker blue DIV.

*That the darker blue DIV is the header for the light blue DIV.

*That each dark blue DIV and light blue DIV will be treated is one item/gropu/etc.

*That on smaller screens the Liver Damage group appears above the Kidney Damage group.

*That on larger screens the Liver Damage group appears to the left of the Kidney Damage group.

If so, then the issue is the way you're conditionally outputting your content/markup. The template doesn't match the output markup you've provided. Each header is nested in the same set of DIVs as its associated content.

I would expect to see something like this if my assumptions are correct:

Which match your template but not output markup. This would get you the results you are looking for with the supplied CSS, http://jsfiddle.net/kqwpheh9/. The jsFiddle doesn't include any spacing between the lists, you'll have to include that later.
It appears your .table_container and .subSection_content DIVs might be redundant, among other markup considerations.


text:
Q: Bootstrap 4 - Achieve flex + justify-content-center with 2 elements With utilising d-flex, justify-content-center and flew-grow-1, I achieved the desired result with 3 divs.

      LEFT

      Middle

      Right

I want to achieve the same effect with 2 divs while Middle one is forced to be the exact center. However, if I try to remove the 'Right' element, it can't calculate the center.

      LEFT

      Middle

Is there a way to force "Middle" to be exact center and Left or Right divs take space from Middle as they need? Kind of like all the positions of Left and Middle are same as in the first image but 'Right' div is not there.
Fiddle http://jsfiddle.net/4a7tLf0m/

I can achieve the same effect with giving specified column size (col-3 instead of col-auto) but I don't like the fact that I need to be explicit. Is this the only way to go?

A: Keep the right/left div as invisible when not required. That way middle will always occupy the exact same position as when the other 2 divs are not there.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

      LEFT

      Middle

      Right

      LEFT

      Middle

      Right

      LEFT

      Middle

      Right


text:
Q: How can I assign weights to coins so that they can be counted in a single weighing? I was sorting out the coins in my loose-change jar the other day, and the following thought crossed my head:  Is it possible to deduce the number of each type of coin in this pile by simply weighing them?
The coins I were counting were Australian 5c, 10c, 20c and 50c.  According to Wikipedia, they weights are:
5c     2.83 grams
10c    5.65 grams
20c   11.30 grams
50c   15.55 grams

But this might be a particularly bad choice of weights for the coins.  Since 565 divides 1130, we can't tell the difference (through weighing) between two 10c coins and one 20c coin.  It seems that two 5c coins and one 10c coin would be hard to distinguish also.
So my question is:

Question: What would be a better way to designate the weights of these coins so that we could (in most cases) uniquely determine the number of each type of coin in a single weighing?

This would be subject to some practical constraints:

*

*Each coin is a reasonably light, but not too light (e.g. between 2 and 20 grams).

*If A and B are two multisets of coins, and A and B have equal weights, then |A| and |B| should be very large (more than is likely to be in a typical jar).

*The scales do not measure with infinite precision.  Coins are not minted with infinitely accurate weights.

*The weights of the coins must differ by a reasonable amount (e.g. by at least 3 grams).

A: A small observation.  For two coins let's suppose we arbitrarily fix the precision at somewhat better than one gram, so let's make the weights $w_1, w_2$ positive integers.  Then the way to minimize redundancy is to require that the weights $w_1, w_2$ are relatively prime.  This is to maximize the size of the smallest nontrivial solution to $w_1 x + w_2 y = 0$.  Within the constraints you describe this means we should take $w_1 = 17, w_2 = 20$; then we can decide the number of coins unambiguously up to the point where we have either $20$ of the first coin or $17$ of the second.
If we up the precision to somewhat better than a tenth of a gram then we should instead take something like $w_1 = 16.9, w_2 = 20$; then I think we can decide the number of coins unambiguously up to the point where we have either $200$ of the first coin or $169$ of the second, which is surely good enough for all practical purposes.  So it seems to me that the answer to the problem depends strongly on what precision we can measure weights to.

A: I am neither a mathematician nor particularly good at maths but here is my 'pennyworth' on the problem.
(1) Weighing the same denomination coins (assuming they are the same 'model') is extremely accurate with a reasonable digital scale. Once one is weighing upwards of twenty or thirty coins, the likely deviation from the true number of coins drops dramatically (thanks to the wonders of The Central Limit Theorem). I have used this approach to take inventories of paper work sets and I was surprised by just how accurate the item counts were using a cheap digital scale weighting up to 10 kilogrammes and with an accuracy of +/- one tenth of a gram. I had a weight to number conversion calculation in a spreadsheet but obviously a purpose-made scale 'would incorporate the conversion on a chip. There should be scope for 're-calibration' given that coins change.
(2) With a mixed bag of coins, it strikes me that no matter how cunningly one might design the coin weights, the more coins one had, the greater the number of possible weight combinations. At some point, these would 'eat into' the maximum accuracy range of the balance. If this is so (and this is only my intuition, this should be proven or disproven), then this would suggest a maximum number of coins that could be weighed at any one time. It could be objected that prime numbers solve this problem but if we think of the scale's accuracy as defining a minimum measurable number space, I suspect that populations of high primes or combinations with even relatively few primes could fall in the same number space and not be discriminated. Again, it would take a mathematician to show whether this intuition is grounded or foundless.
[P.S. Reading the foregoing posts more carefully, I see that Qiochu has already found the upper bound for a given set of weights]. This suggests another approach, namely, batching mixed coins into maximum number of coins or total weight and then weighing (and thus accurate counting) using Qiochu's system.
(3) One also should think of practicalities:
 (a) At the moment, coin weights are not designed for counting by weight.
 (b) Most people I have seen counting coins do so from a till in which the coins have already been sorted into denominations. This suggests that in the real world, the approach in the first paragraph is the best one.
(4) A fourth reflection is that with the advent of cash cards, 'money' cards, smart phone apps and other 'virtual purse' solutions, maybe the problem of counting coins is one that will not be with us for much longer. Perhaps coins could also be made another way, incorporating a passive (secure and non-rewritable!) RFID tag to 'tell' counting machines what denomination they are.


text:
Q: HA NameNode exits unexpected with Error replaying edit log at offset. Expected transaction ID was xxxx 2 HA Namenode exits at the same time, can't restart after. The error log is:
org.apache.hadoop.hdfs.server.namenode.EditLogInputException: Error replaying edit log at offset 95968824.  Expected transaction ID was 2615482563
Recent opcode offsets: 95968192 95968425 95968658 95968824
Please help me...
I tried restart the namenode with cdh, but not work.


text:
Q: How to direct (Python) error messages printed in a PowerShell console to a text file Firstly, the errors I'm interested in redirecting are NOT PowerShell errors, but those generated by a Python script that is called within my PowerShell script. I have read multiple post on here (and other StackExchange sites, Windows PowerShell scripting guy article, and various other locations. This has lead me to develop the script as it is below, but the output is somewhat odd.
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"

$SnapsToTest = Get-ChildItem C:\Snaps\ -Directory
$ErrorFile = "C:\Tools\Scripts\Errors.txt"
$SnapDir = "C:\Logs"
$LogDir = "\var\log\"
$LogFile = "support.log"
$env:PYTHONIOENCODING="UTF-8"

Start-Transcript -path $ErrorFile
Push-Location
Set-Location -Path $SnapDir

$SnapsToTest | ForEach-Object {
        Write-Host $_.Name
        python C:\Tools\Scripts\script1.py $_.Name
        $LogToTest = $_.Name+$LogDir+$LogFile
        python C:\Tools\Scripts\script2.py $LogToTest
    }

Pop-Location
Stop-Transcript

Now, if I run script using .\myscript.ps1 > output.text I almost get what I'm after, but not quite.
I end up with two files, output.text and errors.txt.
The Output Text shows all the output generated by the Python script. The Errors Text file shows SOME of the output written to the screen, but not if the Python script crashes an writes out its stack trace, however I DO see this in the terminal, and this I do not understand.
For example, the output I see in the error text file is:
**********************
Windows PowerShell transcript start
Start time: 20160429160228
Username: PC\me
RunAs User: PC\me
Machine: PC(Microsoft Windows NT 10.0.14328.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Process ID: 16844
PSVersion: 5.1.14328.1000
PSEdition: Desktop
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.14328.1000
CLRVersion: 4.0.30319.42000
BuildVersion: 10.0.14328.1000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1
**********************
SnapDir1
SnapDir2
SnapDir3

However, what I see in the console is:
C:\Tools\Scripts> .\myscript.ps1 | Out-File output.txt
SnapDir1
SnapDir2
Traceback (most recent call last):
  File "C:\Tools\Scripts\script1.py", line 446, in <module>
    main(sys.argv[1])
  File "C:\Tools\Scripts\script1.py", line 436, in main
    dba = DBAnalyser(rootdir)
  File "C:\Tools\Scripts\script1.py", line 54, in __init__
    self.osstatus = self._read_osstatus(osstatus_file)
  File "C:\Tools\Scripts\script1.py", line 170, in _read_osstatus
    ret[hostname]["meminfo"] = { "memtotal": memtotal, "memfree": memfree}
UnboundLocalError: local variable 'memtotal' referenced before assignment
SnapDir3

I can't see how to get the above error I see in the PowerShell console to show in the Errors.txt file
This is running in Windows 10 Pro 64 bit.


text:
Q: Probability of a random variable as a function given a CDF I have a cumulative function/cdf defined as follows, where $X$ is a random variable:
$\ F_X(x) = \left\{\begin{aligned}
&0 &&: x \le 0\\
&1-e^{-x} &&: x > 0
\end{aligned}
\right.$
How would I go about solving $P(0 \le e^X \le 4) $ ?
I understand that if we are given a probability range and a CDF we can find the probability as follows:
$P(a \le X \le b) =F_X(b)-F_X(a)$
Would I just need to do some simplification like taking the natural log of both sides of the range of the probability?

A: We know that $e^X \geq 0$, the event $e^X \leq 4$ is equivalent to  $X \leq \ln 4$, hence
$$P(0 \leq e^X \leq 4)= P(X \leq \ln 4)=F_X(\ln 4) = 1- \exp(-\ln 4)=\frac34$$

A: $P(0 \le e^X \le 4) = P(e^X \le 4) = P(X \le \ln 4) = F(\ln 4)$


text:
Q: Tensorflow Dataset Titanic import problems I'm lost as to how to import Tensorflow 2's built in datasets. Their docs aren't very intuitive and I'm used to working with csvs.
How do I get the 'Titanic' dataset to work with the basic model?
is there a good resource to learn Tensorflow's API for pipelining their datasets?
for the below code I get the error: ValueError: Layer sequential_54 expects 1 inputs, but it received 13 input tensors
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras.optimizers import Adam

data = tfds.load("titanic",split='train', as_supervised=True).map(lambda x,y: (x,y)).batch(10)

model = tf.keras.models.Sequential([tf.keras.layers.Dense(2,activation='relu'),
tf.keras.layers.Dense(13, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')])

model.compile(optimizer=Adam(learning_rate=0.01), loss='categorical_crossentropy', metrics=
['accuracy'])

model.fit(data,epochs=30)

A: The import of data seems to be correct, but you are using categorical_crossentropy which naturally needs one-hot encoded labels (targets), which can be generated using:
from keras.utils import to_categorical

labels = to_categorical(labels)

But for two class (binary) problem, you need to use binary_crossentropy and you can still maintain your dense layer:
tf.keras.layers.Dense(1, activation='sigmoid')])

Lastly, you need to add the labels (targets) here to train the network and possibly add batch size
model.fit(data, labels, epochs=30, batch_size=80)


text:
Q: Thinkpad t60 crashes I have a new (to me) thinkpad t60.
Often, if I unplug it while it is running, it re-boots and gives the message, "System has recovered from a serious error".
Why is this happening and what can I do about it?
XP Pro SP3, 3 gig ram
EDIT:
I am waiting to have the store where I bought it fix this problem. Scheduling problems have made this take a long time. I will report the solution as soon as I am able to solve it. Thanks for all the responses.
EDIT: I took it back to the retailer to have him try and fix the problem.
It is his opinion that the IBM power monitor / battery utility is the problem, as stated by Wil, below, and it has been removed. He then had no occurrences of the problem over a period of numerous tests. I am going to do some testing over the next 24 hours and will report what happens.
EDIT: The tech uninstalled the IBM power monitor / battery utility, as suggested and then updated all thinkvantage. His take is that it was caused by the BM power monitor / battery utility, as suggested. It seems fine. Thanks.
Thanks.
EDIT: Well, the store took the T60 14") back. He couldn't stop it from crashing. I have had it replaced with the 15" inch, still have all the software from Thinkvantage installed, and for the last few days have had no problem/. (How do you make the emoticon for fingers crossed? X?

A: A friend had this issue on a T60 when he recently installed a Windows Update.
Uninstall the IBM power monitor / battery utility.
They have not released an update yet. Removing this program fixed the crash on my friend's laptop.

A: Sounds like a bad battery or other hardware fault. Does the laptop work without the charger at all? The error specified is a result of the machine unexpectedly being turned off (usually from sudden power loss or crash) because the Mini-Dump file is written, but the paging file still thinks it hasn't been. You can try the paging file workaround here, but I've heard this problem with laptops a few times before and it's been hardware related mostly.

A: Have you tried going to IBM and getting the newest patches. I was getting a Blue screen on my T42 every so often, as it turns out after a bit of investigation I was having a wireless driver problem. I found this by following the windows error messagebox. I am not saying that you are having a wireless problem just giving a sugestion that you may want to read a bit further into the error screen and perhaps download some drivers from IBM.


text:
Q: Datanucleus enhancer not working with appengine At the moment I am working on a webapplication written in Java, using Spring, JPA, AppEngine and Datanucleus. It all worked well, until last week when all of a sudden nothing would compile anymore (not even older versions on SVN).
The versions I am using at the moment are:

*

*datanucleus: 3.2.5

*appengine: 1.8.1

*datanucleus-appengine: 2.1.2

*datanucleus-jpa: 2.1.8

*datanucleus-api-jpa: 3.3.0-m1

*datanucleus-maven-plugin: 3.3.0-m1

Together with some other dependencies, however I think the ones in the list are the most important ones. Everything is compiled using Maven. When I run maven clean install or maven datanucleus:enhance the enhancer crashes:
[ERROR] --------------------
[ERROR]  Standard error from the DataNucleus tool + org.datanucleus.enhancer.DataNucleusEnhancer :
[ERROR] --------------------
[ERROR] Exception in thread "main" java.lang.NoSuchMethodError: org.datanucleus.metadata.MetaDataManager.getOMFContext()Lorg/datanucleus/OMFContext;
        at org.datanucleus.jpa.metadata.JPAAnnotationReader.processClassAnnotations(JPAAnnotationReader.java:199)
        at org.datanucleus.metadata.annotations.AbstractAnnotationReader.getMetaDataForClass(AbstractAnnotationReader.java:126)
        at org.datanucleus.metadata.annotations.AnnotationManagerImpl.getMetaDataForClass(AnnotationManagerImpl.java:171)
        at org.datanucleus.metadata.MetaDataManager.loadAnnotationsForClass(MetaDataManager.java:2757)
        at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:1015)
        at org.datanucleus.enhancer.DataNucleusEnhancer.getFileMetadataForInput(DataNucleusEnhancer.java:796)
        at org.datanucleus.enhancer.DataNucleusEnhancer.enhance(DataNucleusEnhancer.java:513)
        at org.datanucleus.enhancer.DataNucleusEnhancer.main(DataNucleusEnhancer.java:1281)

[ERROR] --------------------

It also gives some other errors:
Extension Point "org.datanucleus.implementation_creator" not registered, but plugin "org.datanucleus.enhancer" defined in file:/D:/FBLAAUW/.m2/repository/org/datanucleus/datanucleus-enhancer/3.1.1/datanucleus-enhancer-3.1.1.jar refers to it.

and several of the following errors (approx 100)
ERROR DataNucleus.Persistence  - User-defined type mapping class "org.datanucleus.store.types.sco.simple.Collection" was not found. Please check the mapping file class specifications and your CLASSPATH. The class must be in the CLASSPATH.

I am using JRE 1.7, but I also tried using JRE 1.6 (which also did not work). My guess is that the used versions are not compliant with each other, but I am not sure. Does anyone have an idea on this?

A: Suggest you sort out the versions of jars being used. This page states the compatibility of Googles "datanucleus-appengine" with DataNucleus project jars


text:
Q: Capistrano on Windows: 'cap deploy' defaults to wrong username I am trying to use Capistrano to connect over ssh with svn in order to deploy an app to prod from a windows dev box (Aptana Studio Community Edition). When I run 'cap deploy' it starts executing tasks in deploy.rb, then it asks for a password for user account 'a' but I need to connect using account 'b' not 'a'. User account 'a' has no root privileges on the linux box that I am trying to connect. It seems that svn picks up a default username.
Does any know what's going on? is svn picking up Windows username? in deploy.rb i tell it to connect with user account 'b' with password 'bb'.

A: Capistrano on Windows is a huge pain in the neck. I only moved back to it when I shifted my development environment to Linux.
Anyway, here's some things to try...

*

*If you enter a blank password, does it prompt for a username?

*I'm unclear whether it is the svn or shell username that's wrong but either way you can use these in your deploy.rb file:
set :scm_username, "your svn username"
set :scm_password, "your svn password"
set :user, "your linux user"


text:
Q: R : Creating a RESTful API for given R script that takes in parameters and returns a calculated value via a GET call I have an R script that takes in arguments and returns a float value based on this input. I need to convert it into a RESTful API so that it can be accessed via a URL GET call.
I have looked into the same and came across some very promising looking alternates - Plumber , OpenCPU and Jug. However I need a solution that will be robust and stable ( I am expecting almost 150 thousand calls in 10 mins as of now - might move towards real time so will be a bit relaxed than this) . Kindly help me answer the following questions :

*

*How to make a webservice that won't crash on production in case of hige traffic?

*How else can I call an Rscript logic from a JAVA web service without making them tightly coupled? (The script has barely 15 LOC)

*Is there a performance difference when it comes to making RESTful API in R v/s that in Python ?

Please direct me to anything that will help me understand this in the right manner.
I am very new to the concept of web services so I apologize in advance in case I asked stupid questions.


text:
Q: How to explicitly launch the stock launcher from my activity? Platform: ASUS Nexus 7, running JellyBean

I've created a kiosk application by making it the default HOME / LAUNCHER intent. I need to be able to get out of it, to the stock android launcher, via a secret code for service and maintenance.
I've searched all over, and can't find a good, succinct answer. The best I've come up with is to create an intent chooser (Intent.createChooser(Intent i, String title)) and choose between my launcher and the stock launcher. This is okay, but really a workaround.
I've tried:
PackageManager pm = this.getPackageManager();

try {
    Intent i = pm.getLaunchIntentForPackage("com.android.launcher");
    if (i != null)
        this.startActivity(i);
}
catch (ActivityNotFoundException e) { }

and I get null for the intent every time. Yet, the stock launcher shows a package of "com.android.launcher" on my tablet. Clearly I'm getting something totally wrong here.

A: Step #1: Document that they need to run your app manually once out of the launcher before setting it up as the home screen.
Step #2: On that first run, use resolveActivity() to find out what the default home screen is, and hold onto the relevant pieces of information from the ResovleInfo (e.g., the component name) in some persistent data store.
Step #3: Use that data to bring up the default home screen as needed from whatever back door you have in your kiosk app.


text:
Q: Unable to align radio buttons and their labels in one line Below is a snippet of the appearance of current page.
Radio buttons and their labels not in single line
Below is the piece of code is being used. (JSP)

   *<fmt:message key="registration.agreement"/>

      <input id="termsAgree-Y" class="x-form-field" type="radio" value="Y" name="termsAgree"> <fmt:message key="registration.yes"/>

      <input id="termsAgree-N" class="x-form-field" type="radio" value="N" name="termsAgree"> <fmt:message key="registration.no"/>

I have tried using inline styling like
display: inline!important;

with input and label tags but nothing is working.
While checking in Chrome Developer mode, I came across an extra attribute that was getting appended in the input tags of both the radio buttons and I am unable to figure out from where it is coming.
element.style {
    display: block;
}

Can someone please suggest way to override all existing stylings that are getting implemented on this element, so as to bring the radio buttons and their labels in one line. I am new to front-end part, so please help me out. Also, help me find the origin of this styling (Can it be found using Chrome Developer tool)

A: Just write after fmt

      <fmt:message key="registration.yes" />Yes

i think it will work.

A: You did that wrong. You missed the right name.
change it into display:inline-block;
In the example below I used it onto the div's. But this css will work on every element you want.

div{display:inline-block;}

   * Subject<fmt:message key="registration.agreement"/>

      <input id="termsAgree-Y" class="x-form-field" type="radio" value="Y" name="termsAgree"> <fmt:message key="registration.yes"/>Yes

      <input id="termsAgree-N" class="x-form-field" type="radio" value="N" name="termsAgree"> <fmt:message key="registration.no"/>No

A: An easy way to fix this would be to simply add "float: left" to the radio buttons.
<input style="float:left" id="termsAgree-N" class="x-form-field" type="radio" value="N" name="termsAgree">
<fmt:message key="registration.no"/>

This means you don't need to worry about changing to display:inline-block. This snippet demonstrates that it works even when the radio buttons are set to display:block.

  <input type="radio" style="display:block;" />
  without float:left

  <input type="radio" style="display:block; float:left" />
  with float:left

This is a picture of before and after:


text:
Q: Where can I find previous versions of Azure Service Fabric SDKs? I need to find older SDK versions of Azure Service Fabric SDK (2.1.163 to be precise). It is no longer available on Web Platform Installer and couldn't find it anywhere else too.
Can someone please point me to that?
Many thanks!

A: These are the links. Install in this order:

*

*Runtime:
http://download.microsoft.com/download/C/9/6/C9680A4C-291F-4A6F-B699-26FF704577BA/MicrosoftServiceFabric.5.1.163.9590.msi

*SDK:
http://download.microsoft.com/download/C/9/6/C9680A4C-291F-4A6F-B699-26FF704577BA/MicrosoftServiceFabricSDK.2.1.163.msi

*VS Tools:
http://download.microsoft.com/download/E/7/6/E76A0B84-6DAB-4734-85E2-5912A1130FB4/MicrosoftAzureServiceFabricTools.VS140.en-us.msi


text:
Q: What causes this Page Not Found error in my Codeigniter 3 application? I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.
I have added a registration and login system to this application. I am current working on a password reset system.
In the Changepasword controller, the index method takes the parameters $email and $token:
public function index($email, $token) {
    $data = $this->Static_model->get_static_data();
    $data['pages'] = $this->Pages_model->get_pages();
    $data['tagline'] = 'New password';
    $data['categories'] = $this->Categories_model->get_categories();

    // Form validation rules
    $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
        $this->form_validation->set_rules('cpassword', 'Confirm password', 'required|matches[password]');
    $this->form_validation->set_error_delimiters('
', '
');

    if(!$this->form_validation->run()) {
        $this->load->view('partials/header', $data);
        $this->load->view('auth/newpassword');
        $this->load->view('partials/footer');
    } else {
        $this->Usermodel->set_new_password($email, $token);
    }
}

In the routes file I have this line for the above controller:
$route['changepasword/(:any)/(:any)'] = 'changepasword/$1/$2/';

The entire routes file:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$route['default_controller'] = 'posts';
$route['install'] = 'install';
$route['migrate'] = 'migrate';
$route['register'] = 'register';
$route['login'] = 'login';
$route['newpassword'] = 'newpassword';
$route['changepasword'] = 'changepasword';
$route['changepasword/(:any)/(:any)'] = 'changepasword/$1/$2/';
$route['dashboard'] = 'dashboard';
$route['dashboard/create-post'] = 'dashboard/posts/create';
$route['dashboard/create-page'] = 'dashboard/pages/create';
$route['dashboard/create-category'] = 'dashboard/categories/create';
$route['dashboard/manage-authors'] = 'dashboard/users';
$route['404_override'] = '';
$route['categories/posts/(:any)'] = 'categories/posts/$1';
$route['(:any)'] = 'posts/post/$1';
$route['translate_uri_dashes'] = FALSE;

I also added this to the config.php file:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_()@=&\-!';

Yet, at the URL http://ciblog.com/changepasword/myaddress@gmail.com/f450469ac1970b06074acb7c430d431d instead of the view being rendered, I get the error:
404 Page Not Found
The page you requested was not found.

If I use md5($this->user_email) instead of $this->user_email I get the URL: http://ciblog.com/changepasword/ec9814883d7f7149bc15f1ed1f472da9/d7571dc4e25ea76278bee5eb45251f11, but still, the 404 Page Not Found erroe message.
All the code I have written so far for this update password functionality is HERE.
What am I doing wrong?

A: Change these 2 lines!
$route['changepasword'] = 'changepasword';
$route['changepasword/(:any)/(:any)'] = 'changepasword/$1/$2/';

UPDATE:
You forget to define function/method name in route:
Modify from this: $route['newpasword/(:any)/(:any)'] = 'newpasword/$1/$2/'; to this: $route['newpasword/(:any)/(:any)'] = 'newpasword/index/$1/$2/'; And the previous line ($route['newpasword'] = 'newpasword';) is deletable because you not use index  function without parameters.


text:
Q: Loop through class method OOP+PDO I have a class called POSTS and here is the code:
<?php
// This is a class file:
        class POSTS {
            private $connection;
            public $title;
            public $details;

            // This connection coming from another PDO file.
            function __construct($dbConn) {
                $this->connection = $dbConn;
            }

            public function getRealtedPosts($section_name) {
                $stm = $this->connection->prepare("SELECT * FROM posts WHERE section_name !=:Section_name");
                $stm->bindParam(":Section_name", $section_name);
                $stm->execute();

                $results = $stm->fetch(PDO::FETCH_OBJ);
                $this->title = $results->title;
                $this->details = $results->details;
            }
        }

        // Here the Index File:
        // I already Initiated the class and connection by
        // required the PDO file.

        $section_name = 'PHP';

        while ($POSTS->getRealtedPosts($section_name)) {
            $post_title = $POSTS->title;
            $post_details = $POSTS->details;
        ?>

<?php echo $post_title;?>

<?php echo $post_details;?>

        <?php
        }
?>

Unfortunately the output is nothing :( however if I removed the while loop only one row is appeared.
Also I tried to make the loop inside my class file but it didn't work.
Help please.

A: This only fetches one row:
$results = $stm->fetch(PDO::FETCH_OBJ);

Just replace it with:
$results = $stm->fetchAll(PDO::FETCH_OBJ);

Of course you then need to store all results somewhere, currently you only store title and details of one row in your class.
A complete example:
class POSTS {

   // the rest of your class

   public function getRealtedPosts( $section_name ) {
        $stm = $this->connection->prepare("SELECT * FROM posts WHERE section_name !=:Section_name");
        $stm->bindParam(":Section_name", $section_name);
        $stm->execute();

        return $stm->fetchAll( PDO::FETCH_OBJ );
    }
}

Then, in your index file:
$results = $POSTS->getRealtedPosts( $section_name );
foreach ( $results as $post ) {
?>

<?php echo $post->title;?>

<?php echo $post->details;?>

<?php
}


text:
Q: I Want to add the numbers in the matrix I want the sum of the numbers in the matrix in each column to add up, tried doing this using different variation's of the same music[i+1][j]+=music[i][j], but its not working, so basically what the program does, it assigns 3 points to the first number the user inputs as his favorite song, the second song get 2 points and the third 1 point, i want the matrix at the end to sum up all the points from the participants and give me the total.
#include <stdio.h>
#include <stdlib.h>

int main()

{   int num=0, pers=0;

    int i,j, k;

    int votos=0;

    printf("Digite la cantidad de personas:");

    scanf("%d", &pers);

    float music[pers+1][10];

    for(i=0;i<pers+1;i++){

       for(j=0;j<10;j++){
        music[i][j]=0;
       }
    }

for(i=0;i<pers;i++){

  printf("Participante %d :\n",i+1);

       for(k=1;k<=3;k++){

         printf("Digite el numero de sus 3 canciones favoritas %d:\n",k);

          scanf("%d",&num);

           for(j=0;j<9;j++){
             if (k==1){
              music[i][num-1]=3;
            }
               if (k==2){
                music[i][num-1]=2;
              }
               if (k==3){

                music[i][num-1]=1;
              }

               music[10][j]+=music[i][j];
       }
    }
}
    for(i=0;i<pers+1;i++){
       for(j=0;j<10;j++){
        printf("%.2f\t",music[i][j]);
       }
       printf("\n");
    }
        return 0;
     }

A: Try This Code It working and sum up
#include <stdio.h>
#include <stdlib.h>

int main(){
int num=0, pers=0;

int i,j, k;

int votos=0;

printf("Digite la cantidad de personas:");

scanf("%d", &pers);

float music[100][100];
float sum[100][100];

for(i=0;i<pers+1;i++){

   for(j=0;j<10;j++){
    music[i][j]=0;
   }
}

for(i=0;i<pers;i++){

printf("Participante %d :\n",i+1);

   for(k=1;k<=3;k++){

     printf("Digite el numero de sus 3 canciones favoritas %d:\n",k);

      scanf("%d",&num);

       for(j=0;j<9;j++){
         if (k==1){
          music[i][num-1]=3;
        }
           if (k==2){
            music[i][num-1]=2;
          }
           if (k==3){

            music[i][num-1]=1;
          }

           sum[i][j]+=music[i][j];
       }
    }
}
for(i=0;i<pers+1;i++){
   for(j=0;j<10;j++){
    printf("%.2f\t",sum[i][j]);
   }
   printf("\n");
}
    return 0;
 }

A: GDB is your friend for these sorts of problems. You can install an interactive debugger and step through your code line by line to see what values your matrix takes on certain input.
If you did that, you may have saw that you're accessing the 10th row of your matrix. Even if pers is initialized to three.
There's also an issue where you begin summing music values as they're being initialized (leading to over counting).
  for (i = 0; i < pers; i++)
  {
    printf("Participante %d :\n", i + 1);
    for (k = 1; k <= 3; k++)
    {
      printf("Digite el numero de sus 3 canciones favoritas %d:\n", k);
      scanf("%d", &num);
      if (k == 1)
      {
        music[i][num - 1] = 3;
      }
      if (k == 2)
      {
        music[i][num - 1] = 2;
      }
      if (k == 3)
      {
        music[i][num - 1] = 1;
      }
    }
  }

  for(j = 0 ; j < 10; j++)
  {
    for (i = 0; i < pers+1; i++)
        music[pers][j] += music[i][j];
  }

I'm hoping this code doesn't fully solve your problem since it'll be good for you to look into gdb and learn how to interact with your code and understand where its deviating from your expectations.
It'll also help to do as paddy suggested and explain what your input and output is supposed to look like.


text:
Q: How do you create links in a node list if you want two nodes linked if they share the same attribute/s I have a CSV node list and I want to create an edges list by linking the nodes if they share at least one attribute in the Listed_in column.

ID
Listed_in

1
Horror,Sci-Fi

2
Sci-Fi,Adventure

3
Adventure

4
Sci-Fi

That way I can have a new undirected edges list like this:

Source
Target

1
2

1
4

2
3

2
4


text:
Q: Xcode 6 - universal image support I am wondering which image sizes are needed with new XCode 6 and iPhone 6 and iPhone 6 plus support.
So if I am now having a fullwidth image, which is
640 x 80 pixel

for an iphone 4s/5 series. So with "@2x". For iPhone 6 plus I need the "@3x" as well. So that would be
1242 x 80 pixel

?
Update:
My goal is it to have a fullwidth image which looks good on every iphone or ipad (Size class any any).

A: Assuming that your 640 x 80 image is @2x, the @3x image size would be 960 x 120 (960 = 640 / 2 * 3)


text:
Q: SignalR on .NET Can't send a derived class or an implementation of an interface to client everyone. I'm currently trying to send a derived class (or an implementation of an interface) from the server to the client. I can't do it because it won't call the method in the client. I've tried taking out the inheritance and sending it, and it does work properly, so the problem comes from trying to send a derived class to the client. Thanks in advance
Here are the classes:
Interface:
public interface ISquare
{
    Uri Image
    {
        get;
        set;
    }

    List<Player> PlayerList
    {
        get;
        set;
    }
}

Implementations:
public class Property: ISquare
{
    private Uri image { get; set; }
    private List<Player> playerList { get; set; }
    public int price { get; set; }
    public int nHouses { get; set; }
    public bool hasHotel { get; set; }
    public bool isBought { get; set; }
    public ColorProperty color { get; set; }
    public int moneyToPay { get; set; }
    public Player buyer { get; set; }
    public int squarePosition { get; set; }
    public Uri Image
    {
        get
        {
            return image;
        }

        set
        {
            image = value;
        }
    }
    public List<Player> PlayerList
    {
        get
        {
            return playerList;
        }

        set
        {
            playerList = value;
        }
    }

    public Property(int price, int nHouses, bool hasHotel, bool isBought, ColorProperty color, int moneyToPay, Player buyer, int squarePosition, Uri image, List<Player> playerList)
    {
        this.price = price;
        this.nHouses = nHouses;
        this.hasHotel = hasHotel;
        this.isBought = isBought;
        this.color = color;
        this.dineroAPagar = moneyToPay;
        this.buyer = buyer;
        this.squarePosition = squarePosition;
        this.image = image;
        this.playerList = playerList;
    }

    public Property(int price, ColorPropiedad color, int squarePosition)
    {
        this.price = price;
        this.nHouses = 0;
        this.hasHotel = false;
        this.isBought = false;
        this.color = color;
        this.dineroAPagar = 0;
        this.buyer = null;
        this.squarePosition = squarePosition;
        this.image = image;
        this.playerList = new List<Player>();
    }
}

public class Square : ISquare
{
    private Uri image { get; set; }
    public SquareType type { get; set; }
    private List<Player> playerList { get; set; }
    public Uri Image
    {
        get
        {
            return image;
        }

        set
        {
            image = value;
        }
    }
    public List<Player> playerList
    {
        get
        {
            return playerList ;
        }

        set
        {
            playerList = value;
        }
    }

    public Square(SquareType type, List<Player> playerList)
    {
        this.type = type;
        this.playerList = playerList;
    }

    public Square(SquareType type)
    {
        this.image = null;
        this.type = type;
        this.playerList= new List<Player>();
    }

    public Square()
    {
        this.image = null;
        this.type = SquareType.PROPERTY;
        this.playerList = new List<Player>();
    }
}

Here's what the client looks like:
private async void joinGame(Player playerServer)
    {
        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        () =>
        {
            if (playerServer != null)
            {
                _navigationService.Navigate(
                    typeof(GameView),
                    new PlayerWithLobby()
                    {
                        player = playerServer,
                        lobby = _lobby
                    }
                );
            }
            else
            {
                throw new NotImplementedException("Player is null");
            }
        }
        );
    }


text:
Q: How do I keep my android activity keep on going even if somebody switches from dark mode to day mode or vice versa (using Java) The problem is that when I switch from dark mode to light mode (android dark mode and android light mode), the activity which was going on that works fine but a duplicate activity starts all over again.
Now this does not matter when you are just working with visuals because the new activity covers the screen and old activity is not displayed but I am also working with sounds so the sounds playing in both the activities are heard.
In short, when switching from dark mode to light (or vice versa), the ongoing activity continues while a duplicate activity of the very same one starts from the beginning. I don't want this new duplicate activity. How do I avoid it?
I don't think my code is required here. I require the answer in Java.

A: The description of your problem doesn't make much sense. Normally, if you change the light/dark mode setting, Android will kill the existing instance of your Activity and create a new instance, so that the new instance can recreate all the UI elements with the proper style. You say that Android isn't killing the existing instance, but it is starting a new instance and this doesn't make sense. You should add logging in onCreate() and onDestroy() to see if this is really going on, or if you are seeing something else.
Note that you can prevent Android from restarting your Activity by adding
android:configChanges="uiMode"

to the <activity> declaration in the manifest.
Instead of killing and recreating your Activity, the Android framework will instead call onConfigurationChanged() on the existing instance of the Activity. You will then need to handle the change yourself.


text:
Q: Getting error when trying to edit subpage in Grav Whenever I try to add or edit a subpage (i.e. a child page of the main page),
I am getting this error:

count(): Parameter must be an array or an object that implements Countable

Offending line is:
<div data-grav-array-type="container"{% if field.value_only %}
     data-grav-array-mode="value_only"{% endif %}
     {{ value|length <= 1 ? ' class="one-child"' : '' }}>

This is happening in: /grav/templates/forms/fields/array/array.html.twig.
I'm not familiar enough with Grav to understand the stack and debug it.

A: It looks like you upgrade to PHP 7.2.  PHP changed count() behavior in the following RFC: https://wiki.php.net/rfc/counting_non_countables
Since then, calling count() with a parameter that is a scalar, null, or an object that doesn't implement Countable raises PHP warning like Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d.
Thus, since PHP 7.2 this will be considered as a bug in the code.
Examples:
https://github.com/twigphp/Twig/blob/2.x/lib/Twig/Node/Module.php#L370
https://github.com/twigphp/Twig/blob/2.x/lib/Twig/Extension/Core.php#L1117
You may want to use length() or try to convert your variable to iterable


text:
Q: Python : Pass two values to function used in filter I made a filter function to filter out file types in a list of file names .
>>> l1
['180px-Cricketball.png', 'AgentVinod_450.jpg', 'Cricketball.bmp', 'Django-1.4', 'Django-1.4.tar.gz', 'Firefox Setup 11.0.exe', 'I-Will-Do-The-Talking-Tonight-(Muskurahat.Com).mp3', 'kahaani-.jpg', 'Never gonna leave this bed.mp3', 'Piya-Tu-Kaahe-Rootha-Re-(Muskurahat.Com).mp3', 'pygame-1.9.1release', 'pygame-1.9.1release.zip', 'pygame-1.9.2a0.win32-py2.7.msi', 'python-2.7.2.msi', 'python-3.1.2.msi', 'Resume.doc', 'selenium-2.20.0', 'selenium-2.20.0.tar.gz', 'sqlite-shell-win32-x86-3071100.zip', 'wxdesign_220a.exe', 'YTDSetup.exe']
>>> def myfilt(subject):
    if re.search('.jpg',subject):
        return True

>>> filter(myfilt,l1)
['AgentVinod_450.jpg', 'kahaani-.jpg']

This works fine.
Now suppose I want make this more flexible. I want to pass file type to the function .
So I rewrite the function
>>> def myfilt(subject,filetype):
    if re.search(filetype,subject):
        return True

Now how do I pass the filetype through the filter function?
I tried:
>>> filter(myfilt(l1,filetype),l1)

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    filter(myfilt(l1,filetype),l1)
  File "<pyshell#28>", line 2, in myfilt
    if re.search(filetype,subject):
  File "C:\Python27\lib\re.py", line 142, in search
    return _compile(pattern, flags).search(string)
TypeError: expected string or buffer

Nothings works. Any ideas?

A: You would usually use a list comprehension rather than filter() for such cases:
[x for x in l1 if myfilt(x, filetype)]

If you really want to use filter(), you could use a lambda function
filter(lambda x: myfilt(x, filetype), l1)

or functools.partial():
filter(functools.partial(myfilt, filetype=filetype), l1)

The list comprehension seems the easiest and most readable option, though.


text:
Q: Double Dollar Sign - Assign Array key=>value I would like to create 3 different arrays which can change depending on which fields are pulled from some mysql tables.
This is the code I have:
    // Gather db rows with query
    $compQuery['subCats'] = mysql_query("SELECT id,name,category FROM subcategories ORDER BY id DESC");
    $compQuery['cats'] =    mysql_query("SELECT id,name FROM categories ORDER BY id DESC");
    $compQuery['mans'] =    mysql_query("SELECT id,name,link FROM manufacturers ORDER BY id DESC");

    // Place rows into arrays
    foreach($compQuery as $name=>$query){

        $name = array();

        while($data = mysql_fetch_array($compQuery[$name])){
            foreach($data as $key=>$value){

                $$name[$key] = $value;

            }

        }

    }

What I would expect this to produce is 3 arrays: subCats, cats and mans each with the value pairs.  Instead of finding the $$name variable and assigning [$key] = $value to the array it is taking a single letter out of the $$name variable and assigning the $value to this new variable.
For example, if $name = 'subCats', $key = '3', and value = 'machine tools'
It would create the variable $C using the 3rd letter in subCats:
$C = 'machine tools'

What it should do is create:
$subCats[3] = 'machine tools';

Now, obviously there are easier ways to create separate arrays for each query, and I have modified my code to a lazier/easier version.  However, I am still curious as to how I would go about assigning a key value pair to a double dollar sign variable.
Any help would be greatly appreciated!  I have the simple code working now, but would like to implement this new code to be more dynamic and allow for more queries as needed without hassle.
Thanks!
Josh

A: In this line:
$name = array();

You're overwriting $name. You probably meant to write to $$name:
$$name = array();

A: ${$name}[$key]
But I do not like to create 'unknown' variable, as in variables whose name is not in the code... What if the name is 'key','db','_GET','compQuery' etc? All hell breaks loose...


text:
Q: Unity apply idle animation to model I created a model in Blender and posed it the way I want it to look. The character will never move and no animations will ever change.
I exported the character with animations to an FBX and imported it into Unity 3D. After dropping the character into the scene, the character's pose is back to the default take.
How can I force the character to use the pose that I want? Do I have to do it in script or is there a setting that I can change to make it play the idle animation at all times?

A: Putting your model in the scene will not invoke idle animation, animation and rendering is two separate thing. To always play a certain animation on a model you have three option -
1. Via Legacy Animation -
Select you model in the scene, remove the default Animator component and add a new Animation component. (Animator and Animation are two different component type.) It has an option of selecting an animation clip. Drop your animation clip there and choose 'Play Automatically'.
2. Via Script -
You can add Animation component, attach multiple animation and select which one to play via script too.
You can also do this for meca-anim way which is explained in the next point.
3. Via Meca-Anime
Every model has a default Animator component. It needs an animation controller object to run. Create an animation controller (Click on create button in project view). Attach the controller to the Animator component. Double click on the controller to open Animator view. Drop your clip there and make it as default. The default animation plays automatically now. Using Meca-anime has many advantage over legacy way, which is beyond the scope of this answer. Check the following link instead -
Mecanim vs Legacy Animation


text:
Q: Could not load file or assembly 'Interop.WIA, Version=1.0.0.0, Culture=neutral I've an application using "Microsoft Windows Image Acquisition Library v2.0" to acquire images. In my Win 7 x64 developer machine it works properly but if I try to create a setup project an install it on another Win 7 x64 pc I get this error:
Could not load file or assembly 'Interop.WIA, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=a9bedaecc58d6a85'

My project Build platform is set to "x86", reference CopyLocal is set to true.
In the setup project I add the primary output and it imports all dll but not Interop.WIA!
What I miss?
Update
Here my setup project files list and WIA reference properties, interop is not detected!

update
I tried to create a simple winform project, added reference setup created and interop reference has been detected! So the problem seems to be that my project "Primary Output" won't recognize interop reference!
Can I force it?

A: The dll should be indeed added to the setup manually.


text:
Q: Custom Ribbon button in SharePoint 2010 showing up as disabled I've create a custom ribbon button that only shows up the Insert block for a blog post.  On my dev environment, it shows up fine.  When I deploy to another environment, it shows up, but is disabled.  I can't figure out how to enable it.
Button is enabled and okay on my dev environment

Button is disabled on other environment, where I'm a site collection admin.

It states that it is likely security or you have something selected that is not in context.  I'm a site collection admin, so don't think it's security and I've selected the Rich text area, so not sure about the object context either.
Secondary Question:  I'd ultimately like to take over the Video and Audio button, but cannot find where that is referenced in the cmdui.xml.  Where does that thing come from?
Here is my code for the ribbon button:
 <?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
  Id="CommandUI.Ribbon.EditingTools.BlogSiteMediaButton"
  RegistrationType="ContentType"
  RegistrationId="0x0110"
  Location="CommandUI.Ribbon">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.EditingTools.CPInsert.Media.Controls._children">
          <Button
            Id="Ribbon.EditingTools.CPInsert.Media.Controls.BlogSiteMediaButton"
            ToolTipTitle="Video"
            ToolTipDescription="Insert a video onto the page."
            Sequence="15"
            Image32by32="/_layouts/images/lg_ICWMD.gif"
            Image16by16="/_layouts/images/lg_ICWMD.gif"
            Command="BlogSite_Media_Button"
            LabelText="Insert Video"
            TemplateAlias="o1" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="BlogSite_Media_Button"
          CommandAction="javascript:OpenInsertMediaDialog();" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
  <CustomAction Id="Ribbon.EditingTools.CPInsert.Actions.Scripts"
   Location ="ScriptLink"
   ScriptSrc="/_layouts/BlogSite.MediaButton/BlogSite.Ribbon.InsertMedia.js" />
</Elements>

A: Finally figured this one out and it was a simple thing.  The environment I developed in was RTM.  The shared development server that it was being deployed to and tested on was still Beta.  Ahhh!  So this was just a true beta bug with SharePoint that is now fixed in RTM.  So much wasted troubleshooting time.  Sometimes, it's the simplest things.


text:
Q: PropTypes for Next.js: TypeError: prop_types__WEBPACK_IMPORTED_MODULE_0___default(...).shape is not a function I have a component in Next.js:
import PropTypes from "prop-types";

export default function DetailComponent({ data }) {
    return (
        <div>
            {data.heading} {data.title}
        </div>
    );
}

DetailComponent.propTypes = {
    data: PropTypes.shape({
        heading: PropTypes.string,
        title: PropTypes.string,
    }),
};

Which gives this error when I try to view a page with the component:
error - TypeError: prop_types__WEBPACK_IMPORTED_MODULE_0___default(...).shape is not a function
    at Object../components/section/DetailComponent.js (D:\Documents\app\frontend\.next\server\pages\section\[...slug].js:237:59)
    at __webpack_require__ (D:\Documents\app\frontend\.next\server\webpack-runtime.js:25:42)
    at Object../pages/section/[...slug].js (D:\Documents\app\frontend\.next\server\pages\section\[...slug].js:2323:91)
    at __webpack_require__ (D:\Documents\app\frontend\.next\server\webpack-runtime.js:25:42)
    at __webpack_exec__ (D:\Documents\app\frontend\.next\server\pages\section\[...slug].js:2663:39)
    at D:\Documents\app\frontend\.next\server\pages\section\[...slug].js:2664:28
    at Object.<anonymous> (D:\Documents\app\frontend\.next\server\pages\section\[...slug].js:2667:3)
    at Module._compile (node:internal/modules/cjs/loader:1102:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
    at Module.load (node:internal/modules/cjs/loader:967:32) {
  page: '/section/80539-asd/2'
}

The following works fine:
DetailComponent.propTypes = {
    data: PropTypes.object,
};

Why can't I use PropTypes.shape()?
Here's my package.json:
  "dependencies": {
    "axios": "^0.22.0",
    "next": "11.1.2",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "sass": "^1.42.1",
    "swr": "^1.0.1",
  },
  "devDependencies": {
    "eslint": "^7.32.0",
    "eslint-config-next": "11.1.2",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-react": "^7.26.1",
    "prop-types": "^15.7.2"
  }

Edit:
The following seems to work... but then when are you supposed to use PropTypes.shape()?
DetailComponent.propTypes = {
    data: {
        heading: PropTypes.string,
        title: PropTypes.string,
    },
};

A: "prop-types" was installed under devDependencies. Installing as a dependency fixed the error. npm i prop-types -P


text:
Q: multiple hierarchy in coredata I do have a problem where I am having a hard time figuring out how to lay out the relationship in coredata. I tried to visualize the problem below.
Basically in my application users have STATEMENTS that are made of TERMS.

*

*One or more TERMS make STATEMENTS[1].

*Users can also tap on a term[2] and

*create another statement that's connected to this term[3].

*Once they solve this sub statement[4]

*they can go back to the main statement [5] and highlight another term and so on.

They should be able to go deeper than one level if need be. Say, select another term in sub statement and create another statement etc.
I am not sure how to create such a schema in coredata.
I already have my TERM and STATEMENT entities, and I initially separated STATEMENT AND SUBSTATEMENT as two different entities but I am not entirely sure if this is a approach anymore.
I think a more efficient approach would be to store each statement in just one entity and have a relationship with TERM but I Am not sure how to figure out the levels.
I would appreciate any directions.


text:
Q: Security issue in PHP after logging in (using codeigniter) I am using CodeIgniter to build an admin system.
But I am having a problem regarding security.
Let me give an example: A user succesfully logged in and gets redirected to the main page of the admin system. Now that users presses the "BACK" button in his browser. He now gets send back to the login page. He now presses the "NEXT" button and get send back to the main page of the admin system.
I don't want users to be able to get send back to main page of the admin system once they are at the login page after they are logged in. How can I achieve this.
Thanks in Advance,
Mark
EDIT:
Thanks for all the ideas, but no works for me. What I meant was, that when someone logs in he gets redirected to the main page of the system. Then he clickes on the "back" button that is left of the url bar at the top of the browser.

A: Have your login page first check to see if the user is already logged in by checking the session.
If the user IS logged in, use a php redirect such as header ("Location: $URL"); where $URL is your main page.

A: Simply use sessions on login page:
if(isset($_SESSION['admin_loggedin'])){
header("location: admin_index.php");
exit();
}

A: Try clearing cache on login page How to clear browser cache with php? , check if user is authorized and redirect him if $authorized==true.
you can check authorization via checking SESSION or cookies or else...

A: PHP will returns to the login page if it exists on cache and will not actually reloads from server, So we need to force PHP to load it from server when comes to the login page check. So you can use,
header("Cache-Control: no-cache, must-revalidate");

if(isset($_SESSION['user']))
{
      //Write your redirect code
}
else
{
      //Redirect to login page
}

in the page where you are check whether login exists or not. So that PHP will reloads each time from the server without loading from cache. And if session exists, you will be resirected to the corresponding page


text:
Q: How to know where iOS app installed from (using Enterprise distribution) With Enterprise Distribution, I provided a link to .ipa on the internet, and sent it to customers.
After a customer install the .ipa via that link. Is it posible to know where the app was installed from? Any code added or any way to know that?


text:
Q: PhP mailer - Send Multiple Messages to Multiple recipients I am just working with phpmailer. I would like to generate multiple messages and send them to multiple recipients. However, the generateMessage function() just send to the first recipient in recipient list.
Here is my code, any helps is appreciate.
require_once("class.phpmailer.php");

set_time_limit(0);

$wh = implode("', '", $abc);
echo "aaa" . $wh;
//echo $email;
$db = DB::getInstance();
$query1 = $db->query("SELECT * FROM tablea WHERE Location IN ('$wh')");
$result1 = $query1->results();
$query2 = $db->query("SELECT * FROM tableb WHERE Location IN ('$wh')");
$result2 = $query2->results();
$query3 = $db->query("SELECT * FROM tablec");
$result3 = $query3->results();
foreach ($result3 as $b) {
  $username = $b->email;
  $password = $b->password;
  $Times = $b->P2_Time;
}
$minutePerDay = (24 * 60) / $Times;
echo $minutePerDay;
foreach ($result1 as $r) {
  $TimeP2SendE = $r->Timea;
  break;
}
foreach ($result2 as $r) {
  $TimeP2SendG = $r->Timea;
  break;
}
$currentTime = date('Y-m-d H:i:s');
$TimeDifferentE = (strtotime($currentTime) - strtotime($TimeP2SendE)) / 60;
$TimeDifferentG = (strtotime($currentTime) - strtotime($TimeP2SendG)) / 60;
if ($TimeDifferentE >= $minutePerDay or $TimeDifferentG >= $minutePerDay) {
  $mail = new PHPMailer();
  $mail->IsSMTP();
  $mail->Host = "smtp.gmail.com";
  $mail->Port = 465;
  $mail->SMTPAuth = true;
  $mail->SMTPSecure = 'ssl';
  $mail->Username = $username;
  $mail->Password = $password;
  $mail->AltBody = " ";
  $mail->From = $username;
  $mail->FromName = 'Noti';
  $mail->clearAddresses();
  $mail->AddAddress($email);
  $mail->Subject = $title;
  $mail->IsHTML(true);
  $mail->Body = '';
  $mail->Body .= "
Information
";
  $mail->Body .= '
';
  $mail->Body .= "
";
  $mail->Body .= "";

  if (!$mail->Send()) {
    echo "Error sending: " . $mail->ErrorInfo;
  } else {
    echo "Letter is sent";
  }
}

I have run this function 4 times to send to 4 different recipients, however it just sends to the first recipient.

A: You could build an array of contact objects and loop the array to add each contact like such:
foreach($contacts as $contact){
    $mail->AddAddress($contact->email);
}

This will add each contact's email and build a mailing list.
For a custom body for each recipient I generally use the following method.
function sendEmail($email, $name, $body, $altBody = null) {
        $mail = new PHPMailer;
        $mail->IsSMTP();
        $mail->Host = "smtp.gmail.com";
        $mail->Port = 465;
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = 'ssl';
        $mail->Username = $username;
        $mail->Password = $password;
        $mail->From = $username;
        $mail->FromName = 'Noti';
        $mail->clearAddresses();
        $mail->Subject = $title;
        $mail->IsHTML(true);
        $mail->addAddress($email, $name);     // Add a recipient
        $mail->Body = $message;
        $mail->AltBody = $altBody;

        if (!$mail->send()) {
            error_log($mail->ErrorInfo);
            return false;
        } else {
            return true;
        }
    }

foreach($contacts as $contact){
    //create message here
    sendEmail($contact->email, $contact->name, $message);
}

A:     require_once("class.phpmailer.php");

    set_time_limit(0);

    $wh = implode("', '", $abc);
    echo "aaa" . $wh;
    //echo $email;
    $db = DB::getInstance();
    $query1 = $db->query("SELECT * FROM tablea WHERE Location IN ('$wh')");
    $result1 = $query1->results();
    $query2 = $db->query("SELECT * FROM tableb WHERE Location IN ('$wh')");
    $result2 = $query2->results();
    $query3 = $db->query("SELECT * FROM tablec");
    $result3 = $query3->results();
    $currentTime = date('Y-m-d H:i:s');
    foreach ($result3 as $b) {
      $username = $b->email;
      $password = $b->password;
      $Times = $b->P2_Time;
    }
    $minutePerDay = (24 * 60) / $Times;
    echo $minutePerDay;
    foreach ($result1 as $r) {
      $TimeP2SendE = $r->Timea;
      $TimeDifferentE = (strtotime($currentTime) - strtotime($TimeP2SendE)) / 60;
if($TimeDifferentE >= $minutePerDay){
    sendemail($username,$password,$email,$title);
}
    }
    foreach ($result2 as $r) {
      $TimeP2SendG = $r->Timea;
     if($TimeDifferentG >= $minutePerDay){
    sendemail($username,$password,$email,$title);
}
    }

public function sendEmail($username,$password,$email,$title){
 $mail = new PHPMailer();
  $mail->IsSMTP();
  $mail->Host = "smtp.gmail.com";
  $mail->Port = 465;
  $mail->SMTPAuth = true;
  $mail->SMTPSecure = 'ssl';
  $mail->Username = $username;
  $mail->Password = $password;
  $mail->AltBody = " ";
  $mail->From = $username;
  $mail->FromName = 'Noti';
  $mail->clearAddresses();
  $mail->AddAddress($email);
  $mail->Subject = $title;
  $mail->IsHTML(true);
  $mail->Body = '';
  $mail->Body .= "
Information
";
  $mail->Body .= '
';
  $mail->Body .= "
";
  $mail->Body .= "";

  if (!$mail->Send()) {
    echo "Error sending: " . $mail->ErrorInfo;
  } else {
    echo "Letter is sent";
  }
}