text:
Q: How to restyle a XAML radio button as a coloured label I am using the following style with a group of radiobuttons:
       <Style x:Key="RadioTextStyle" TargetType="{x:Type RadioButton}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RadioButton}">
                    <Label Content="{TemplateBinding Content}" Foreground="Red"/>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Setter Property="Background" Value="Green"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

The trigger is not executed and I assume this is because it is looking for the IsChecked property of the Label.  How can I properly ensure that the label colour properly tracks the IsChecked state of the underlying RadioButton?
I am still trying many variants of this and currently have the following:
<Style x:Key="RadioTextStyle" TargetType="{x:Type RadioButton}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RadioButton}">
                    <Label x:Name="RadioLabel"  Content="{TemplateBinding Content}" Foreground="Red"/>
                    <ControlTemplate.Triggers>
                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsChecked}" Value="True">
                            <Setter Property="Foreground" Value="Green"/>
                        </DataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

This looks right to me and intellisense suggests most of the values.  However, it still doesn't actually change selected labels to green.
Thanks,
Andy

A: Keep your original try. You just need to tell your trigger what it's actually changing something on with TargetName like;
<Style x:Key="RadioLabel" TargetType="{x:Type RadioButton}">
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="{x:Type RadioButton}">

             <Label x:Name="RadioLabel"
                    Content="{TemplateBinding Content}" Foreground="Red"/>

            <ControlTemplate.Triggers>
               <Trigger Property="IsChecked" Value="True">
                  <Setter TargetName="RadioLabel"
                          Property="Background" Value="Green"/>
               </Trigger>
            </ControlTemplate.Triggers>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

Hope this helps, cheers.


text:
Q: How to disable "Collect unused imports" after renaming something in Android Studio? After renaming anything in Android Studio, it starts a process to collect unused imports and Android Studio just freezes for about 5-10 seconds. This is very annoying. How can I disable this?
I have already disabled "Optimize imports on the fly" under "Auto Import". Unfortunately, that does not have any effect on this behaviour.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oauth refresh token provider error in ValidateClientAuthentication I apologize for my English. I presented the following problem. I'm working with C # asp.net MVC 5.
I am implementing a server with the OAuth 2 bearer token and token refresh. When requesting the access token returns me refresh token and token with client_credential grant_type, client_id and client_secret. The problem is to apply the new refresh token from token. When I shipping grant_type refresh_token and refresh_token parameter as the first method is called ValidateClientAuthentication. but as shipping and client_secret client_id not validate me because I check the existence of an object in the database by these parameters. What am I doing wrong. thank you very much

A: I move th secret validation to GrantClientCredentials method and it´s work. Thanks for all


text:
Q: Combining points and their values within the same cell in QGIS I have two shapafiles: points and vector grid. I need to combine points which are in the same cell(or cross cell) and sum their values. How can I do this in QGIS?

A: Since QGIS 3.18 using the array_sum() function, you can use the following expression on the grid layer to calculate the sum of the value attribute from all points that are within a grid-cell automatically:
array_sum (overlay_contains ('points', value))

Screenshot: the expression (together with to_int to get integer values) calculates the blue value for each grid cell: sum of the values of all red points within this cell:

A: You need to do a spatial join using the join attributes by location tool. You can choose to sum the attribute field from the points layer. So this should output a new grid layer with the sum of the points attribute
See this tutorial for how to perform it
http://www.qgistutorials.com/en/docs/performing_spatial_joins.html


text:
Q: EditText focus not going after finishing activity In my form activity, I've 3 fields. After confirming the form to the server it finishes and go to the previous activity. But the problem , After finish the keyboard is still pop up and the previous activity has no input field.
Here is the layout file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@color/colorWhite"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/toolbar"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_gravity="center"
            android:layout_margin="20dp"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <sslwireless.com.easycorporate.Fonts.LoraBold
                android:layout_marginBottom="20dp"
                android:text="@string/change_password_title"
                android:textSize="25sp"
                android:textColor="@color/colorAccent"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <EditText
                android:id="@+id/oldPassword"
                android:background="@drawable/super_white_style"
                android:padding="12dp"
                android:layout_marginTop="15dp"
                android:singleLine="true"
                android:inputType="textPassword"
                android:hint="@string/hints_old_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <EditText
                android:id="@+id/newPassword"
                android:background="@drawable/super_white_style"
                android:padding="12dp"
                android:layout_marginTop="15dp"
                android:singleLine="true"
                android:inputType="textPassword"
                android:hint="@string/hints_new_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <EditText
                android:id="@+id/confirmPassword"
                android:background="@drawable/super_white_style"
                android:padding="12dp"
                android:layout_marginTop="15dp"
                android:singleLine="true"
                android:inputType="textPassword"
                android:hint="@string/hints_confirm_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <Button
                android:id="@+id/changePassword"
                android:text="@string/change_password"
                android:layout_marginTop="20dp"
                android:textColor="@color/colorWhite"
                android:background="@drawable/primary_dark_color_style"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </ScrollView>

</LinearLayout>

Here what actually happening.

i also set the android:windowSoftInputMode="stateHidden" for both activity in the manifest file. is there any way I can remove focus after go back to the previous activity ?

A: In onStop() of the finishing Activity, disable all the EditText fields like this in order to make the soft keyboard disappear:
EditText et = (EditText)findViewById(R.id.confirmPassword);
et.setEnabled(false);

A: call below code for close keybord , call when click on button
InputMethodManager imk = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imk.isActive()){
            imk.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide key board
        }

A: Here's something that actually fixed an identical bug today.
@Override
public void closeKeyboard(View view) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            //Log.d("RKZ", "isKeyboardShown("+((ViewGroup) findViewById(android.R.id.content)).getChildAt(0)+") = "+isKeyboardShown(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0)));
    if(view != null && Util.isSoftKeyboardShown(imm, view)) {
        Util.hideKeyboard(ActivityASG.this, view);
    }
}

And in your CHANGE PIN Button's onClick() just call it like this:
            //close keyboard
            callback.closeKeyboard(noteInput);
            callback.closeKeyboard(mailInput);
            //callback.closeKeyboard(yourCHANGE_PINview);

A: You may force IME to close (before you finish() your activity):
public void hideSoftKeyboard(@NonNull Activity activity) {
    IBinder windowToken = activity.getWindow().getDecorView().getRootView().getWindowToken();
    InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(windowToken, 0);
}


text:
Q: TeamCity with dotCover does not include all my assemblies in coverage report I want to run NUnit on TeamCity and generate report with dotCover. But for some reasons I cannot get the coverage report for all my project assemblies.
TeamCity config as below
Teamcity: 6.5.3
NUnit: 2.5.10
.NET Runtime: Platform: x86
.NET Runtime: Version: v4.0
dotCover: bundled with TC not customized

I have checked that all *.dll *.xml *.pdb files are there in the directory as expected as below (reference DLLs are not listed)
MY.PROJECT.A.dll
MY.PROJECT.A.pdb
MY.PROJECT.A.xml
MY.PROJECT.B.dll
MY.PROJECT.B.pdb
MY.PROJECT.B.xml
MY.PROJECT.C.dll
MY.PROJECT.C.pdb
MY.PROJECT.C.xml
MY.PROJECT.Test.dll
MY.PROJECT.Test.pdb
MY.PROJECT.Test.xml

MY.PROJECT.Test.dll is executed with NUnit and this assembly is excluded in the coverage report by using  *Test* filter. But only MY.PROJECT.A is in the dotCover coverage report whereas MY.PROJECT.B and MY.PROJECT.C are not included.
I checked the log but not error is found.
Any thoughts is much appreciated.

A: Finally, I figured out what is going on, and hope this answer is useful for those who are still struggling with this or similar problem.
Basically, dotCover only includes those assemblies are actually used (more precisely, those assemblies loaded by CLR) by the tests in the code coverage report.
In my case, only MY.PROJECT.A is used by tests, MY.PROJECT.B and MY.PROJECT.C are not used by tests due to external dependencies. and even with using MY.PROJECT.B directives in the tests, it does not count as CLR's lazy loading.
One dummy workaround to show 0% coverage report for these two assemblies is that either use anything  in the assembly in the tests, or force load these assemblies by calling System.Reflection.Assembly.Load("MY.PROJECT.B")
Related Question:

*

*Visual Studio Code Coverage Not Showing All Assemblies

*What constitutes full code coverage ...


text:
Q: data comparison in hadoop Can someone suggest the best and optimal solution for data comparison on 2 different clusters in hadoop? If on one cluster the incoming file is split in 10 blocks and stored in HDFS by MapReduce, and on the other cluster it is stored in 5 blocks and at the end of the day I want a difference in data in these 2 clusters.
Thanks

A: By using the Hadoop FSCK command we can able to retrieve files info.
hadoop fsck / -files -blocks -locations

Rest of the arguments and commands are detailed here
http://hadoop.apache.org/docs/r2.7.0/hadoop-project-dist/hadoop-hdfs/HDFSCommands.html#fsck .


text:
Q: NULL as a parameter I am a bit confused when you pass NULL as a parameter
for example
  int*  array_create( int* array,size)
  {
    array = new int[size];
    return array;
  }

  int main()
  {
    int* array = array_create(NULL,10);//can we pass NULL in this case?
    delete[] array;
    return 0;
  }

I know the example is kinda stupid, but I am wondering if we can pass NULL as the parameter when the function assigns some heap memory to a pointer and returns it?

A: When you call your function like this...
int* array = array_create(NULL,10);//can we pass NULL in this case?

...you are getting behaviour like:
int* array_create(...)
{
    int* array = NULL;
    size_t size = 10;   // using size_t as you'd missed any type
    array = new int[size];
    return array;
}

Ultimately, array is initialised to NULL then shortly afterwards overwritten with the value returned by new, so the initialisation serves no purpose.
For this code, there was simply no point passing an array argument... you could have created a local variable directly:
int* array_create(size_t n)
{
    int* array = new int[size];
    return array;
}

...or even...
int* array_create(size_t n)
{
    return new int[size];
}

I am wondering if we can pass NULL as the parameter when the function assigns some heap memory to a pointer and returns it?

This requirement doesn't make much sense, as the two things are unrelated.  You can pass whatever you like, and return whatever you like.

More commonly, a function might do something like:
void dump_bytes(std::ostream& os, unsigned char* p, size_t n)
{
    if (p)
        for (size_t i = 0; i < n; ++i)
            os << static_cast<int>(p[i]) << ' ';
}

In dump_bytes, specifying a p value of NULL would fail the if (p) condition, ensuring the function didn't invoke undefined behaviour by dereferencing via a NULL pointer, even if n was not 0.

A: Just summarizing from the comments:
Yes, it is completely valid, but in Your example it is completely useless (you know that)
Some examples of this in real code:
In OpenGL you can tell the API if the data you want is coming from is from a buffer:
  glBufferData(..., nullptr);

But wait! That's not null, that's nullptr?
Well in a c++11 compiler nullptr is a better option. Because NULL often usually resolves to 0, a version of the method that takes an int instead of a pointer the compiler will choose the int.
Here's some more data on that:
http://en.cppreference.com/w/cpp/language/nullptr
Also, if you want to edit an array, you should pass a pointer to a pointer.


text:
Q: How to send onPressed value to another widget Flutter I want to send data from widget to another widget, in my example I want to send onPressed value as a variable.
appBar: CancelAppBar(onPressed: ),
What should I write after onPressed (in the above code) to send the value:
Navigator.of(context).push(MaterialPageRoute(builder: (context) => UnderBuild()));
to a widget in a seperate dart file?
Following is the other file:
class CancelAppBar extends StatefulWidget implements PreferredSizeWidget {
  CancelAppBar({Key? key, required this.onPressed}) : super(key: key);

  final ValueGetter<String> onPressed;
  static final _appBar = AppBar();
  @override
  Size get preferredSize => _appBar.preferredSize;

  @override
  _CancelAppBarState createState() => _CancelAppBarState();
}

class _CancelAppBarState extends State<CancelAppBar> {
  get onPressed => null;

  @override
  Widget build(BuildContext context) {
    return AppBar(
      titleSpacing: 0.0,
      title: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(padding: EdgeInsets.only(left: 8.w)),
          IconButton(
            onPressed: ,
            icon: Icon(Icons.close),
          )
        ],
      ),
      backgroundColor: AppColors.dark,
    );
  }
}

A: You can access any StatefulWidget variable in the State class with widget getter, like:
Also, you can notice that:

*

*Your onPressed variable has ValueGetter<String> type which is only a typedef to String Function()

*The onPressed of IconButton widget has the type void Function()
Then you can use your variable like that:
class CancelAppBar extends StatefulWidget implements PreferredSizeWidget {
  CancelAppBar({Key? key, required this.onPressed}) : super(key: key);

  final ValueGetter<String> onPressed;
  static final _appBar = AppBar();
  @override
  Size get preferredSize => _appBar.preferredSize;

  @override
  _CancelAppBarState createState() => _CancelAppBarState();
}

class _CancelAppBarState extends State<CancelAppBar> {
  @override
  Widget build(BuildContext context) {
    return AppBar(
      titleSpacing: 0.0,
      title: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(padding: EdgeInsets.only(left: 8.w)),
          IconButton(
            onPressed: () {
              /// Access your variable by [widget.onPressed]
              widget.onPressed(); /// Call it inside this function because your variable doesn't match directly the [onPressed] of [IconButton] widget
            },
            icon: Icon(Icons.close),
          )
        ],
      ),
      backgroundColor: AppColors.dark,
    );
  }
}


text:
Q: PrimeNG p-inputnumber unable to enter negative fractional numbers I need to capture negative decimals with PrimeNG's p-inputnumber component, but when entering the component, and minFractionDigits is > 0, entering a - jumps the cursor to the end of the display, so the number cannot be captured conventionally.
. I can navigate back with the arrow keys, but it makes the usage painstaking and slow.
<p-inputNumber [(ngModel)]="modelNum" mode="decimal" locale="en-US"
[minFractionDigits]="2" [maxFractionDigits]="2"
(onFocus)="$event.target.select()" (ngModelChange)="calculateResults(row)">
</p-inputNumber>

Has anyone found a solution to this problem?
**Environment:**
Angular version: 10.x
PrimeNG version: 10.0.3


text:
Q: Visualize Random Forest and VSURF I want to visually sanity check a random forest/vsurf object I've created.  Is there a way to do that in R?
I saw this post: https://stats.stackexchange.com/questions/41443/how-to-actually-plot-a-sample-tree-from-randomforestgettree, but after trying the answers I end with this error:
Error in getTree(rf.model, 1, labelVar = TRUE) :
  No forest component in rf.model

Reproducible Example with code from the stack.exchange answer above:
#**************************
#return the rules of a tree
#**************************
getConds<-function(tree){
  #store all conditions into a list
  conds<-list()
  #start by the terminal nodes and find previous conditions
  id.leafs<-which(tree$status==-1)
  j<-0
  for(i in id.leafs){
    j<-j+1
    prevConds<-prevCond(tree,i)
    conds[[j]]<-prevConds$cond
    while(prevConds$id>1){
      prevConds<-prevCond(tree,prevConds$id)
      conds[[j]]<-paste(conds[[j]]," & ",prevConds$cond)
      if(prevConds$id==1){
        conds[[j]]<-paste(conds[[j]]," => ",tree$prediction[i])
        break()
      }
    }

  }

  return(conds)
}

#**************************
#find the previous conditions in the tree
#**************************
prevCond<-function(tree,i){
  if(i %in% tree$right_daughter){
    id<-which(tree$right_daughter==i)
    cond<-paste(tree$split_var[id],">",tree$split_point[id])
  }
  if(i %in% tree$left_daughter){
    id<-which(tree$left_daughter==i)
    cond<-paste(tree$split_var[id],"<",tree$split_point[id])
  }

  return(list(cond=cond,id=id))
}

#remove spaces in a word
collapse<-function(x){
  x<-sub(" ","_",x)

  return(x)
}

data(iris)
require(randomForest)
mod.rf <- VSURF(Species ~ ., data=iris,
                ntree = 1000, parallel =  TRUE, keep.forest = TRUE)
tree<-getTree(mod.rf, k=1, labelVar=TRUE)
#rename the name of the column
colnames(tree)<-sapply(colnames(tree),collapse)
rules<-getConds(tree)
print(rules)


text:
Q: Csv file - User permission needs to be created after each save For context, I'm uploading a csv file to a Postgres database via the psql command line. The cmd can only access the file after I add Everyone to its permissions and allow full control.
The weird thing is that every time I open the csv and resave it, the permission for Everyone disappears which means I have to re-add it each time I edit the file. It's time-consuming and annoying, is there any way to set the permission permanently?

A: Excel deletes the original file and creates a new one in its place. (This way, if the system crashes, you get to keep either the new file or the old one – you don't end up with a half-written chunk.)
This results in the new file simply inheriting the default permissions from the parent directory. Although Windows detects this kind of save operation and automatically transfers some attributes from the old file to the new one (through "file system tunnelling"), it doesn't preserve file permissions.
(In other words, the permissions are not permanent because the file itself is not permanent.)
So you will need to grant inheritable permissions to the parent directory, which will automatically grant them to all files in that directory. (If that is a problem – create a dedicated subdirectory just for the CSV file, and grant permissions on that.)
It's really unlikely that you actually need to grant permissions to Everyone. Only the account actually used by Postgres needs read permissions, which could be NT AUTHORITY\NetworkService, or NT SERVICE\PostgreSQL, or something along those lines.


text:
Q: Turn off Paragraph Marks Word 2007 Is there a way to turn off the paragraph marks if they are turned on?
I searched online and did not find anything except ways to check if they are on or off.

A: The ShowAll Property is what you're looking for.
To Turn On:
ActiveWindow.ActivePane.View.ShowAll = True

To Turn Off:
ActiveWindow.ActivePane.View.ShowAll = False

To Check if Paragraph Marks are on, and to then turn them off:
If ActiveWindow.ActivePane.View.ShowAll = True Then
    ActiveWindow.ActivePane.View.ShowAll = False
End If


text:
Q: Switching voltage regulator - exceeding output voltage limits I have been designing a digitally adjustable step-down voltage regulator. Mainly because of the availability and price I chose:

*

*MCP1612-ADJI/MS
I followed the datasheet and created the following schematic:

My plan is to use a DAC integrated in the MCU (ATSAMD21E18A) as shown in the schematic to adjust the output voltage from 1.5 V to 5 V using a 0.. 3 V DAC signal.
My concern is, that with a setup like this, I could "force" (introduce a specific voltage to the feedback pin) the regulator to output voltages like 5.1 V. Could this damage the regulator, or will it just cap on a 100% duty cycle without affecting performance?
VCC is approximately 5.. 5.5 V

A: This is a buck regulator, it's physically impossible for it to output a higher voltage than its input voltage. When you request it to output a voltage that it can't produce, it will drop out of regulation and go to 100% duty cycle. It won't get damaged and will continue to operate normally once you request a "sane" voltage again.


text:
Q: Ubuntu Server Install GUI and Remote Access How can I install a GUI for a remote server and then access it over RDP (or similar)
I've done a sudo apt-get install ubuntu-desktop and sudo apt-get install xrdp, but when I go to access it and login, I just get a blank screen. I presume the windowing system hasn't started?
Thanks

A: Did the desktop fail to start up because there is no display attached?
I think the easiest approach is to use LXDE (Lightweight X11 Desktop Environment) with xrdp.
Refer This Link


text:
Q: Show that if $[E : F] = 2$, then $E$ is a splitting field over $F$? At present, I know this might involve the Factor Theorem/Division Algorithm in $E[x]$ and finding a root in the splitting field $E$, such that the root is not in $F$. Could anyone please elaborate further? Thank you in advance for the help.

A: This area is not my strength, so there may be problems with this answer, but I thought I would give my ideas anyway in case they might be helpful:
Let $F \subseteq E$ be a field extension.  Suppose $[E:F] = 2$.  We want to show $E$ is the splitting field of some polynomial over $F$.
Since $[E:F] = 2$, we have that $\{1, \alpha\}$ is a basis for $E$ as a vector space over $F$, where $\alpha$ is a specific element of $E - F$.  Note that this means we can write $E = F(\alpha)$.  Then, since $\alpha^{2} \in E$, we have $\alpha^{2} = f_{1} + f_{2} \alpha$ for some $f_{1}, f_{2} \in F$, i.e., $\alpha^{2} - f_{2} \alpha - f_{1} = 0$.
Then since $\alpha$ is a root of $h(x) = x^{2} - f_{2}x - f_{1}$ which is a polynomial in $F[x]$, and $h$ is a degree 2 polynomial, it must be that this polynomial splits in $E$.  However, it doesn't split in $F$ since $\alpha \not \in F$.

A: Let $\{1,\alpha\}$ be a basis of $E$ over $F$. Then, from $F\subset F(\alpha)\subseteq E$, we get
$$2=[E:F]=[E:F(\alpha)]\,[F(\alpha):F]$$
and so, since $[F(\alpha):F]>1$, we have $F(\alpha)=2$ and $F(\alpha)=E$.
Thus the minimal polynomial of $\alpha$ has degree $2$ over $F$, let it be $X^2-sX+p$. Since this polynomial factors in $F(\alpha)[X]$ as $(X-\alpha)(X-\beta)$, we have that $\beta=s-\alpha\in F(\alpha)$.

A: We cannot have $E=F$; for that would imply $|E:F
|=1$. Hence choose some $u\in E\backslash F$. Then by Tower's law:
$2=|E:F|=|E:F(u)||F(u):F|$.
Since $|F(u):F|=2$, we must have $|E:F(u)|=1$ and so $E=F(u)$.
The nice thing about the above is that, replacing $2$ by a prime $p$, then if $|E:F|=p$ then $E=F(u)$ for some $u\in E$.
Therefore the degree of the minimal polynomial $m$ of $u$ in $F$ is $2$.
Now just show that $m$ must contain all of its roots in $F(u)$.


text:
Q: Instantiate dynamically buttons on vertical layout group I have the following hierarchy:

I want to instantiate dinamically Game Button into that Button Layout and make them look good.
I'm doing something like this:
public GameObject questionButton;

public void nextRound(){

    foreach (Question elem in questionList)
    {
        GameObject child = Instantiate(questionButton);
        child.transform.SetParent(questionButton.transform,false);
        child.GetComponent<Text>().text = elem.answer;
    }
}

But does not seem to work properly, it doens't get ordener with the layout:

How I can do that?

A: The line:        child.transform.SetParent(questionButton.transform,false);
Should be changed as you are setting the parent as the questionButton. You should be setting it as the layout group. So instead:
public GameObject layoutGroup;
...
child.transform.SetParent(layoutGroup.transform,false);


text:
Q: Windows phone apps with same GUID - Creating more apps from one single app I had made a Windows Phone 7 application. I copy pasted that same application 10 times to create 10 different applications, as the only difference in those 10 apps were the images. But now I cannot install 2 applications on emulator as they have same GUID. I tried using the GUID generator tool and replaced the product id in WMAppManifest.xml file and also the GUID in Assembly Information with the new generated GUID, but as soon as I Rebuild the solution, it goes back to the same old GUID and still replaces other app already installed with same GUID. Can anyone help me why is this happening? Am I missing something?

A: I got it working finally!! It might help somebody who might be stuck just like me.
The mistake I was doing was I was entering the GUID generated by the tool in UpperCase while it has to be put in "LowerCase". The GUID Generator tool in Visual Studio 2012 generates a GUID something like this: "AAB123-xxxx-xxxx-xxxxxxx" while what the WMAppManifest.xml file takes is: "aab123-xxxx-xxxx-xxxxxxx".
So the steps to change GUID of any project is as follows:

*

*Go to www.guidgen.com

*Copy the GUID.

*Open Assembly Information and paste it in the GUID field (in lowercase only).

*Open WMAppManifest.xml file and paste it again in the productID field (again in lowercase only)

*Rebuild and deploy the solution.

A: To avoid the GUID issue copy the projects following next steps:

*

*Copy the project folder

*Change the name to the .csproj file

*Add the copyed project to the solution: Right click on solution -> Add -> Existing
project...

*Open the WMAppManifest.xml file and replace the Product ID (you can use a generator)

This works for me. If I deploy multiple projects to the phone I can see all of them ther, they're not replaced.


text:
Q: Combinator pattern I'm having a little issue with the result I'm getting with 'Combinator' pattern.
public interface CustomerRegistrationValidator
    extends Function<Customer, ValidationResult> {

    static CustomerRegistrationValidator isEmailValid() {
        return customer -> customer.getEmail().contains("@") ?
                    ValidationResult.SUCCESS : ValidationResult.EMAIL_NOT_VALID;
    }

    static CustomerRegistrationValidator isPhoneNumberValid() {
        return customer -> customer.getPhoneNumber().startsWith("+0") ?
                    ValidationResult.SUCCESS : ValidationResult.PHONE_NUMBER_NOT_VALID;
    }

    static CustomerRegistrationValidator isAnAdult() {
        return customer -> Period.between(customer.getDob(), LocalDate.now()).getYears() > 16 ?
                    ValidationResult.SUCCESS : ValidationResult.IS_NOT_AN_ADULT;
    }

    default CustomerRegistrationValidator and (CustomerRegistrationValidator other) {
        return customer -> {
            ValidationResult result = this.apply(customer);

            return result.equals(ValidationResult.SUCCESS) ? other.apply(customer) : result;
        };
    }

    enum ValidationResult {
        SUCCESS,
        PHONE_NUMBER_NOT_VALID,
        EMAIL_NOT_VALID,
        IS_NOT_AN_ADULT
    }

}

public class Main {
    public static void main(String[] args) {

            Customer customer = new Customer(
                    "Alice",
                    "alicegmail.com",
                    "089877878",
                    LocalDate.of(2000, 1, 1)
            );

            ValidationResult result = CustomerRegistrationValidator.isEmailValid()
                .and(CustomerRegistrationValidator.isPhoneNumberValid())
                .and(CustomerRegistrationValidator.isAnAdult())
                .apply(customer);

            System.out.println(result);

            if (result != ValidationResult.SUCCESS) {
                throw new IllegalStateException(result.name());
            }
    }
}

Let's say if there are two errors from those methods(isAnAdult, isEmailValid).Why does it print only one from enum types, in my case 'EMAIL_NOT_VALID' with exception instead of two and by the second one I mean 'IS_NOT_AN_ADULT' ?

A: If you want a validator to be able to return multiple distinct result codes (enums), then you need to change the return type to Set<ValidationResult>, or more specifically an EnumSet.
E.g. something like this:
interface CustomerRegistrationValidator
    extends Function<Customer, EnumSet<ValidationResult>> {

    static final EnumSet<ValidationResult> SUCCESS_ONLY = EnumSet.of(ValidationResult.SUCCESS);

    static CustomerRegistrationValidator isEmailValid() {
        return customer -> customer.getEmail().contains("@") ?
                    SUCCESS_ONLY : EnumSet.of(ValidationResult.EMAIL_NOT_VALID);
    }

    static CustomerRegistrationValidator isPhoneNumberValid() {
        return customer -> customer.getPhoneNumber().startsWith("+0") ?
                    SUCCESS_ONLY : EnumSet.of(ValidationResult.PHONE_NUMBER_NOT_VALID);
    }

    static CustomerRegistrationValidator isAnAdult() {
        return customer -> Period.between(customer.getDob(), LocalDate.now()).getYears() > 16 ?
                    SUCCESS_ONLY : EnumSet.of(ValidationResult.IS_NOT_AN_ADULT);
    }

    default CustomerRegistrationValidator and(CustomerRegistrationValidator other) {
        return customer -> {
            EnumSet<ValidationResult> thisResult = this.apply(customer);
            EnumSet<ValidationResult> otherResult = other.apply(customer);
            if (thisResult.equals(SUCCESS_ONLY))
                return otherResult;
            if (otherResult.equals(SUCCESS_ONLY))
                return thisResult;
            EnumSet<ValidationResult> combinedResult = EnumSet.copyOf(thisResult);
            combinedResult.addAll(otherResult);
            return combinedResult;
        };
    }

}


text:
Q: Flag setting issue in React So basically I'm trying to tie in the Login and Sign Up component to the Main component by making use of onClick action of a button.
Given below is the code segment
 function Dev({value}){
    const [isButton, ButtonClicked ] = useState(false);
    const handleClick=()=> ButtonClicked(!isButton);
    return(

            <Card>
                <CardImg top width="100%" src={value.src} alt="Card image cap" />
                <CardBody>
                    <CardTitle className='text-card'>{value.title}</CardTitle>
                    <CardText className='text-text'>{value.text}</CardText>
                    <Button className='text-button' onClick={handleClick}>{value.button}</Button>
                </CardBody>
            </Card>
            {isButton && (value.id ? <Login open={true} /> : <Sign open={true}/>)}

);
}

The code works fine, but there is an issue.
When I first click on the button, isButton will be set to true and the Login component will pop up. After closing it, I have to click twice on the button to render the Login component again.
I know the reason behind this; when I click on the button the second time isButton will be toggled to false and I should click again to toggle it to true. This is kind of inappropriate, is there any way to work around this issue?
The code for Login Component
const Login = (props) => {

    const [modal, setModal] = useState(props.open);

        const toggle = () => setModal(!modal);

        return (

                <Modal isOpen={modal} toggle={toggle}>
                    <ModalHeader toggle={toggle}>Login</ModalHeader>
                    <ModalBody>
                         .
                         .
                         .
                   </ModalBody>
            </Modal>

    );
}

export default Login;


text:
Q: Combine rows into one, replace NA I have the following dataframe: (this is just a small sample)
VALUE COUNT    AREA n_dd-2000 n_dd-2001 n_dd-2002 n_dd-2003 n_dd-2004 n_dd-2005 n_dd-2006 n_dd-2007 n_dd-2008 n_dd-2009 n_dd-2010
2    16  2431  243100        NA        NA        NA        NA        NA        NA  3.402293  3.606941  4.000461  3.666381  3.499614
3    16  2610  261000  3.805082  4.013435      3.98  3.490139  3.433857   3.27813        NA        NA        NA        NA        NA
4    16 35419 3541900        NA        NA        NA        NA        NA        NA        NA        NA        NA        NA        NA

and I would like to combine all three rows into one row replacing NA with the number that appears in each column (there's only one number per column). Just ignore the first three columns.  I used this code:
bdep[4,4:9] <- bdep[3,4:9]

to replace NA's with numbers from another row, but can't figure out how to repeat it for all the columns.  The columns 4 and beyond have a sequence in each row of six numbers followed by 20 NA's, so I've tried going down the road of using lapply() and seq() or for loops, but my efforts are failing.

A: I did a simple solution by replacing the NA:s with zeroes and adding all rows per column. Did this work?
#data
bdep <- rbind(c(rep(NA,6),3.402293,3.606941,4.000461,3.666381,3.499614),
              c(3.805082,4.013435,3.98,3.490139,3.433857,3.27813, rep(NA,5)),
             c(rep(NA,11)))

#solution
bdep2 <- ifelse(is.na(bdep), 0, bdep)
bdep3 <- apply(bdep2, 2, sum)
bdep3 #the row you want?

A: I finally came to a solution by patching together some code I found in other posts (esp. sequencing and for loops). I think this would be considered messy coding, so I'd welcome other solutions. This should better describe what I was trying to do in the OP, where I was trying to generalize too much.  Specifically, I have 17 variables, measured over 14 years (that's 238 columns), and something happened while generating these data where the first 6 years of a variable are in one row and the following 8 years are in the other row, so instead of re-run the model, I just wanted to combine the two rows into one.
Below are some sample data, simplified from my real scenario.
Create the data frame:
df <- data.frame(
  VALUE = c(16, 16, 16),
  COUNT = c(2431, 2610, 35419),
  AREA = c(243100, 261000, 3541900),
  n_dd_2000 = c(NA, 3.805, NA),
  n_dd_2001 = c(3.402, NA, NA)
)

The next two lines establish a sequence starting a pattern at column 4, repeating every 1 column, repeated 2 times out in the first line, 1 time out in the second line, and how many times to repeat the sequence:
info <- data.frame(start=seq(4, by=1, length.out=2), len=rep(1,2))
info2 <- data.frame(start=seq(5, by=1, length.out=1), len=rep(1,2))

This is the code from my real dataset, where I started at column 4, repeated the pattern every 14 columns, out 17 times, and looked at the first 6, then 8 columns: info <- data.frame(start=seq(4, by=14, length.out=17), len=rep(c(6,8),17))
The two for loops below write the specified values in the sequence from row 2 and row 1 to row 3, respectively:
foo = sequence(info$len) + rep(info$start-1, info$len)
foo2 = sequence(info2$len) + rep(info2$start-1, info2$len)
for(n in 1:length(foo)){
  df[3,foo[n]] <- df[2,foo[n]]
}
for(n in 1:length(foo2)){
  df[3,foo2[n]] <- df[1,foo2[n]]
}

Then I removed the first two rows I got those values from and I'm left with one complete row, no NA's:
df <- df[-(1:2),]


text:
Q: Smarty templates i18n I just wonder about an easy way to make i18n inside Smarty templates.
Something like gettext() which I already use inside my PHP scripts.
Any ideas?

A: My recent attempt to use intSmarty (http://code.google.com/p/intsmarty/) was unsuccessful -- it seemed to me that the intSmarty class is not compatible with the latest Smarty code, which isn't surprising since the intSmarty design broke encapsulation by overriding a private method.
This one:
http://blog.piins.com/2008/03/first-piins-os-release-smarty-i18n.html
sounds interesting but I've found the documentation lacking. I've got a test install up and I'm trying to decipher the example code enough to see if it is really useful.
There's http://sourceforge.net/projects/smarty-gettext/ which I haven't evaluated yet, but plan to do so.
Love to see what others have found as well


text:
Q: lattice theory questions about ideals Let $L$ be a (bounded) lattice
a) Give an example of an ideal in $L$ that is not a normal ideal. (A normal ideal is the element in $DM(L)$, Dedekind-MacNeille completion
This question I think about an infinite lattice L, but I don't know which one will work.
b) Is it true that if $L$ is complete, then $L$ is isomorphic to $\mathbb{I}\left(L\right)$, where $\mathbb{I}\left(L\right)$ is the set of all ideals of $L$?
I think it is not true, but quite stuck.
Any hint is appreciated. Thank you.

A: An example of a lattice with a non-normal ideal is the following:

Here, if $I = \{0,a_1,a_2,\ldots\} = L\setminus\{b,1\}$, then $I^{ul}=L$, because $1$ is the only upper bound of $I$.
In this answer there is an example of a complete lattice $\mathbf L$ that is not isomorphic to its ideal lattice (in that case, labelled $\mathbf K$).


text:
Q: UnhandledPromiseRejectionWarning: Error: Invalid integer: New to JSReact, trying to make an e-commerce store fully functional with Stripe.
I'm getting this error in function emulation
UnhandledPromiseRejectionWarning: Error: Invalid integer: $({getBasketTotal(basket) * 100})
and I think the problem is here at the create?total...:
Code down below

useEffect(()   =>{

        const getClientSecret = async () => {
                const response = await axios({
                    method: 'post',
                    url: 'payments/create?total=$({getBasketTotal(basket) * 100})'
                });
                setClientSecret(response.data.clientSecret)
        }

            getClientSecret();
    }, [basket])

A: i think the problem is in your template literal
url: 'payments/create?total=$({getBasketTotal(basket) * 100})'  - print text as it is.
url: 'payments/create?total=${getBasketTotal(basket) * 100}' - prints the value

A: You need to use backticks instead of single quotes if you want to do string interpolation:
url: `payments/create?total=${getBasketTotal(basket) * 100}`


text:
Q: C++ static member initialization order I have a code which has been in use for a long time which has a scenario like following.
There are two classes, A and B.
A class has a public static variable static B* pB;
B class has a static object of itself (static B instance;).
In B constructor I set A::pB = this;
My question is, since static variable initialization order is undefined, if b::instance got initialized before A::pB, making B constructor to get called first and it tries to set A::pB which is uninitialized yet, could it lead to a problem?
My current code runs without any unexpected behavior. Wanted to find out whether it is just my luck or not
(Initialization of A::pB and B::instance happens in different translation units)

A: There are three parts to initialization, zero initialization,
static initialization and dynamic initialization.  (Zero
initialization is actually part of static initialization, but
it's often convenient to keep them separate.)  They occur in
that order.
If you don't specify any initialization for static B* A::pb;,
it will be zero initialized (before anything else), and nothing
else.  If you specify a constant initializer, e.g.
B* A::pb = nullptr;

, that will also occur before any dynamic initialization.
What happens in a constructor is dynamic initialization, so
there should be no problem with your code unless A::pb also
has dynamic initialization, something like:
B* A::pb = someFunctionReturningABStar();

And finally: the default constructor for pointer is trivial; the
pointer is effectively "constructed" when the program is loaded,
before any code is executed.  So there could never be a problem
due to assigning to pB in a constructor.  The only problem
could occur if there was dynamic initialization of the pointer,
which might occur after the assignment in the constructor of
B::instance, and overwrite it.
And of course, until B::instance is constructed, any other
code will see a null pointer in A::pb.


text:
Q: How to check to see if there is a decimal in textbox I am new to c#. I am making a universal app and trying to have a user only be able to input one decimal into a textbox. I have seen that a lot of people suggesting to use KeyPressed event but that does not work for me. So far I have the following working code:
private void tbTotal_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key < Windows.System.VirtualKey.Number0 || e.Key >= Windows.System.VirtualKey.Number9)
        {
            if (e.Key < Windows.System.VirtualKey.NumberPad0 || e.Key >= Windows.System.VirtualKey.NumberPad9)
            {
                if (e.Key == Windows.System.VirtualKey.Decimal)
                {
                        e.Handled = true;
                }
            }
        }
    }

How am I able to get it to allow only one decimal? Thank you in advance.

A: private void tbTotal_KeyDown(object sender, KeyEventArgs e)
    byte a = (byte)e.KeyCode;
    if(e.KeyCode!=Keys.Delete)
    if(a!=8&&a!=13)
    if(a<48||a>57) e.Handled = true;
}


text:
Q: CSS Dropdown Menu snaps/resizes on hover Today I was trying to learn how to create those triangles with CSS Borders and I finally did. Awesome stuff! Although it seems that whenever I hover over the menu two things happen that I want to fix (1) the menu seems to snap and resize on hover and resize back on mouse out. (2) the hover opacity seems to flow down to the first item of the sub-menu. I've created a JSFiddle over here. If anyone can drop some knowledge on me, I'd be very grateful!
HTMLCode
<!DOCTYPE html>

<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Document</title>

Home

Sub-Item

Sub-Item

Sub-Item

Safari

Sub-Item

Sub-Item

Sub-Item

Prices

Sub-Item

Sub-Item

Sub-Item

Photos

Sub-Item

Sub-Item

Sub-Item

Contact

Sub-Item

Sub-Item

Sub-Item

CSS Code
html {
font-size: 62.5%;
}

body {
background: #fff;
font-size: 1.6em;
}

.navContainer {
width: 1100px;
margin: 0 auto;
}

ul.nav {
margin: 0;
padding: 0;
position: relative;
left:30%;
font-size: 1.3rem;

}

li {
float: left;
list-style-type:none;
text-align: center;
background: #aa2929;

}

li a {
display: block;
text-decoration: none;
color: #fff;
color: rgba(255,255,255, 0.7);
text-shadow: 0 1px 1px rgba(0,0,0,0.5);
padding: 1rem 2rem;
transition: all .3s ease-in-out;

}

li a:focus,
li a:hover {
color: #fff;
background: #a85555;
background: rgba(255,255,255, 0.15);
}

ul.subNav {
margin: 0;
padding: 0;
}

ul.subNav li {
float: none;
display: none;

}

.nav li:hover ul.subNav li  {
display: block;
}

.group:after {
content: "";
display: table;
clear: both;
}

li a.active:hover:after {
content: "";
box-sizing: border-box;
display: block;
margin: 0 auto;
padding: 0;
width: 0;
height: 0;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-bottom: 7px solid rgba(89, 172, 255, 0.83);
}

A: It's because your "Sub-Items" are wider than your main nav elements, so when you hover and the Sub-Items are shown, the parent (main nav element) has to expand to fit it.
Putting a fixed width on .nav.group > li should solve your problem.
Another option is to absolute-position the dropdowns.

A: position absolute on your subNav and a fixed width on the parent list items ( .nav li) will fix the issue
.nav li{
    width:80px; /* I used 80px as example */
}
.subNav{
    position:absolute;
}

Add the above to the base of your css it will fix it.
Code Snippet...

html {
  font-size: 62.5%;
}
body {
  background: #fff;
  font-size: 1.6em;
}
.navContainer {
  width: 1100px;
  margin: 0 auto;
}
ul.nav {
  margin: 0;
  padding: 0;
  font-size: 1.3rem;
}
li {
  float: left;
  list-style-type: none;
  text-align: center;
  background: #aa2929;
}
li a {
  display: block;
  text-decoration: none;
  color: #fff;
  color: rgba(255, 255, 255, 0.7);
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
  padding: 1rem 2rem;
  transition: all .3s ease-in-out;
}
li a:focus,
li a:hover {
  color: #fff;
  background: #a85555;
  background: rgba(255, 255, 255, 0.15);
}
ul.subNav {
  margin: 0;
  padding: 0;
}
ul.subNav li {
  float: none;
  display: none;
}
.nav li:hover ul.subNav li {
  display: block;
}
.group:after {
  content: "";
  display: table;
  clear: both;
}
li a.active:hover:after {
  content: "";
  box-sizing: border-box;
  display: block;
  margin: 0 auto;
  padding: 0;
  width: 0;
  height: 0;
  border-left: 7px solid transparent;
  border-right: 7px solid transparent;
  border-bottom: 7px solid rgba(89, 172, 255, 0.83);
}
.nav li {
  width: 80px;
}
.subNav {
  position: absolute;
}
.nav > li > a {
  height: 1.5em;
}

        Home

Sub-Item

Sub-Item

Sub-Item

        Safari

Sub-Item

Sub-Item

Sub-Item

        Prices

Sub-Item

Sub-Item

Sub-Item

        Photos

Sub-Item

Sub-Item

Sub-Item

        Contact

Sub-Item

Sub-Item

Sub-Item

Hope this helps


text:
Q: PHP - Using http_build_query for pagination is giving me repeated parameters I have this code for pagination
if($pages > 1 && $set <= $pages) {
         ?>

         <?php
         if($set > 1) {
             ?>
             <a href="?<?php echo http_build_query($_GET); ?>&page=1"> <<<
               |
             <a href="?<?php echo http_build_query($_GET); ?>&page=<?php echo ((int)$set - 1) ?>"><<
               |
             <?php
         }

         for($i = 1; $i <= $pages; $i++) {
             ?>
             <a href="?<?php echo http_build_query($_GET); ?>&page=<?php echo $i.""; ?>"><?php echo $i; ?>  |
             <?php
         }
         if($set < $pages) {
             ?>
             <a href="?<?php echo http_build_query($_GET); ?>&page=<?php echo ((int)$set + 1); ?>">>>
               |
             <a href="?<?php echo http_build_query($_GET); ?>&action=list&page=<?php echo $pages; ?>"> >>>
             <?php
         }
         ?>

        <?php
     }

The pagination bar looks perfect:
1  |   2  |   3  |   4  |   >>   |    >>>
or
<<<    |   <<   |   1  |   2  |   3  |   4  |   >>   |    >>>
The problem is that (for example) when I am in the page 1...
and then I click Page 3 I get an URL LIKE THIS:
mypage.php?item=products&page=1&page=3

as you can see there are two 'page' parameters... how can I avoid this? It still works and it shows the correct page, it seems to be ignoring the first get parameter with the same name that was passed through the URL.

A: Use array_unique function
$_GET = array_unique ( $_GET );

Or better use preg_replace function:
$query = http_build_query($_GET);
$query = preg_replace('/page=\d*/i', '', $query);

So
<?php
if($pages > 1 && $set <= $pages) {
     $query = http_build_query($_GET);
     $query = preg_replace('/page=\d*/i', '', $query);
     ?>

     <?php
     if($set > 1) {
         ?>
         <a href="?<?php echo $query ?>&page=1"> <<<
           |
         <a href="?<?php echo $query ?>&page=<?php echo ((int)$set - 1) ?>"><<
           |
         <?php
     }

     for($i = 1; $i <= $pages; $i++) {
         ?>
         <a href="?<?php echo $query ?>&page=<?php echo $i.""; ?>"><?php echo $i; ?>  |
         <?php
     }
     if($set < $pages) {
         ?>
         <a href="?<?php echo $query ?>&page=<?php echo ((int)$set + 1); ?>">>>
           |
         <a href="?<?php echo $query ?>&action=list&page=<?php echo $pages; ?>"> >>>
         <?php
     }
     ?>

    <?php
 }


text: Q: global action type of lightning component is not visible under link type [tile menu] in lightning community I am trying to add global action type of lightning component in line type [tile menu] in lightning community, but it is not visible. I found that only global action is visible whose record type is accessible to user. But in my case, it is not object specific action. is some other configuration needed to achieve this?


text:
Q: React - Calling a specific function when 'Enter' key is pressed Didn't succeed in using this thread to help.
I have button div with an onClick that invokes a handleSendMessage.
I want this handleSendMessage to be invoked whenever a user presses the 'Enter' key
while on the page.
How can I do that?
Component looks like this :
    const ChatScreen = () => {
      const [message, setMessage] = useState("");
      const dispatch = useDispatch();
      let chatsFromState = useSelector(state => state.chatsState.chats);

      const socket = io("localhost:4000");

      socket.on("RECEIVE_MESSAGE", msgReceived => {
        console.log("msgReceived ", msgReceived);
      });

      const handleChange = e => setMessage(e.target.value);

      const handleSendMessage = async () => {
        socket.emit("SEND_MESSAGE", message);
        await dispatch(sendMessage(message));
        setMessage("");
      };

      return (

HI

          <input
            value={message}
            onChange={handleChange}
            placeholder="Your message here..."
          />

            Send

            {chatsFromState.map((chat, i) => (

                message : {chat.message}

            ))}

      );
    };

    export default ChatScreen;

A: Adding a onKeyPress keyboard event to your input element you could capture the key event and then check for the key Enter.
The event happens in the input since this is where the user has focus, if the user clicked anywhere else on the page, the focus would be lost and this won't work anymore. The trick here is thinking where the focus might be and listen to that.
Here is a very retrieved example, just be sure to focus on the input and hit Enter, a message will be logged:

const ChatScreen = () => {
  const handleChange = (e) => {
    if (e.key === 'Enter') {
      console.log('setMessage');
    }
  }

  return (<input type="text" onKeyPress={handleChange} />);
}

const root = document.getElementById('container')

ReactDOM.render(<ChatScreen />, root)


text:
Q: Android: Create Horizontal List View but Image size cannot be set I'd like to create an Horizontal List View.
And I reference this http://www.dev-smart.com/archives/34
But it set ImageView size 150dp in "listitem.xml"
<ImageView
      android:id="@+id/image"
      android:layout_width="150dip"
      android:layout_height="150dip"
      android:scaleType="centerCrop"
      android:src="@drawable/icon"
      />

I tried to change the width and height of the ImageView, but it's useless.
It seems that in the HorizontalListView.java, the function "addAndMeasureChild()" has set
child.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
                MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));

But I change the MEasureSpec to EXACTLY or others, it's still useless.
Anyone can figure out this?
Thanks in advance.
Eric

A: MeasureSpec.makeMeasureSpec(getWidth()... is the width of the listview, try replacing getWidth() with params.width, this worked for me using a fixed size for the layout, in your case, the imageview. My solution doesn't work if you use MATCH_PARENT or WRAP_CONTENT.


text:
Q: Content-based filtering recommendation system for a group Is there any example of content-based filtering recommendation for a group of observations? For example, user can choose a group of 10 movies they like the most, and the recommendation engine will return a list of movies that are most similar to the 10 movies they have chosen.
For a single observation I know we will calculate the distance between the single observation and the rest of the data, but for this group scenario, what would be the best way to implement it?


text:
Q: How to notate a diagonal matrix with a offset Is there standard notation for a diagonal matrix with a $d$ offset.
for example, when $d = 1$, we have:
M = $\begin{bmatrix} 1 & 1 & 0 & 0 & 0 \\ 1 & 1 & 1 & 0 & 0 \\ 0 & 1 & 1 & 1 & 0 \\ 0 & 0 & 1 & 1 & 1 \\ 0 & 0 & 0 & 1 & 1 \end{bmatrix}$
And,this definition 'a diagonal matrix with a $d$ offset' seems inaccurate, is there standard definition or name for it?


text:
Q: How to Encode Authorization:Bearer How to Encode Authorization:Bearer parameter value in PostMan. It is passed in Header as a JSON request.
http://localhost:52586/api/Location1/6

Content-Type:application/json
Authorization:Bearer {{Location1AdminToken}}


text:
Q: JavaFX Button with multiple text lines I need to create a toolbar in my screen that will have multiple buttons, and each button must have multiple lines of Text. For example:

I looked over the internet and StackOverflow but I couldn't find anything showing how to do this in JavaFX. I'm using JavaFX 8.
Someone could help me, please?
Tks

A: Also you can use the wrapTextProperty. But you have to set toolbar height greater than expected button height.
Button btn = new Button();
btn.wrapTextProperty().setValue(true);
// or btn.setWrapText(true);
btn.setText("Some looooooooooooong text");

Or if you want to determine exactly where the line should be wrapped, you can go this way:
Button btn = new Button();
btn.setText("Line1\n Line2\n Line3");

Last way will work without changing toolbar height.

A: I resolved this problem including a VBox inside my button, and then including several Labels inside the VBox. Like this:

The result is:

If there is a more elegant way to have the same result, please, let me know.
Thank you.

A: In the button text property select "switch to multi-line mode
"

A: From sobolev's response, you can do:
Button btn = new Button();
btn.setText("Line1\n Line2\n Line3");
button.textAlignmentProperty().set(TextAlignment.CENTER);

This will create 3 lines of text and allign them in the center of your button.

A: My solution is pretty much the same as the one given by the OP, but instead of Label uses Text so it's more flexible to changes in the size of the button, as it will use as many lines as needed. If required, also one can set a wrapping width, to define a width constraint.
@Override
public void start(Stage primaryStage) {
    Button btn = new Button();
    ImageView imageView = new ImageView(new Image(getClass().getResource(<image>).toExternalForm()));
    Text text=new Text("Some long text that may be line wrapped");
    text.setWrappingWidth(100);
    VBox vBox = new VBox(5, imageView,text);
    vBox.setAlignment(Pos.CENTER);
    btn.setGraphic(vBox);
    btn.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);

    Scene scene = new Scene(new StackPane(btn), 300, 250);

    primaryStage.setScene(scene);
    primaryStage.show();
}

A: Label label= new Label("your long text here");
label.setStyle("-fx-max-width : 180px);
label.setWrapText(true);


text:
Q: How to explain that the same answer was given before A student out of the audience asks something similar to a question a lecturer answered previously in a dialogue with another student. What can the lecturer say in responce in this situation? Of course, I'm asking about idiomatic and colloquial phrases. Should the lecturer give the answer in the present simple or in the present continuous?

The same [that I said before] is referring to your question too.
What I said 5 minutes ago applies to your question too.

I also consider possibility of using verbs 'belong', 'concern', etc. Could you suggest something appropriate for this type of situations?

A: Use something like:
1: "What I said 5 minutes ago applies to your question too."
2: "What I said five minutes ago answers this question."
3: "I thought I answered that five minutes ago -- can you point me to where I need to clarify?"


text:
Q: Anonymous class creation can not be evaluated. Java Design Eclipse When I want to open the Design tab in Eclipse, I get this error:
Anonymous class creation can not be evaluated.
In general case it is impossible to evaluate creation of anonymous class. So, expression ...
new AbstractFormatterFactory() {
    @Override public AbstractFormatter getFormatter(JFormattedTextField tf) {
        NumberFormat format = DecimalFormat.getInstance();
        format.setMinimumFractionDigits(2);
        format.setMaximumFractionDigits(2);
        format.setRoundingMode(RoundingMode.HALF_UP);
        InternationalFormatter formatter = new InternationalFormatter(format);
        formatter.setAllowsInvalid(false);
        formatter.setMinimum(0.0);
        return formatter;
    }
}

... was not evaluated.
The problem is in this block:
final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));

textField1.setFormatterFactory(new AbstractFormatterFactory() {

    @Override
    public AbstractFormatter getFormatter(JFormattedTextField tf) {
        NumberFormat format = DecimalFormat.getInstance();
        format.setMinimumFractionDigits(2);
        format.setMaximumFractionDigits(2);
        format.setRoundingMode(RoundingMode.HALF_UP);
        InternationalFormatter formatter = new InternationalFormatter(format);
        formatter.setAllowsInvalid(false);
        formatter.setMinimum(0.0);
        return formatter;
    }
});

How can I solve this anonymous class thing?

A: What is this warning stopping you from doing other then viewing it in a Design tool?
If it is causing a concern it will be due to a random bug in the plugin.
To work out the likely cause, comment out the whole function, test it is okay not and add back the method a line at a time to see when breaks the plugin.


text:
Q: Windows Azure ignoring files with unknown extensions I have uploaded my website to windows azure. The website is working properly on the local server.
I am uploading images to the server.
ISSUE:
If the files had some weird names like  2013_6_5_15_12_33_144pwzve.lg2
Windows azure shows 404 error
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
But works with this file name 2013_6_5_12_1_5_SampleStudent.png
I created some sample page to check if file is uploaded successfully it is.
All the files are on the server.
I checked using grid
grvNotSent.DataSource = Directory.GetFiles(Server.MapPath("~/Test"));
Any idea?
Any help is appreciated
Thanks

A: what is LG2? Have you added a mime type for that file extension in the web.config?
You can add the mime type mapping like this:
  <system.webServer>
      <staticContent>
         <mimeMap fileExtension=".lg2" mimeType="whatever_this_type_is" />
      </staticContent>
   </system.webServer>

When IIS sees unknown mime type it ignores the request with 404.


text:
Q: Error library not loaded after installing php7.2 dyld: Library not loaded: /usr/local/opt/tidy-html5/lib/libtidy.5.dylib
  Referenced from: /usr/local/opt/php@7.2/bin/php
  Reason: image not found

The library is already installed and it's visible in Cellar/, however, when trying to run anything with php, returns that error. If
I try to manually link, says that it's already linked.:
"brew link tidy-html5
Warning: Already linked: /usr/local/Cellar/tidy-html5/5.8.0
To relink, run:
  brew unlink tidy-html5 && brew link tidy-html5"

No idea what to do, already tried reinstalling everything.. the php, the library, the node, everything...


text:
Q: How to popup json data in Angular?   "devices": [
    {
      "sub_family": "6s Plus",
      "presales_description": "iPhone 6 Plus features a stunning 5.5-inch Retina HD display, amazing cameras and many advanced features, all in a breakthrough design. A 5.5-inch Retina HD display. An A8 chip with 64-bit desktop-class architecture. 8MP iSight camera with Focus Pixels and optical image stabilisation. Touch ID. Fast 4G LTE and Wi-Fi.1 Long battery life.2 And iOS 9 and iCloud.",
      "Camera": true,
      "device_type": "smartphone",
      "presales_vendor": "Apple",
      "sim_form-factor": "Nano",
      "memory": 64,
      "device_class": "HC14",
      "TV Capable": true,
      "family": "iPhone",
      "specification_reference": "D20",
      "variants": [
        {
          "colour": "Space Grey",
          "default": true,
          "presales_sequence": 961,
          "s_code": "S0346715",
          "credit_risk": 750,
          "colour_code": "#898989",
          "max_credit_term": 24,
          "list_price": 759,
          "presales_start_date": "02/04/2016"
        },
        {
          "colour": "Silver",
          "default": true,
          "presales_sequence": 961,
          "s_code": "S0346717",
          "credit_risk": 750,
          "colour_code": "#e5e5e5",
          "max_credit_term": 24,
          "list_price": 759,
          "presales_start_date": "02/04/2016"
        }]}

This is  the code I tried:
View full spec

x

{{data.colour}}


text:
Q: Após destruir o Datatable, próximo carregamento apresenta erro : Cannot read property 'column' of undefined Quando carrega o datatable pela primeira vez, tudo funciona normalmente, as colunas da tabela são visualizadas sem problema.
Mas quando atualizo a tabela com novo parametro de filtro, a tabela não é carregada, e fica mostrando a mensagem carregando, e apresenta o erro:

VM26416:1 Uncaught TypeError: Cannot read property 'column' of undefined
      at ResponsiveDatatablesHelper.createExpandIcon (:1:4640)
      at n.fn.init.rowCallback (eval at globalEval (jquery.min.js:2), :329:31)

    // Carregamento a tabela na primeira vez
$(document).ready(function() {
        AjaxDatatable();
});

// função da tabela
AjaxDatatable(valorNovoParametro);

// função que cria a tabela
    function AjaxDatatable(Pint_PeriodoAtividades){
        //alert(Pint_PeriodoAtividades);
        var tabelaGrid;
        //$('#dt_basic').DataTable().destroy();
        tabelaGrid = $('#dt_basic').DataTable({
            "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>>" +
            "t"+
            "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>r>",
            "bProcessing": true,
            "bServerSide": true,
            "autoWidth" : true,
            "searching": false,

            "bretrieve": true,
            "bDestroy": true,

            "order":[],
            "lengthMenu": [[10,5,15,20,25,50,100], [10,5,15,20,25,50,100]],
            "oLanguage": {
                "sProcessing":   'Carregando dados... ',
                "sLengthMenu":   "Mostrar _MENU_ registros",
                "sZeroRecords":  "Não foram encontrados resultados",
                "sInfo":         "Mostrando de _START_ até _END_ de _TOTAL_ registros",
                "sInfoEmpty":    "Mostrando de 0 até 0 de 0 registros",
                "sInfoFiltered": "",
                "sInfoPostFix":  "",
                "sSearch":       "Buscar: ",
                "sUrl":          "",
                "deferRender": true,
                "oPaginate": {
                    "sFirst":    "Primeiro",
                    "sPrevious": "&laquo Anterior",
                    "sNext":     'Seguinte &raquo' ,
                    "sLast":     "Último"
                }
            },
            "ajax": {
                url: "<?php echo $Pstr_UrlControlador.'Pctrl_PreencherTabelaGrid/'?>",
                type:"POST",

                data: function( d ) {
                    d.Pint_IdInteressado= 0;
                    d.Pint_StatusAtividade= 0;
                    d.Pint_TipoAtividade= 2;
                    d.Pint_PeriodoAtividades= 0;
                },

            },
            stateSave: true,

            "columns": [

                { "data": "id" },
                { "data": "status" },
                { "data": "finalizada" },
                { "data": "dtagendamento" },
                { "data": "titulo" },
                { "data": "campanha" },
                { "data": "interessado" },
                { "data": "periodo" },
                { "data": "action" },

            ],

            "columnDefs":[
                { "targets": [0,1,2,7,8], "searchable": false, "orderable": false, "visible": true }
            ],
            "preDrawCallback" : function() {
                Gjs_MarcarDesmarcarCheckbox(false);
                // Initialize the responsive datatables helper once.
                if (!responsiveHelper_dt_basic) {
                    responsiveHelper_dt_basic = new ResponsiveDatatablesHelper($('#dt_basic'), breakpointDefinition);
                }
            },
            "rowCallback" : function(nRow) {

                responsiveHelper_dt_basic.createExpandIcon(nRow);
            },
            "drawCallback" : function(oSettings) {

                responsiveHelper_dt_basic.respond();
                $('[data-toggle="tooltip"]').tooltip();  // para poder funcionar o tooltip em datatables
            }
        });

    }

 //HTML
    <form action="<? echo $Pstr_UrlControlador.'Gctrl_DeletarRegistroSelecionado' ?>" method="post" name="form_tabela" id="form_tabela">

    Status
    Finalizada
    Data
    Titulo
    Campanha
    Lead
    Período
     Ação

    </form>

A: Resolvi o problema retirando do script o código:
"rowCallback" : function(nRow) {
 responsiveHelper_dt_basic.createExpandIcon(nRow);
},
Depois que exclui essa parte do código, funcionou!!!!


text: Q: how to make free hand draw polygon in flutter web how to make web site map with free hand draw polygon using flutter web. I tried using google_maps_flutter plugin it works on android but I need develop in web also.


text:
Q: Visual Studio 2015 "Run All" Link Defaulting to Another Culture I have a .Net 3.5 ASP.Net project with a separate unit test .Net 4.0 project that I use Visual Studio 2015 to edit.
When I run the unit tests separately by method or class, the tests pass as expected.
Some of the tests fail when I click the "Run All" link in the Test Explorer or commit the source changes to activate an on premise Team Foundation Server 2015 build script.
I have identified the problem to the thread culture defaulting to Germany in the "Run All" link and build server instances versus passing tests running as English (United States).
I am editing this code and running it in production in Ohio without any requirements for any other culture settings. How do I default the MSTest to English (United States) and why does MSTest run in a German culture?


text:
Q: How to call Base class method through base class pointer pointing to derived class class Base
{
  public:
    virtual void foo()
    {}
};

class Derived: public Base
{
  public:
    virtual void foo()
    {}
};

int main()
{
    Base *pBase = NULL;
    Base objBase;
    Derived objDerived;

    pBase = &objDerived;
    pBase->foo();

    /*Here Derived class foo will be called, but i want this to call
    a base class foo. Is there any way for this to happen? i.e. through
    casting or something? */
}

A: You can do it through scope resolution operator ::
Something like this:
pBase->Base::foo()

A: pBase->Base::foo()

A: Both responses above are correct...But be careful, if you need to do that, maybe you have a big problem about the conception or the design...


text:
Q: MapStateToProps not working I am trying to use redux with react. The mapStateToProps is not called.
The dispatch calls are working properly, the action reaches the reducer and the newState is returned and the state of the store is modified. But mapStateToProps is not called and the component is not rerendering.
class Wrapper extends React.Component {
      updateChartData (data) => {
        ...logic...
        this.props.actions.chartDataAction(modifiedData);
        }
}

function mapStateToProps(state, ownProps) {
    return {
        chartData: state.chartData
        };
}

function mapDispatchToProps(dispatch) {
      return {
      actions: bindActionCreators(chartDataAction, dispatch)
      };
}

export default connect(mapStateToProps, mapDispatchToProps)(Wrapper);

The other classes that use updated state is as follows
class Chart extends React.Component {
    render(){
        /*console.log(this.props.chartData);*/
    }
}

function mapStateToProps(state, ownProps) {
    console.log(state);
    return {
        chartData: state.chartData
    };
}

let ChartComponent = withStyles(styles)(Chart);

export default connect(mapStateToProps)(ChartComponent);

The action is as follows
export default function (state = [], action) {
if (action.type === actionTypes.CHANGE_CHARTDATA) {
    return action.chartData;
} else {
    return state;
}

}
The reducer is
export default function (state = [], action) {
    if (action.type === actionTypes.CHANGE_CHARTDATA) {
        return action.chartData;
    } else {
        return state;
    }
}

I've even checked using redux dev tools. The chartData is being updated in the redux store. The chartData is properly passed to the Chart class and it renders on the first update. On consecutive dispatching, the chartData is updated in the redux store, but the mapStateToProps of Chart class is not called and the Chart class is not rerendering.
UPDATE:
I'm trying to live update the chart and it does not render if the few entries in the chartData array are changed.
I noticed that the chart component rerenders when the whole chartData is changed. But I want it to rerender if any part of the chartData is changed.

A: Edit : Be sure to follow the immutable update patterns even outside of your reducer (in updateChartData() method in your case).
You are probably mutating data in your "...logic...", you can use immutable-js to make it easier for you.


text:
Q: How to connect one page with another page in landing page of django? I have one landing page. I want to separate them and divide them in different pages so that whenever I make changes in it, I don't have to search a long index.html page. How to do this? I made changes but it is not working because in
  it has id which I don't know how to reach?
views.py
def contact(request):
    if request.method == 'POST':
        print(request)
        first = request.POST.get('first', '')
        last = request.POST.get('last', '')
        email = request.POST.get('email', '')
        textarea = request.POST.get('textarea', '')
        print(first, last, email, textarea)
    return render(request, 'home/contact.html')

index.html

    <form action="" method="post">
      {% csrf_token %}

          <input type="text" class="form-control" name="last" placeholder="Full name">

          <input type="text" class="form-control" name="email" placeholder="Email address">

          <textarea name="textarea" id="" class="form-control" placeholder="Write your message." cols="30" rows="10"></textarea>

          <input type="submit" class="btn btn-block btn-primary text-white py-2 px-5" value="Send Message">

    </form>

A: Here is solution
  Contact

A: First of all you have to write that section from index.html to individual html file
Example:
index.html

    ...title...

            ...section 1...

            ...section 2...

Now, split those section into individual html file as...
section1.html

     ...section 1...

section2.html

     ...section 2...

Now, remove your section 1 and section 2 from index.html and at same place include this section1.html and section2.html as below...
index.html

    ...title...

        {% include "section1.html" %}
        {% include "section2.html" %}


text:
Q: Dalitz plot for $ \pi \to \gamma (1) + e^+ (2) + e^- (3) $ I am studying the decay above and I need an exact form of Dalitz plot in coordinates $m^2_{12}, m^2_{23}$ to integrate over three-particle phase-volume. Please, tell where to read about it?
I tried to compute it by myself but I stuck on calculations.


text:
Q: ExtJs drag and drop menuitems from panel to panel I've defined DragZone as:
    var menuItems = panel.query('.menuitem');
    Ext.each(menuItems, function (component) {
        component.DragZone = Ext.create('Ext.dd.DragZone', component.getEl(), {
            getDragData: function (e) {
                var compEl = component.getEl(),
                cloneEl;

                cloneEl = compEl.dom.cloneNode(true);
                cloneEl.id = Ext.id();

                return {
                    ddel: cloneEl,
                    repairXY: Ext.fly(e.getTarget()).getXY(),
                    componentClone: component.cloneConfig()
                };
            },
            getRepairXY: function () {
                return this.dragData.repairXY;
            },
            ddGroup: 'auGroup'
        });
    });

Where menus are menuitems from panel:
xtype: 'panel',
title: 'Geometry Controls',
items: [
    {
        xtype: 'menu',
        floating: false,
        itemId: 'geometryControlsMenu',
        defaults: {
            height: 20
        },
        items: [
            {
                xtype: 'menuitem',
                itemId: 'angles',
                text: 'Angles',
                iconCls: 'icon-apgo'
            },
            {
                xtype: 'menuitem',
                itemId: 'coordinatePlane',
                text: 'Coordinate Plane',
                iconCls: 'icon-apgo'
            }

Dragging is working but I have problems with displaying dragging items, it look like it has been croped:

But if I'll change dragsource from menuitem to menu itself:
var menuItems = panel.query('.menu');

displaying works ok:

How could I fix this?

A: component.DragZone.resizeFrame= true;


text:
Q: DirectX Z order I have to draw a map with Managed DirectX. The map arrived in MapInfo format (lines, polylines, regions/polygons). Polygons are already triangulated (done with GLUtesselator).
The idea:

*

*GPS Coordinates are converted to x,y points (Mercator Projection)

*I use PositionColored VertexFormat

*Center of the view is [x,y] (can modify by mouse move)

*Camera is always positioned to [x,y,z] where z is the zoom (-100 by default, can modify by mouse wheel)

*Camera target is: [x,y,0], camera up: [0,1,0]

*The layers of the map are positioned by Z (+1.0, 0.99, 0.98, 0.97...etc)

I can already do:

*

*Draw lines and polylines

*Draw one layer of polygons

My problem is: when I want to draw all layers I see only one of them. I think there is some problem with z ordering. What should I do to solve this? Modify the RenderState? The best would be if I could draw as in GDI (first in the back, last in the front).
Other question: how can I get the coordinate of a pixel under the mouse cursor? (in the GDI version of the map I could do it because I used my own viewport for rendering, but now directx do everything)
Thanks!

A: If your map is purely 2D, make sure that Z buffering is turned off. Once it is, things will display in the order you draw them in.


text:
Q: Implementing a horizontal sub menu with Javascript I am looking for some examples that I could use to implement a horizontal sub-menu in Javascript (not JQuery). I would like a menu that will be SEO friendly. Here's an example of what I am looking for:
opt1     opt2      opt3       opt4
opt1a opt1b opt1c opt1d

opt1     opt2      opt3       opt4
  opt2a opt2b opt2c opt2d

So when the user hovers over opt1 at the top level then the opt1a, opt1b, opt1c and opt1d choices appear on the SECOND level menu below it. When the user hovers over opt2 at the top level then the opt2a, opt2b, opt2c and opt2d choices on the SECOND level would show.
Has anyone seen any code examples for this? What I am thinking of is to have four different DIVs for the second level menus and then have some way of making these DIVs visible when the user hovers over the different top levels. It sounds easy but I'm guess it is not so easy.

A: A good way to make a horizontal menu that has a minimum of cross-browser hassles is to use the following pattern. The key is to style what's INSIDE the
 and not the
 itself.

SOME TITLE

link1

2

<input type="text" .../>

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

CSS:
.menu ul, .menu li {
   list-style=type:none;
   padding:0;
   margin:0
}

.menu li {
    display:inline-block
}

.menu a {
     display:block;
    ....other styles....

}

Then you nest them:

SOME TITLE

link1

sub1

2

<input type="text" .../>

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

You're right, then use position:relative on ul li, position:absolute on ul ul etc... You're on the right track, but use lists, not DIVs.

A:

Menu 1

                        Hello world

                        Hello world

                        Hello world

Menu 2

                        Hello world

                        Hello world

                        Hello world

Menu 3

Menu 4

This code probably does the same as above but the second level is below the top level. Hope this help !


text:
Q: Operate with index in a column of a dataframe in R I have a dataframe called "d" with 11 variables and 170 rows. I want to operate with the values in 9,10 and 11th (d$CH4, d$CO2, d$N2O) and to create a new df dr$CH4, dr$CO2, dr$N2O columns saving the results of the operations. It consists of a series of substractions. I did it one by one. for the 9th column (d$CH4) it goes as follows: d[2,9] - d[1-9] then d[4,9] - d[3-9] , d[6,9] - d[5-9] and so on ending with one column (dr$CH4) and 85 rows with the results of each substraction. Then I would repeat the process with the other two columns. basically every odd row minus its previous even row.
I tried this but it would just give an empty df as output.
dr<- d[,9:11]
dr[,1:3] <- NA  #saving the names of the columns
j<-0

for (i in d$CH4){
    dr[j,1] <- d[(i+1),9] - d[i, 9]
    j+1

}

A: I would suggest a solution without any loop - you can just shift your data.frame by one and then subtract the original one, e.g.:
d <- data.frame(matrix(runif(170*11), ncol=11, nrow=170))
dr<- d[,9:11] #getting subset
dr_help <- dr[2:nrow(d),] #shifting
result <- dr_help - dr[1:(nrow(dr)-1),] #calculation (equal to i+1 - i)

Also, please note that your new data.frame is one shorter than the original one because you can not calculate the last entry as i+1 would be greater than nrow(d).


text:
Q: Detaching ncu profiler while leaving the profiled program running I am currently using Nsight Compute CLI to profile DNN training. I use the following command to launch and attach the profiler with the program. (I will abbreviate the metrics part, since it is not the core concern of this topic.) If I run this script with appropriate command line arguments, the profiler and the program runs fine and the log and report is created.
#!/bin/bash

path_to_report=$1
path_to_script=$2

/usr/local/NVIDIA-Nsight-Compute/ncu \
    --log-file ./temp-report \
    -o $path_to_report \
    --print-summary per-gpu\
    --target-processes all \
    --metrics some_metrics_blah_blah \
    --force \
    $path_to_script

However, I want to exit the profiler (or the profiling process) after a certain time (let's say 5 minutes), but keep the program running. This is because the profiler adds large overhead & info, so I want to stop profiling but keep the DNN training running. But as I tried to terminate the ncu related process with the kill command, not only the ncu related process but also the training program exits. So I am needing help on this issue. Would there be any way to achieve my objective?


text:
Q: Using python's pillow library: how to draw text without creating draw object of an image the code bellow shows how to write text on image with creating a draw object
from PIL import Image, ImageFont, ImageDraw

image =  Image.new(mode = "RGBA" , size= (500, 508) )

draw = ImageDraw.Draw(image)

font = ImageFont.load("arial.pil")

draw.text((10, 10), "hello", font=font)

what i'm asking for is how to return the text as a pillow object so i can just paste it on another images without having to create image object and draw object then writing text on them, i just want the raw text as a pillow object to use it later in .paste() function.
something like (code doesn't exist but it's what i can imagine):
from PIL import Image, ImageFont, ImageDraw

image =  Image.new(mode = "RGBA" , size= (500, 508) )

font = ImageFont.load("arial.pil")

text = font.loadtext("hello") #imaginary part (a pillow object)

image.paste(text, (10,10))

A: You can make a function that creates a piece of empty canvas and draws text in and returns it as a PIL Image like this:
#!/usr/local/bin/python3

from PIL import Image, ImageFont, ImageDraw, ImageColor

def GenerateText(size, fontname, fontsize, bg, fg, text, position):
   """Generate a piece of canvas and draw text on it"""
   canvas = Image.new('RGBA', size, bg)

   # Get a drawing context
   draw = ImageDraw.Draw(canvas)
   font = ImageFont.truetype(fontname, fontsize)
   draw.text(position, text, fg, font=font)

   return canvas

# Create empty yellow image
im = Image.new('RGB',(400,100),'yellow')
# Generate two text overlays - a transparent one and a blue background one
w, h = 200, 100
transparent = (0,0,0,0)
textoverlay1 = GenerateText((w,h), 'Arial', 16, transparent, 'magenta', "Magenta/transparent", (20,20))
textoverlay2 = GenerateText((w,h), 'Apple Chancery', 20, 'blue', 'black', "Black/blue", (20,20))

# Paste overlay with transparent background on left, and blue one on right
im.paste(textoverlay1, mask=textoverlay1)
im.paste(textoverlay2, (200,0), mask=textoverlay2)

# Save result
im.save('result.png')

Here's the initial yellow image before pasting:

And here's the result after pasting the two overlays:


text:
Q: Strange behaviour from setInterval vuejs I'm having some strange behaviours with the setInternal in my vue.js component. Below is the code:
<template>
  <div>
  {{ hours }} : {{ minutes }} : {{ seconds }}
  </div>
</template>

<script lang="ts">
import {
  Vue,
  Component,
  Prop,
} from 'vue-property-decorator';
import moment from 'moment';

@Component
export default class Countdown extends Vue {
  @Prop() private end!: Date;

  @Prop({ default: 1000 })
  interval!: number;

  private remaining!: number;

  get hours() {
    debugger;
    return Math.floor(this.remaining / 3600);
  }

  get minutes() {
    // eslint-disable-next-line no-mixed-operators
    return Math.floor(this.remaining % 3600 / 60);
  }

  get seconds() {
    return Math.floor(this.remaining % 3600 % 60);
  }

  created() {
    this.refresh();
  }

  refresh() {
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    const self = this;
    return setInterval(() => {
      self.remaining = (moment(self.end).toDate().getTime() - new Date().getTime()) / self.interval;
    }, self.interval);
  }
}
</script>

Firstly, I thought using an arrow function i.e => { } would allow me to use this.end or this.remaining but this isn't the case as I have to use const self = this; in order for it work work.
In addition, the computed properties hours, minutes and seconds aren't being updated. I've put a breakpoint on each of these and none of them get touched as the DOM always displays NaN NaN NaN
Does anyone understand what the problem is?

A: Even though you are using Definite Assignment Assertions, and you don't get any error, this.remaining is undefined, and you get NaN, at some point you need to assign it some value:
directly:
private  remaining: number = this.calculate();

calculate() {
   return (moment(this.end)
            .toDate()
            .getTime() -
             new Date().getTime()) /
             this.interval;
  }

refresh() {
   setInterval(() => this.remaining = this.calculate(), this.interval);
}

For some reason assign the first value directly inside setInterval not update the value. Will be interesting to kwon why :(.


text:
Q: How to serve messages properties both public, still access them from inside web project? Background
We have several clients, some is native as iPad and Android, other is html clients, like web and SmartTv.
We have a centralized web project that serve typical assets to all this clients, like icon, favicon, fonts and so on. In this way we can maintain assets in one place.
Problem
I now want to serve the messages property file, that is not public in the war file, to the JavaScript and the native clients.
Is there any good suggestion how to provide this messages public and in a proper format that fit the different clients?

A: If I understand correctly, you want to use the #{i18n/} tag as shown here. It will give you a javascript method that provides I18N translation of keys as defined in the messages file.

A: One solution in Play! is to serve the messages to the public as json:
public class AssetsController extends Controller{

    public static void getMessages(){
        String locale = params.get("locale");
        if(locale == null){
            locale = Lang.get();
        }
        System.out.println(locale);
        Properties messages = Messages.all(locale);
        renderJSON(messages);
    }
}


text:
Q: numpy: How to vectorize aggregation loop I have a vector of zeros, and two arrays of non-unique indices and (complex) values. What's the fastest equivalent of this operation?
X = zeros(....)

for index, value in zip(indexes, values):
    X[index] += value

I would use np.bincount with weights parameter, but it only works for integer values.


text:
Q: Jquery SlideDown() function not showing I would like to slideUp and slideDown the gridview when I click the gridview list, but only slideUp is working.
This below is showing in script file.
$('.divname').SlideUp(

This below is not showing in script file
$('.divname').SlideDown(

A: They are case-sensitive, and should be used like so: slideUp() and slideDown() and not SlideUp() or SlideDown().
See examples below. The red div uses slideUp() and the yellow div uses SlideUp().

$('#test1').mouseover(function() {
  $(this).slideUp();
});
$('#test2').mouseover(function() {
  $(this).SlideUp();
});
#test1 { margin: 1em; border: 1px solid black; width: 100px; height: 100px; background-color: red; position: absolute; top: 0; left: 0; }
#test2 { margin: 1em; border: 1px solid black; width: 100px; height: 100px; background-color: yellow; position: absolute; top: 0; left: 150px; }

test1

test2


text:
Q: Android app error when posting an answer on a site you have never created a user on Steps to reproduce:

*

*Open the navigation drawer and select All Sites option, it will show you all the Stack Exchange sites.

*Select any site in which you haven't logged in yet (i.e., you are not member yet). For example, I have selected Arqade. As we have selected Arqade, it will load all the questions of this site.

*Select any Question and navigate to Answer section.

*Now try to post answer, it will give you below error message:

Issues:

*

*Here user can post answer on any question on any Stack Exchange site. It should show me login page for the site which I haven't joined yet or simply it shouldn't allow me to post on that particular Stack Exchange site which I haven't joined yet.

*As I have mentioned in 1st point it allows users to post answer on any site but I know the answer never going to be get posted on that particular site. Here it should show proper error message then. You can see improper error message "this error has been logged" by which no user can come to know what is the error exactly.

A: If the user has not registered on a site then the android app should allow for them to register on that site and post as a member. I can't think of any good reasons to prevent someone from registering (or posting anonymously) on a stack exchange site from the android app when they can just launch a browser on the mobile device and register/post that way. Having a native app is supposed to make the user experience more friendly not to remove features that would be available if visiting the site from a browser on the same device.
Quick and simple the app should know if a user has permission to post before bringing up the editor (not counting changes that happen while typing up the post)

A: As of version 1.0 the application handles site registration seamlessly or via a prompt, depending on the severity of the action you're doing, meaning that this bug has been fixed.


text:
Q: Question about limit of a product
Is it possible that both $\displaystyle\lim_{x\to a}f(x)$ and $\displaystyle\lim_{x\to a}g(x)$ do not exist but $\displaystyle\lim_{x\to a}f(x)g(x)$ does exist?

The reason I ask is that I was able to show that if $\displaystyle\lim_{x\to a}f(x)$ does not exist but both $\displaystyle\lim_{x\to a}g(x)$ and $\displaystyle\lim_{x\to a}f(x)g(x)$ do exist, then $\displaystyle\lim_{x\to a}g(x)=0$. However, I'm not sure whether the assumption on the existence of $\displaystyle\lim_{x\to a}g(x)$ is necessary.

A: Let $f(x) = g(x)$ be a function that is $1$ on the rationals and $-1$ on the irrationals.

A: $f(x)=7+\sin(1/x)$, $g(x)=1/f(x)$, $a=0$.

A: Yes.  As a simple example, I'll work with sequences.  Let $f(n) = (-1)^n$ and $g(n) = (-1)^{n}$.  Then $f(n)g(n) = 1$, so $1 = \lim_{n \to \infty} f(n)g(n)$, but neither of the individual limits exist.

A: If you have two disjoint sequences $u_n\to a$ and $v_n\to a$
i.e. $\{a_n\mid n\in\mathbb N\}\cap\{b_n\mid n\in\mathbb N\}=\varnothing$
You can define $\begin{cases}f(a_n)=1 & \forall n\in\mathbb N\\f(x)=0&\text{otherwise}\end{cases}\quad$ and $\quad\begin{cases}g(b_n)=1 & \forall n\in\mathbb N\\g(x)=0&\text{otherwise}\end{cases}$
It is clear that $f(x)g(x)=0$ everywhere so it has a limit zero, while neither $f$ nor $g$ has a limit. And you can smoothen these functions if desired to get a $C^\infty$ example, just make sure that $f$ and $g$ bumps do not coincide.


text:
Q: GLUT: Wrong Mouse Coordinates? Using SCREEN_WIDTH = 1200, and SCREEN_HEIGHT = 800.
First, I draw a box to the screen at (x = 0, y = 0, w = 40, h = 40);
Then I use the handleMouse Function to return the x and y coordinates of where the mouse is clicked.
The problem is, when the program starts in non-Maximized windowed mode, when I click on (What appears to be) the very bottom right corner of the box the coordinates returned are x = 40, y = 32. When I think it should be returning x = 40, y = 40.
I don't know whether the problem is if its not being drawn right, or the functions is returning the wrong x/y.
I believe I understand how openGL rendering, transformation and glOrth work, but I could be completely wrong. I have seen a few suggestions online saying that the Windows Decor(Using windows 7) can cause this problem, but have done very little explaining and provided no solution.
This is my entire source code. I have stripped off everything from my game down to the basics, and the problem still persists :( . I added two pictures so people could see my problem. In NON-MAXIMIZED WINDOW(the top picture), when clicking the bottom-right corner, the coordinates returned are 41,32; The y coordinate is smaller than it should be. And in the MAXIMIZED WINDOW(the bottom picture), when clicking the same corner, It returns the correct coordinates 40, 40. These results occur for both my original source code and genpfault's suggested code.
//Turns out I can't post Pictures :(, links instead.
non-Maximized Windowed!
Maximized Windowed!
main.cpp
int main( int argc, char* args[] )
{
    //Initialize FreeGLUT
    glutInit( &argc, args );

    //Create OpenGL 2.1 context
    glutInitContextVersion( 2, 1 );

    //Create Double Buffered Window
    glutInitDisplayMode( GLUT_DOUBLE );
    glutInitWindowSize( SCREEN_WIDTH, SCREEN_HEIGHT );
    glutCreateWindow( "OpenGL" );

    //Do post window/context creation initialization
    if( !initGL() )
    {
        printf( "Unable to initialize graphics library!\n" );
        return 1;
    }
    //initGame();

    glutMouseFunc(handleMouse);

    glutDisplayFunc( render );

    glutMainLoop();

    return 0;
}

Functions.h
#ifndef FUNCTIONS_H
#define FUNCTIONS_H

bool initGL();

void render();

void handleMouse(int button, int state, int x, int y);

#endif

Functions.cpp
bool initGL()
{

    //Initialize clear color
    glClearColor( 0.f, 0.f, 0.f, 1.f );

    //Check for error
    GLenum error = glGetError();
    if( error != GL_NO_ERROR )
    {
        //cout <<"Error initializing OpenGL! " << gluErrorString( error ) << endl;
        return false;
    }

    return true;
}

void render()
{

    //Clear color buffer
    glClear( GL_COLOR_BUFFER_BIT );
    glColor3f(1.f,1.f,1.f);

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glBegin(GL_QUADS);
        glVertex2f(0,0);
        glVertex2f(0, 41);
        glVertex2f(41, 41);
        glVertex2f(41, 0);
    glEnd();

    glutSwapBuffers();
}

void handleMouse(int button, int state, int x, int y)
{

    std::cout << x << '\t' << y << std::endl;

}

constants.h
const int SCREEN_WIDTH = 1200;
const int SCREEN_HEIGHT = 800;

A: Try moving the quad away from the edge of the display because when I tryed to do something like that the edge of the screen was very odd
glBegin(GL_QUADS);
 glVertex2f(20,20);
 glVertex2f(20, 61);
 glVertex2f(61, 61);
 glVertex2f(61, 20);
glEnd();

A: This works fine for me on Windows 7 on Aero and Classic:
#include <GL/glut.h>
#include <iostream>

void render()
{
    glClearColor( 0, 0, 0, 1 );
    glClear( GL_COLOR_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    double w = glutGet( GLUT_WINDOW_WIDTH );
    double h = glutGet( GLUT_WINDOW_HEIGHT );
    glOrtho(0, w, h, 0, -1, 1);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glColor3ub( 255, 255, 255 );
    glBegin(GL_QUADS);
        glVertex2f(0,0);
        glVertex2f(41, 0);
        glVertex2f(41, 41);
        glVertex2f(0, 41);
    glEnd();

    glutSwapBuffers();
}

void handleMouse(int button, int state, int x, int y)
{
    std::cout << x << '\t' << y << std::endl;
}

int main( int argc, char* args[] )
{
    glutInit( &argc, args );

    glutInitDisplayMode( GLUT_DOUBLE );
    glutInitWindowSize( 640, 480 );
    glutCreateWindow( "OpenGL" );

    glutMouseFunc(handleMouse);
    glutDisplayFunc( render );
    glutMainLoop();
    return 0;
}

Most notably I added the runtime glutGet() window size queries to render().


text:
Q: MapServer Clustering GetFeatureInfo I'm having a bit of a problem with clustering in map server the clustering itself works fine and the GetFeatureInfo works fine most of the time. However some times when I click on a cluster point it some times gives a different number to how many points are meant to be in the cluster.
See this example cluster should contain 171 points but clicking on it gives 173.

Here is my mapfile I've removed the classes as its ridiculously long with them and I don't think its relevant
MAP
  FONTSET "fonts.list"
  IMAGETYPE "png"
  MAXSIZE 3000
  NAME "TEST"
  SIZE 1000 1000
  STATUS ON
  UNITS DD

  OUTPUTFORMAT
    NAME "png"
    MIMETYPE "image/png"
    DRIVER "AGG/PNG"
    EXTENSION "png"
    IMAGEMODE RGB
    TRANSPARENT FALSE
  END # OUTPUTFORMAT

  SYMBOL
    NAME "circle"
    TYPE ELLIPSE
    FILLED TRUE
    POINTS
      1 1
    END
  END

  PROJECTION
    "init=epsg:4326"
  END # PROJECTION
  LEGEND
    KEYSIZE 20 10
    KEYSPACING 5 5
    LABEL
      SIZE MEDIUM
      OFFSET 0 0
      SHADOWSIZE 1 1
      TYPE BITMAP
    END # LABEL
    STATUS OFF
  END # LEGEND

  QUERYMAP
    SIZE -1 -1
    STATUS OFF
    STYLE HILITE
  END # QUERYMAP

  SCALEBAR
    INTERVALS 4
    LABEL
      SIZE MEDIUM
      OFFSET 0 0
      SHADOWSIZE 1 1
      TYPE BITMAP
    END # LABEL
    SIZE 200 3
    STATUS OFF
    UNITS MILES
  END # SCALEBAR

  WEB
    METADATA
      "wms_srs" "EPSG:900913"
      "ows_enable_request"  "*"
      "wms_title"   "Testing"
    END # METADATA
  END # WEB

  LAYER
    CLASSITEM "Cluster:FeatureCount"
    CLUSTER
      BUFFER 10
      REGION "ellipse"
    END # CLUSTER
    CONNECTION ""
    CONNECTIONTYPE POSTGIS
    DATA "position from data"
    LABELCACHE OFF
    LABELITEM "Cluster:FeatureCount"
    METADATA
      "wms_include_items"   "all"
      "wms_timeitem"    "datetime"
      "wms_timeextent"  "1910-01-01/2050-02-01"
      "gml_include_items"   "all"
      "gml_geometries"  "none"
      "wms_title"   "Data"
    END # METADATA
    NAME "test1"
    PROCESSING "GETSHAPE_STYLE_ITEMS=all"
    PROCESSING "LABEL_NO_CLIP=True"
    PROCESSING "CLUSTER_GET_ALL_SHAPES=ON"
    PROCESSING "ITEMS=id"
    STATUS OFF
    TEMPLATE "blank.html"
    TILEITEM "location"
    TOLERANCE 10
    TYPE POINT
    UNITS METERS

    CLASSES_HERE
  END # LAYER

END # MAP

I hope that provides enough for some suggestions on the issues if any more information is required please do let me know, any suggestions would be highly appreciated.