text:
Q: Backing out of a fragment or activity when a button is pressed I have a contact list that takes the user to a contact edit screen. I am trying to handle closing of the edit activity/fragment (contact edit) depending on which one I am currently using. So if I'm using a fragment, I'd like it to close the fragment after saving or deleting from the database, but the same goes for when I'm in portrait/landscape mode on a small device and running an activity. I have the following code that pops up an error (as I expected) when I'm in twopane mode. Basically, I want the user to see a list of contacts, edit the contacts, then see the updated list of contacts plus or minus their edits.
// Set the save button to check the required fields, save the contact and finish
saveButton.setOnClickListener(new View.OnClickListener() {
  public void onClick(View view) {
    if (TextUtils.isEmpty(mLastName.getText().toString()) ||
            TextUtils.isEmpty(mFirstName.getText().toString())) {
      makeToast();
    } else {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.popBackStackImmediate();
        getActivity().finish();
   }
  }
});

// Set the delete button to delete the contact and close the fragment
deleteButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        // Delete the contactUri created from an ID passed in from contactActivity
        getActivity().getContentResolver().delete(contactUri, null, null);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.popBackStackImmediate();
        getActivity().finish();
    }
  });
return aView;

With the above code I get a NullPointerException at contactEditFragment.onClick
I guess I need a way to differentiate between an activity and a fragment.
05-05 05:40:57.200: E/AndroidRuntime(1350): FATAL EXCEPTION: main
05-05 05:40:57.200: E/AndroidRuntime(1350): java.lang.NullPointerException
05-05 05:40:57.200: E/AndroidRuntime(1350):     at com.somestuff.ContactEditFragment$1.onClick(ContactEditFragment.java:106)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at android.view.View.performClick(View.java:4204)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at android.view.View$PerformClick.run(View.java:17355)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at android.os.Handler.handleCallback(Handler.java:725)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at android.os.Handler.dispatchMessage(Handler.java:92)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at android.os.Looper.loop(Looper.java:137)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at android.app.ActivityThread.main(ActivityThread.java:5041)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at java.lang.reflect.Method.invokeNative(Native Method)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at java.lang.reflect.Method.invoke(Method.java:511)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-05 05:40:57.200: E/AndroidRuntime(1350):     at dalvik.system.NativeStart.main(Native Method)

Here is the onContactSelected:
public void onContactSelected(String id) {
        if (mTwoPane)
        {
            Log.i("SECOND INSIDE OF ONITEMSELECTED TWO PANE MODE !!! IN CONTACTS ACTIVITY - THE ID IS:", id);
            // In two-pane mode, show the contact edit view in this activity by
            // adding or replacing the detail fragment using a
            // fragment transaction.

                // Create new fragment and transaction
                Bundle arguments = new Bundle();
                arguments.putString(ContactEditFragment.CONTACT_ID, id);
                ContactEditFragment contactEditFragment = new ContactEditFragment();
                contactEditFragment.setArguments(arguments);
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack
                transaction.replace(R.id.item_detail_container, contactEditFragment);
                transaction.addToBackStack(null);

                // Commit the transaction
                transaction.commit();

        } else {
            // In single-pane mode, simply start the detail activity
            // for the selected contact ID.
            Intent detailIntent = new Intent(this, ContactEditActivity.class);
            detailIntent.putExtra(ContactEditFragment.CONTACT_ID, id);
            startActivity(detailIntent);
                }

A: I have tried the following code, and so far it works as I am expecting:
   // Set the save button to check the required fields, save the contact and finish
        saveButton.setOnClickListener(new View.OnClickListener() {
          public void onClick(View view) {
            if (TextUtils.isEmpty(mLastName.getText().toString()) ||
                    TextUtils.isEmpty(mFirstName.getText().toString())) {
              makeToast();
            } else {
                if (getActivity().findViewById(R.id.item_detail_container) != null){
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.popBackStackImmediate();
                }
                else{getActivity().finish();}
           }
          }
        });

        // Set the delete button to delete the contact and close the fragment
    deleteButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            // Delete the contactUri created from an ID passed in from contactActivity
            getActivity().getContentResolver().delete(contactUri, null, null);

                if (getActivity().findViewById(R.id.item_detail_container) != null){
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.popBackStackImmediate();
                }
                else{getActivity().finish();}
        }
      });
    return aView;


text:
Q: jsf menuitem does not set property i try to set normal property by menu-item, but it is does not work.
jsf:
<p:menuitem value="Names"
            url="/master.xhtml"
        action="#{navigation.name}">

       <f:setPropertyActionListener target="navigation.name"
      value="Billy" />
</p:menuitem>

ManagedBean:
@ManagedBean(name="navigation")
@SessionScoped //
public class LinksNavigation {

    public LinksNavigation() {
        super();
        this.milchFleisch = "./menuFleisch.xhtml";
    }

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name= name;
    }

}

But it does not work. I dont set   with "f:setPropertyActionListener"
value = "Bully". How can i set property Value by menuItem??
Thanks

A: In setPropertyActionListeneryou have a String instead of an EL expression. Change
target="navigation.name"

to
target="#{navigation.name}"

Also, you need to take a closer look to at the tag documentation for p:menuitem. The attribute action is expecting a method expression. You will get a MethodNotFoundException with the way your code is set up. You need to change
action="#{navigation.name}"

to
action="#{navigation.getName}"

The abbreviated syntax #{navigation.name} is used for value expressions.
You are mixing navigation methods. You cannot have the attributes url and action together for the same p:menuItem. When I tested your code action and setPropertyActionListener were never called when url was present. This behavior suggest that you have to pick one or the other.
COMMENT
Based on your sample, I think you should rethink your approach. Let's pretend for a moment that you decided not to use url="/master.xhtml" and let's go over the sequence of events. After you press the menu item, the expression #{navigation.name} in setPropertyActionListener will first set the value "Billy" to your name property (e.g. navigation.setName("Billy")).  Then the expression #{navigation.getName} in the attribute action will call getName(). Now action will have the String value "Billy" and it will try to navigate to Billy.xhtml (assuming no navigation rules in faces-config and you have JSF 2.0). If that's the behavior you're after or if you have rules set up in faces-config and you are not hardcoding the value than that's another story entirely. Just keep this in mind.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ito product rule Stochastic Differential Equation
$dS(t) = rS(t)(α − S(t))dt + σS(t)dW(t), S(0) = x.$
where W(t) is a standard Brownian motion and r, α, σ are positive constants.
I have no idea why this question need ito product rule.
Show by using the product rule that the following process is a closed-form solution
of the above Stochastic Differential Equation
$$S(t)=\frac{\exp\big\{(r\alpha-\frac{1}{2}\sigma^2)t+\sigma W(t)\big\}}{\frac{1}{x}+r\int_0^t\exp\big\{(r\alpha-\frac{1}{2}\sigma^2)s+\sigma W(s)\big\}\ ds}$$
I have no idea why this question need ito product rule.
My thought is let $f(Z)=\frac{Z}{(1/x+r\int z\ ds)}$
$dS(t)=df(z(t))=fz(z(t))dz(t)+fzz(z(t))dz(t)dz(t)$, but I'm stuck.


text:
Q: redefine \ref so that it also shows page number? i was idly wondering instead of having see Section \ref{labelname} produces

see Section 4.1.1

i could make it so that see Section \ref{labelname} produces

see Section 4.1.1 (p65)

is this possible? Would using hyperref mess this up?

A: Maybe you would like to take a look at the varioref package with its command \vref. This will generate your demanded output. In addition, this does not have an effect on your hyperref settings.

A: You can define a command, like \myref
 \newcommand{\myref}[1]{\ref{#1} (p\pageref{#1})}
Then you can use  \myref{xxx}

A: The cleaner way would be a new macro like in the answer of goodluck.
But also \ref can be redefined. It should be done as late as possible, because many packages redefines it. In the solution it is done in \AtBeginDocument at the end of the preamble, especially after package hyperref is loaded.
Also package hyperref supports a star form that generates the reference without the link.
For example, this is useful if the reference is part of another reference to avoid nested links.
\documentclass{article}
\usepackage{hyperref}

\makeatletter
\AtBeginDocument{%
  \newcommand*{\original@ref}{}%
  \let\original@ref\ref
  \@ifpackageloaded{hyperref}{%
    \renewcommand*{\ref}{%
      \@ifstar\newrefstar\newref
    }%
    \newcommand*{\newrefstar}[1]{%
      \original@ref*{#1} \textbf{(p\pageref*{#1})}%
    }%
    \newcommand*{\newref}[1]{%
      \hyperref[#1]{\newrefstar{#1}}%
    }%
  }{%
    \renewcommand*{\ref}[1]{%
      \original@ref{#1} \textbf{(p\pageref{#1})}%
    }%
  }%
}
\makeatother

\begin{document}
\section{Introduction}
\section{Foo bar}
\subsection{Hello World}
\label{sec:hello}
This is subsection \ref{sec:hello}.
\end{document}


text:
Q: R: on.exit - use returned value without knowing its name I have below function. I cannot alter the function in any way except the first block of code in the function.
In this simple example I want to display apply some function on returning object.
The point is the name of variable returned by function may vary and I'm not able to guess it.
Obviously I also cannot wrap the f function into { x <- f(); myfun(x); x }.
The below .Last.value in my on.exit call represents the value to be returned by f function.
f <- function(param){
  # the only code I know - start
  on.exit(if("character" %in% class(.Last.value)) message(print(.Last.value)) else message(class(.Last.value)))
  # the only code I know - end

  # real processing of f()

  a <- "aaa"
  "somethiiiing"
  if(param==1L) return(a)

  b <- 5L
  "somethiiiing"
  if(param==2L) return(b)

  "somethiiiing"
  return(32)
}
f(1L)
# function
# [1] "aaa"
f(2L)
# aaa
# [1] 5
f(3L)
# integer
# [1] 32

Above code with .Last.value seems to be working with lag (so in fact not working) and also the .Last.value is probably not the way to go as I want to use the value few times like if(fun0(x)) fun1(x) else fun2(x), and because returned value might be a big object, copy it on the side is also bad approach.
Any way to use on.exit or any other function which can help me to run my function on the f function results without knowing result variable name?

A: In a similar way to how you are modifying the function, you could easily wrap it as well. Here's a reproducible example.
library(data.table)

append.log<-function(x) {
    cat(paste("value:",x,"\n"))
}

idx.dt <- data.table:::`[.data.table`
environment(idx.dt)<-asNamespace("data.table")

idx.wrap <- function(...) {
    x<-do.call(idx.dt, as.list(substitute(...())), envir=parent.frame())
      append.log(if(is(x, "data.table")) {
          nrow(x)
      } else { NA })
      x
}
environment(idx.wrap)<-asNamespace("data.table")

(unlockBinding)("[.data.table",asNamespace("data.table"))
assign("[.data.table",idx.wrap,envir=asNamespace("data.table"),inherits=FALSE)

dt<-data.table(a=1:10, b=seq(2, 20, by=2), c=letters[1:10])

dt[a%%2==0]

A: Since R 3.2.0 it is fully possible, thanks to new function returnValue.
Working example below.

f <- function(x, err = FALSE){
  pt <- proc.time()[[3L]]
  on.exit(message(paste("proc.time:",round(proc.time()[[3L]]-pt,4),"\nnrow:",as.integer(nrow(returnValue()))[1L])))
  Sys.sleep(0.001)
  if(err) stop("some error")
  return(x)
}
dt <- data.frame(a = 1:5, b = letters[1:5])
f(dt)
f(dt, err=T)
f(dt)
f(dt[dt$a %in% 2:3 & dt$b %in% c("c","d"),])


text:
Q: Changing FirstPersonController MouseLook sensitivity I am an absolute beginner. I am currently making an aim down sights script with javascript, and when aiming I want the sensitivity for both x and y to drop to 2. I tried using
GetComponent.<UnityStandardAssets.Characters.FirstPerson.MouseLook>().sensitivityX = 2;

but that doesn't work. The error for that line is
NullReferenceException: Object reference not set to an instance of an object
Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.String cacheKeyName, System.Type[] cacheKeyTypes, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory)
Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.Object[] args, System.String cacheKeyName, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory)
Boo.Lang.Runtime.RuntimeServices.SetProperty (System.Object target, System.String name, System.Object value)
AimDownSights.Update () (at Assets/AimDownSights.js:33)

Does anyone know how to access the reference the Mouse Look dropdown in FPSController so I can change sensitivity? Thanks!

A: First of all, you should be using C# as soon as possible because it has more features than Javascript. Also, you will get more help with C# than Unityscript. Finally, the chances of Unityscript being discontinued in the future is high so make that decision now. You can find C# tutorial for Unity here.
The MouseLook script is not not exposed in the  FirstPersonController script.
We will expose the MouseLook. Open the FirstPersonController.cs script from Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts directory and add the script below to it:
public MouseLook mouseLookCustom
{
    get { return m_MouseLook; }
}

That's it. We have now exposed the MouseLook instance.

To modify the mouse stuff:
C#:
using UnityStandardAssets.Characters.FirstPerson;

public class Fpstest : MonoBehaviour
{
    FirstPersonController fps;

    // Use this for initialization
    void Start()
    {
        GameObject fpObj = GameObject.Find("FPSController");
        fps = fpObj.GetComponent<FirstPersonController>();
        fps.mouseLookCustom.XSensitivity = 5;
    }
}

Unityscript/Javascript:
#pragma strict
import UnityStandardAssets.Characters.FirstPerson;

var fps:FirstPersonController;

function Start () {
    var fpObj = GameObject.Find("FPSController");
    fps = GetComponent.<FirstPersonController>();
    fps.mouseLookCustom.XSensitivity = 5;
}


text:
Q: Maven Bundle Plugin R6 Metatype I'm trying to use the maven-bundle-plugin to build a bundle using the osgi r6 metatype annotations.
I have created a config class
@ObjectClassDefinition(
    name = "Bundle State Validator"
)
@interface BundleInstallationConfig {
    boolean DEFAULT_ENABLED = true;

    @AttributeDefinition(
        defaultValue = "true"
    )
    boolean isEnabled() default DEFAULT_ENABLED;
}

and I'm using it in my component class.
@Component(
    immediate = true
)
@Designate(ocd = BundleInstallationConfig.class)
public class BundleInstallationVerifier {
}

but when I build it the generated metatype file doesn't look right and it doesn't load in the config admin. This is what is generated (it's missing the designate section)
<metatype:MetaData localization="OSGI-INF/l10n/test.test.BundleInstallationConfig">
    <OCD id="test.test.BundleInstallationConfig" name="Bundle State Validator" description="Watches bundles to ensure they are in the correct state and switches the System Ready state.">
        <AD id="isEnabled" type="Boolean" name="Is enabled" default="true"/>
    </OCD>
 </metatype:MetaData>

This is the bundle plugin in my pom
       <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>2.5.4</version>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <obrRepository>NONE</obrRepository>
                    <_metatypeannotations>*</_metatypeannotations>
                    <_dsannotations>*</_dsannotations>
                </instructions>
            </configuration>
        </plugin>

I have got this far mostly through the frustrations of this guy
https://github.com/bndtools/bnd/issues/1030
https://groups.google.com/forum/#!msg/bndtools-users/_F0Nr8b7rlQ/2A9x660pAgAJ

A: I don't think the maven-bundle-plugin uses bndlib 3.0 yet. bndlib 3.0 (not released yet) is the source of OSGi R6 annotations support. You are a little ahead of things.

A: Your designate does not appear because one has not been defined in the class. Have a look at Neil Bartlett' post on this topic: enter link description here


text:
Q: DAX: How to achieve the effect of a join/relationship between a bitmask column and a table of bit values? I have a table CarHistoryFact (CarHistoryFactId, CarId, CarHistoryFactTime, CarHistoryFactConditions) that tracks the historical status of cars. CarHistoryFactConditions is a 25-bit (in binary) int column that encodes the status of 25 various conditions the car may be in at a given point in time.
I have a dimension table CarConditions with a row for each of the conditions, and their base 10 bit value.
How can I implement a "relationship" between the fact and dimension, giving a list of all the conditions a given car is
I can come up with bit parsing code, but I'm not sure how to hook it up to the dimension table to get just the currently applicable conditions at a car-time.
Bitmask parsing in dax can be seen here :
https://radacad.com/quick-dax-convert-number-to-binary

A: You can create a CROSSJOIN Table where all records are added 25 times and then filter out the once not existing
CarHistoryConditions =
var temp = CROSSJOIN(CarHistoryFact ; CarConditions )
return FILTER(temp; MOD(TRUNC(CarHistoryFact [CarHistoryFactConditions] / CarConditions [bit]):2) = 1)

note: I assumed the CarHistoryFactConditions and bit to be an integer, not a string of bits. For sure you can change that.
The reult is a table with as many rows of conditions for each car. E.g. Car one has 2 conditions and Car two has 5 conditions. You get 7 rows


text:
Q: *Error: (null) Code:8004100E Source:(null) Do you want to stop debugging ?* error while running the following vb script Execution of following Vb-script leads to the Error: (null) Code:8004100E Source:(null) error
Program:- ' List Internet Explorer Summary Settings
    strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
            "\root\cimv2\Applications\MicrosoftIE")

Set colIESettings = objWMIService.ExecQuery _
    ("Select * from MicrosoftIE_Summary")

For Each strIESetting in colIESettings
    Wscript.Echo "Active printer: " & strIESetting.ActivePrinter
    Wscript.Echo "Build: " & strIESetting.Build
    Wscript.Echo "Cipher strength: " & strIESetting.CipherStrength
    Wscript.Echo "Content advisor: " & strIESetting.ContentAdvisor
    Wscript.Echo "IE Administration Kit installed: " & _
        strIESetting.IEAKInstall
    Wscript.Echo "Language: " & strIESetting.Language
    Wscript.Echo "Name: " & strIESetting.Name
    Wscript.Echo "Path: " & strIESetting.Path
    Wscript.Echo "Product ID: " & strIESetting.ProductID
    Wscript.Echo "Version: " & strIESetting.Version
Next

Error:-

VbsEdit 64-bit
Line:   5
Column: 1
Error:  (null)
Code:   8004100E
Source: (null)
Do you want to stop debugging ?
Yes   No
Please help me to overcome this issue.

A: Error 8004100E means "invalid namespace". Starting with Windows Vista the namespace root\cimv2\Applications\MicrosoftIE has been removed from WMI.


text:
Q: What is the shortcut for opening MSDN page in Visual Studio 2013 I am thinking that there may be some shortcut for opening the related MSDN page for default c# methods classes etc.
Such like:
String variableName = "Variable";

press some shortcut while String focused and it opens:
String Documentation

A: Place the cursor on the keyword and press F1. You will be redirect to related MSDN page. Example in your case
String variableName = "Variable";
Put your cursor on String and press F1 you will be redirected to MSDN page of String documentation.


text:
Q: Freeing up memory allocated for an arbitrary position at an array I am writing code to manage insertions and deletions into array elements. I know that a linked list or some other data structure is better suited for this, but I'm limited to using an array.
Extra memory for the array allocations are managed by use of the realloc() function. However, for deletions, I must free up the memory allocated to the last element. For this, I tried using free (a + n), n representing the last element, however, this ends up giving crashes like:
*** Error in `./a.out': munmap_chunk(): invalid pointer:
0x000000000158f018 ***
Aborted (core dumped)

I believe that the crashes are expected, since the OS manages a list of allocations for the heap, and while a itself has been allocated through malloc(), the OS does not know about any allocations for a + n, resulting in a hard error.
How should I go around freeing up the last element stored in the array?

A: Use realloc to shrink the allocation:
array_size--;
array = realloc(array, array_size);


text:
Q: Passing function code using java 8 supplier I am trying to understand lambdas in Java 8. I have this very simple example using a functional interface.
This is not a working example and I understand that I can directly call method1 and method2 rather than using getValue() and Supplier, but, I wanted to know if there are any issues with calling method1 and method2 using supplier.get().
public <T> T mytest(SomeObject var) {
    //extract values from someobject
    if(somecondition) {
        getValue(() ->  method2(obj5instance, obj6instance));
    } else {
        getValue(() ->  method1("somestr", obj1instance, obj2instance, obj3instance));
    }
}

private String method1(String s1, Obj1 s2, Obj2 s3, Obj3 s4){
    //network call here to compute return value
    return "computedmethod1";
}

private String method2(Obj5 s2, Obj6 s3){
    //network call here to compute return value
    return "computedmethod2";
}

public <T> T getValue(Supplier<T> supplier){
    //this will call method1 or method2
    //wrap the return value from supplier.get and return
    return supplier.get();
}

Update based on Andrew's comment.
That makes a lot of sense, thanks. I am having difficult wrapping my head around the concept of supplier.
C1.java
public C3 m1(Obj obj){
  Supplier<String> mysupplier = () -> foo(arg1, arg2, arg3);       //foo is an expensive call
return someFn(mysupplier);
}

How does supplier work internally? When the supplier is created, does it keep a reference to foo() and the arguments passed to foo?
public C3 someFn(Supplier<String> supplier){
//this returns an instance of C3 that has a method lazyCall() which runs supplier.get()
}

C2.java
C3 c3 = c1.m1(obj);

If and when c3.lazyCall() is called, it runs the supplier.get() and foo is run. Is this a valid use of supplier?

A: One of the advantages of the Supplier interface is providing a value in a lazy way.
We try to delay a supplier.get() call as far as possible, because it's better to execute a resource-consuming operation (if you have such) at the moment when it really needs to be performed avoiding cases where the result of the operation can be ignored or might be skipped.
Here, the wrapper over a Supplier is senseless, because there are no conditions where it may not get called. Also, I don't see any reasons why these methods should be executed lazily. Though, I don't see a whole processing too.
EDIT:

How does supplier work internally? When the supplier is created, does it keep a reference to foo() and the arguments passed to foo?

Think about a lambda expression like a shortcut to anonymous class declaration (as it actually is) with overriding a single method. In the lambda body, you simply write method code which is gonna be executed when it gets invoked.
No, it doesn't keep references, because it has a direct access to them (with some limitations like effectively final variables).


text:
Q: R add specific (different) amounts of times to entire column I have a table in R like:
start                duration
02/01/2012 20:00:00  5
05/01/2012 07:00:00  6
etc...               etc...

I got to this by importing a table from Microsoft Excel that looked like this:
date        time      duration
2012/02/01  20:00:00  5
etc...

I then merged the date and time columns by running the following code:
d.f <- within(d.f, { start=format(as.POSIXct(paste(date, time)), "%m/%d/%Y %H:%M:%S") })

I want to create a third column called 'end', which will be calculated as the number of hours after the start time. I am pretty sure that my time is a POSIXct vector. I have seen how to manipulate one datetime object, but how can I do that for the entire column?
The expected result should look like:
start                duration  end
02/01/2012 20:00:00  5         02/02/2012 01:00:00
05/01/2012 07:00:00  6         05/01/2012 13:00:00
etc...               etc...    etc...

A: Using lubridate
> library(lubridate)
> df$start <- mdy_hms(df$start)
> df$end <- df$start + hours(df$duration)
> df
#                start duration                 end
#1 2012-02-01 20:00:00        5 2012-02-02 01:00:00
#2 2012-05-01 07:00:00        6 2012-05-01 13:00:00

data
df <- structure(list(start = c("02/01/2012 20:00:00", "05/01/2012 07:00:00"
), duration = 5:6), .Names = c("start", "duration"), class = "data.frame", row.names = c(NA,
-2L))

A: You can simply add dur*3600 to start column of the data frame. E.g. with one date:
start = as.POSIXct("02/01/2012 20:00:00",format="%m/%d/%Y %H:%M:%S")
start
[1] "2012-02-01 20:00:00 CST"
start + 5*3600
[1] "2012-02-02 01:00:00 CST"


text:
Q: Is it possible to install MySQL Server along with standalone client-side software? I'm writing an application for a venue that will have large-scale competitions. In order to effectively manage those competitions, multiple employees need to engage with and modify a set of data in real-time, from multiple machines in the gym. I have created a Python application which accomplishes this by communicating with a MySQL server (which allows as many instances of the application as necessary to communicate with it).
Is there a nice way to get MySQL server installed on a client machine along with this Python application (It only necessarily needs to end up on one machine)? Perhaps is there a way to wrap the installers together? Am I asking the right question? I have no experience with application distribution, and I'm open to all suggestions.
Thanks.

A: The 'normal' way to do it is to have a network setup (ethernet and/or wireless) to connect many Clients (with your Python app) to a single Server (with MySQL installed).
To have the "Server" distributed among multiple machines becomes much messier.
Plan A:  One Master replicating to many Slaves -- good for scaling reads, but not writes.
Plan B:  Galera Cluster -- good for writing to multiple instances; repairs itself in some situations.
But if you plan on having the many clients go down a lot, you are better off having a single server that you try to keep up all the time and have a reliable network so that the clients can get to that on server.


text:
Q: jsp how to escape double quotes
    Report Type

        Pending Funding

       Previously Funded

So, on loading, I want the default option 2 to be selected.
 <body topmargin="0" leftmargin="0" rightmargin="0" onload="window.moveTo(0,0);
                                                       window.resizeTo(screen.availWidth,screen.availHeight);
                                                       window.focus();
                                                       insertOption('number');
                                                       document.achReportCriteria.reportOutputStyleID.value="2";
                                                       doDetail();">

I tired \" and even &quot, but it doesn't seem to like it.

A: Why not use simple quote?
document.achReportCriteria.reportOutputStyleID.value='2';

A: Here's the easiest, simplest solution and cleanest solution:

And this function could even be stored in an external JS file, to avoid reloading each time the page is reloaded.

A: As far as nesting quotes goes you can use singles, the same as you already used for insertOption('number'):
document.achReportCriteria.reportOutputStyleID.value='2';

You said in a comment on another answer that that didn't work, but that must be because of some other error, not because of the quotes. I think it is because that syntax doesn't work to select a radio button. Try instead setting the checked property of the first one:
document.achReportCriteria.reportOutputStyleID[0].checked = true;

Or, better, rather than using JS just include the checked attribute directly in the markup:


text:
Q: How to turn on numbers on the first pages of my sections? Here is my code:
\documentclass[a4paper,12pt,times,numbered,print,index, oneside]{Classes/PhDThesisPSnPDF}
\usepackage{titlesec}
\begin{document}
\frontmatter
\begin{titlepage}
\maketitle
\end{titlepage}
\include{Abstract/abstract}

\tableofcontents
\listoffigures
\listoftables
\printnomenclature

\mainmatter

my text
\end{document}

So the structure of my document is the following:

*

*The title page (treated as the first one in roman numbers, but the number isn't displayed).

*The table of contets, abstract, etc. (not the main part of my thesis)- numbered using roman numbers.

*My main thesis-numbered using arabic numbers.

I'd like to have a roman number on each page of the second part of my text. However, roman numbers aren't displayed on the page if this is the first page of a section (i.e. the abstract or the list of figures).
How can I diable this bevaviour? I'd like to have all my roman numbers (excpet for the title).

A: If you are willing to live risky, you can add the following after your title page.

I cannot recommend that solution, though. It is against the design of the template. The author must have had some reasoning when coming up with that.

Basically, that replaces all instances of an empty page with a plain page. All of them after you do this.
\makeatletter
\let\ps@empty\ps@plain
\makeatother


text:
Q: TFS expired user As usual I extensively searched for a solution before asking here, I'm really stuck.
I'm currently working on a customer TFS server and I have no administration rights whatsoever. Me and a colleague were using the same user account, which I know is a bad practice but again I had no choice here.
Today we found out that the account is expired and the customer is saying that it will not be reactivated. Instead they gave us a new account.
The problem is that in our local workspaces we had some uncommited changes. I'm trying to find a way to reassing the local workspace to a different user but every path I tried leads to a dead end.
One thing I tried was to access the current workspace and set it to "Public" so another user can work on it, but I can't access the current workspace as I am offline and the user is expired.
If I change TFS credentials and try to Get Latest Version or anything else I don't see the old workspace but only the workspace(s) of the new user, which has no "Use" access to my local workspace.

I also read that a manual merge of the changes (using KDiff or Winmerge) is discouraged as TFS doesn't see edits done outside VS so it wouldn't know the files have been modified. I personally noted this behaviour when I tried to change some nodes in .csproj files with Notepad++ and TFS didn't give me the file in the pending changes.
Anyone knows the proper way to work with a new user without losing the local changes?
Thanks.

A: 1)Create a branch for the latest change set from the server
2) Check out the files to your workspace
3) Overwrite the files in worspace
4) Now the branch contains your changes
5) Merge the branch which contains your chnages with the latest.

A: You have three options:

*

*If you are using TFS 2012+ and VS 2012+ you can create a new workspace as the new user and make it a 'local' workspace rather than a server workspace. Then just drop the changes in a VS will detect them.

*If you are using an old version of TFS and/or VS you can use the 'go online' option (2010 only)

*If you are using a really old version you may need to checkout the entire workspace before dropping the changes back in.
Update: In order to achieve a merge of the changes you could create a branch from the last/latest changeset that you 'got' from the server. Then just overwrite you files... You now have a branch with just your changes and you can then user the merge tool to stitch it back together.
note: Also note that you should check in code frequently (at least daily) to avoid this issue in the first place.


text:
Q: Gaussian process regression in python- read n-samples and n-Targets from file According the answer here Implementation of Gaussian Process Regression in Python y(n_samples, n_targets)
Is not a duplicated question. It based on those answer and I have different issues
I want to read my samples from .txt file, which contains 3D-coordinates for each point (6x3) and looks like:
30.1678, -173.569, 725.724
-44.6401, -182.179, 733.301
39.7365, -187.244, 792.871
-9.43636, -200.9, 794.027
-38.2015, -199.272, 816.198
-17.6029, -189.19, 855.988

And one of the my 3D (1x3) target point:
14.8016, -175.911, 779.752

If I try to read my files as follows and make a prediction:
xFile= io.BytesIO(open('1_xRSImageCoordinates.txt', 'rb').read().replace(b'\n', b','))
xData= np.genfromtxt(xFile, dtype= float, delimiter= ',')
print("xData= ", xData)

yFile= io.BytesIO(open('1_y1InCoordinates.txt', 'rb').read().replace(b'\n', b','))
yData= np.genfromtxt(yFile, dtype= float, delimiter= ',')
print("yData= ", yData)

gaus = GP(xData, yData, kernel, R= R)

x_guess = np.linspace(-10, 10, 400)
y_pred = np.vectorize(gaus.predict)(x_guess)

colors = ['b', 'c', 'y', 'm', 'r']
plt.scatter(xData, yData, marker='o', label=u'Observations', color= colors[1])
plt.plot(x_guess, y_pred[0], c="b" , label=u'Prediction')
plt.plot(x_guess, y_pred[0] - np.sqrt(y_pred[1]) * 3, "r:" , label=u'Confidence Interval -')
plt.plot(x_guess, y_pred[0] + np.sqrt(y_pred[1]) * 3, "r:" , label=u'Confidence Interval +')

Then I get
xData=  [  30.1678  -173.569    725.724    -44.6401  -182.179    733.301
39.7365 -187.244    792.871     -9.43636 -200.9      794.027    -38.2015  -199.272  816.198    -17.6029  -189.19     855.988          nan]
yData=  [  14.8016 -175.911   779.752        nan]

File "C:/Users/trm/workspace/gaussianProcess/gaussianProcess.py", line 72, in predict
m_expt = (sigma_1_2.T * np.mat(self.sigma).I) * np.mat(self.y).T

File "C:\Users\trm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\numpy\matrixlib\defmatrix.py", line 309, in __mul__
return N.dot(self, asmatrix(other))

ValueError: shapes (1,19) and (4,1) not aligned: 19 (dim 1) != 4 (dim 0)

I don't understand why the nan variables are included in the array. I guess that I parse the file correctly. or not? why I get those Value Error at the end?
Thanks for any help


text:
Q: List of commands with Popen Hi guys,
I have three commands for copy/paste the folder with a similar path. I using this code:
        from subprocess import Popen, PIPE

        cmd_list = [
            'cp -r /opt/some_folder_1/ /home/user_name/',
            'cp -r /var/some_folder_2/ /home/user_name/',
            'cp -r /etc/some_folder_3/ /home/user_name/',
        ]
            copy_paste = Popen(
            cmd_list,
            shell = True,
            stdin = PIPE,
            stdout = PIPE,
            stderr = PIPE

        )

            stdout, stderr = make_copy.communicate()

But for the copy/paste three folders, I should three times run code.
Could you help me with these guys?
Thank you!

A: Do:
import subprocess

cmd_list = [
    ['cp', '-r', '/opt/some_folder_1/', '/home/user_name/'],
    ['cp', '-r', '/var/some_folder_2/', '/home/user_name/'],
    ['cp', '-r', '/etc/some_folder_3/', '/home/user_name/'],
]
for cmd in cmd_list:
    res = subprocess.check_output(cmd)
    # stdout and stderr are available at res.stdout and res.stderr
    # An error is raised for non-zero return codes

When passing a list into Popen or any of the other subprocess functions, you're not able to pass multiple commands in the cmd_list. It is expected that the first item in the list is the command you are running, and everything else are parameters for that one command. This restriction helps keep your code safer, especially when using user supplied input.
Another options is you can join everything together into a single command with a double ampersand. When doing so if one command fails the remaining commands won't run.
copy_paste = Popen(
    ' && '.join(cmd_list),
    shell = True,
    stdin = PIPE,
    stdout = PIPE,
    stderr = PIPE

)


text:
Q: Why is something looking for VsixUtil.exe here? I have a solution that's a VS extension, that compiles to a VSIX. I deleted my packages folder, built the solution, and I get an error...
The specified task executable location "D:\git\QueryFirst\packages\Microsoft.VSSDK.BuildTools.15.0.26201\tools\VSSDK\bin\VsixUtil.exe" is invalid.
The folder exists, but sure enough VsixUtil.exe is not in it. I installed VsixUtil with nuget, but it doesn't go to that location. Why is my solution looking for VsixUtil in that location. Can I point it somewhere else? Or install it there?
I'm on VS 2017 Enterprise.

A: The VsixUtil.exe utility should not be downloaded/installed separately. The NuGet package that you have used to download is not "official" from Microsoft or VisualStudioExtensibility.
Apparently there is a version mismatch in your project between two VSSDKs:

*

*the project is using a recent Microsoft.VsSDK.targets file that uses the VsixUtil task:

  <UsingTask TaskName="VsixUtil" AssemblyFile="$(VsSDKAssemblyFile)" />

*

*but it is going to the folder of an old VSSDK (Microsoft.VSSDK.BuildTools.15.0.26201) that doesn't have the VsixUtil.exe file required for that task.

Upgrade your Microsoft.VSSDK.BuildTools NuGet package of your project to use the latest versions 15.8.x ( 15.8.3252 or 15.8.3247) that do include VsixUtil.exe in the folder tools\vssdk\bin.


text:
Q: Is it possible to turn on Samsung smart TV, Tizen OS through network? My TV model is UA43J5500AJXZK
Is it possible to control, generally Tizen OS, on/off, switch input channel, through network or wireless?
The old way does not work anymore, by sending tcp packet directly, as the port has been removed.


text:
Q: Acer Aspire E1-572G won't wake up from sleep I have this laptop at work, Acer Aspire E1-572G, and whenever it sleeps, it does not want to wake up whatever I do. I put it to sleep by closing the lid or FN + ALT + F4.
I tried of course opening the lid, and using the same key combination again, pushing the power button, moving the mouse. Nothing helped! Any ideas?
PS: In the power plan I currently use, the hybrid sleep is off.
Update: It has Windows 8.1 Version 6.3 (Build 9600) and it is brand new.

A: I have the same laptop and the same problem after upgrading to windows 8.1
After hours of testing  things out, using different versions of drivers, it still didn't fix the problem. The only solution that worked out for me is disabling the Windows 8.1 Fast boot. It didn't affect my boot time that much anyway. Besides I encountered a lot of errors after installing software if I use the "shut down" option. Since restart isn't affected by the Windows 8.1 fast boot. I had to "restart" all the time if I install a software to be safe. So, I just disabled the "fast boot".
Now it goes to sleep and wakes up normally.

A: http://us.acer.com/ac/en/US/content/drivers and using the Acer Aspire E1-572G SNID to find the right drivers and installing the ones that relate to VGA seems to have fixed the problem.

A: This used to be a very common problem on many laptops and some desktops. Not seen it so much recently though. It is generally a bug in the video drivers.
Make sure that you have the latest drivers (just because it is new doesn't mean it has the latest). If that doesn't work, you could even try downgrading the drivers if the old ones are available.
Check both the Acer web site and the graphics card manufacturer's site (if you have a discrete graphics card version).
You could also try connecting the HDMI connector both before putting to sleep and before waking to see if it is doing something strange with the external connector.
There is at least one other person who seems to have the same issue. So you should also raise this as a fault to Acer.

A: I found the solution of this problem :
first:install intel VGA driver
second:install AMD VGA driver
third:roll back intell VGA driver
forth:update intel VGA driver
it has been tested and work

A: I am not sure if anyone is still facing this issue but i was and now have solved it.
I had to reinstall the drivers exactly as the ones it came with pre packaged with.
Intel Drivers Version 10.18.10.3355 INTEL HD GRAPHICS
AMD Driver Version 13.201.0.0  AMD CATALYST
I hope this helps. It seems to solve the issue for me.

A: I had a problem with an Aspire R7 that would sometimes not wake from sleep or standby.  I found somewhere that when the laptop is not responding correctly, do a hard reset.  There is not a way to remove the battery, but there is a tiny pinhole in the back or under side. Has a battery like icon. Press is for about 5 seconds and let go. Turn on your laptop.  If everything looks normal, cool. If not, please take notes on what you see and error codes for more troubleshooting. Hope this helps, take care! ~Lucy

A: This is an issue with the BIOS and 8.1. All you need to do to fix this issue is to update the bios to the latest one from the relevant product download page on the Acer website.

A: I'm not so sure, but I think I had the same problem. If there was a USB (wireless) mouse connected to any one of the USB 2.0 ports (two at the right side and one 3.0 on left) it worked OK. By removing the USB plug it rebooted immediately!

A: I have the same problem and I:

*

*unplug the two external monitors I have connected

*remove the battery by "sliding the pin hole switch".

The Acer battery switch looks like a pin hole that gets pressed in or pressed down on, but you actually slide it to remove it.

*Once it restarts I reconnect the external monitors and drives.


text:
Q: painting DataGridView Row I am trying to set the background color of a DataGridView row to red. I tried with the following line:
dgvActiveCalls.Rows[1].DefaultCellStyle.BackColor = Color.Red;
but it doesn't work. Then just to see if something is wrong with update I tried to paint the column instead of row:
dgvActiveCalls.Columns[1].DefaultCellStyle.BackColor = Color.Red;
and it worked fine. I would be really thankful if anyone could show the way to paint the DataGridView row.
Thanks!

A: Make sure that the default style isn't being overriden by another of the styles.  Interesting quirk of DGV in 2.0:  Seems like the inheritence chain is almost upside down from what you'd expect.  If you are dynamically adding columns, your DefaultCellStyle can be ignored and be overridden by the RowsDefaultCellStyle.  Sorting can also override styles you've set.
You might want to check in which order you're setting these styles and google for some articles regarding style inheritence.
P.S. Interestingly enough, I googled to find a link to provide, and came across this blog with an almost identical explanation:
http://yakkowarner.blogspot.com/2008/06/datagridview-style-inheritance.html

A: I tested that on my machine and it worked fine. Are you sure that line isn't highlighted? If it's highlighted you'll see the highlighted color, not the red.

A: I suggest that you put that code inside of the DataGridView's RowPrePaint event. For example:
private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
    /*Here you put your validation in order to paint only the row that you want*/
    if (e.RowIndex == 1)
    {
         DataGridViewRow row = ((DataGridView)sender).Rows[e.RowIndex];
         row.DefaultCellStyle.BackColor = Color.Red;
    }
}


text:
Q: bash assign variable inside if condition In C, it is possible to assign a variable inside an if condition, like this:
if ( (age = now - mdate) > 7 ) {
    # use variable `age`
}

Is it possible to do this in bash?

A: It's possible, but it has nothing to do with the if statement.
Inside an arithmetic statement, you can assign to variables.
now=10
mdate=1
if (( (age=now - mdate) > 7 )); then
    echo "$age"
fi

Here, (( ... )) is a command whose content is evaluated as an arithmetic expression. It's unrelated to the if statement's syntax, e.g.
(( age=10 ))
(( wait = 16 - age ))
echo "$wait years until you can drive"

Less bash-specific, you can break the condition into multiple commands:
# This works in any POSIX-compliant shell
if age=$((now - date)); [ "$age" -gt 7 ]; then
    echo "$age"
fi

A: You can use (( .. )):
if (( (age = now - mdate) > 7 )); then
   echo "more than 7"
fi


text:
Q: __xstat dynamic symbol resolving error on 64bit I am trying to dynamically load stat function using dlopen and dlsym.
Functions from stat family are wrapped in corresponding functions __xstat, __xstat64 itp.
Following sniped of code, compiles and works when compiled in 32bit mode (sys/stat.h is included to get stat structure for sake of example)
#include <iostream>
#include <dlfcn.h>
#include <sys/stat.h>

typedef int (*xstat_f) (int __ver, const char *__filename, struct stat *__stat_buf);

int main()
{
    auto* h = dlopen("libc.so.6", RTLD_LAZY);
    if(!h)
    {
        return 1; // invalid handle
    }

    auto f = (xstat_f)dlsym(h, "__xstat");
    if(!f)
    {
        return 1; // invalid handle
    }

    struct stat s = {};

    const auto r = f(3, "/tmp", &s);

    if (r != 0)
    {
        perror("stat");
        return errno;
    }

    return 0;
}

g++ main.cpp -o main -ldl -m32
Executable compiled without -m32 switch on 64bit machine returns EINVAL (Invalid argument).
What is the reason?
Also I've made a minimal test
#include <iostream>
#include <sys/stat.h>

int main(){
    struct stat s;
    const auto x = stat("/tmp", &s);
    if(x != 0) return errno;
    return 0;
}

and using objdump -T, on both executables, 32bits and 64bits, shows that stat is resolved as __xstat, so I am using correct symbol. Also I've tried combination of __xstat/__xstat64, struct stat/stat64, same result.

A: __xstat declarations follows:
int __xstat(int ver, const char *path, (struct stat *stat_buf))

in documentation parameter ver is described like, ver shall be 3 or the behavior of these functions is undefined, which is not entirely true, because in source code, definition of _STAT_VER_LINUX follows:
#ifndef __x86_64__
# define _STAT_VER_LINUX    3
#else
# define _STAT_VER_LINUX    1
#endif

That's why __xstat call on 64bits was failling, parameter ver should have been set to 1, and 3 on 32bits compilation.


text:
Q: How to optimize code that generates graph in R Could you help me optimize the code below? As you can see, I'm using the same date twice, once for graph generation and once for subset y generation. The result is correct, but I'd like some help trying to optimize to at least use the date only once and another optimizing that you find necessary. Every help is welcome.
Thank you very much!
library(dplyr)
library(lubridate)
library(tidyverse)

#dataset
df <- structure(
  list(date1 = c("2021-06-28","2021-06-28","2021-06-28","2021-06-28","2021-06-28",
                 "2021-06-28","2021-06-28","2021-06-28"),
       date2 = c("2021-04-02","2021-04-03","2021-04-08","2021-04-09","2021-04-10","2021-07-01","2021-07-02","2021-07-03"),
       Week= c("Friday","Saturday","Thursday","Friday","Saturday","Thursday","Friday","Monday"),
       DR01 = c(4,1,4,3,3,4,3,6), DR02= c(4,2,6,7,3,2,7,4),DR03= c(9,5,4,3,3,2,1,5),
       DR04 = c(5,4,3,3,6,2,1,9),DR05 = c(5,4,5,3,6,2,1,9),
       DR06 = c(2,4,3,3,5,6,7,8),DR07 = c(2,5,4,4,9,4,7,8)),
  class = "data.frame", row.names = c(NA, -8L))

#Generate graph

dmda<-"2021-07-01"
dta<-df

datas<-dta %>%
  filter(date2 == ymd(dmda)) %>%
  summarize(across(starts_with("DR"), sum)) %>%
  pivot_longer(everything(), names_pattern = "DR(.+)", values_to = "val") %>%
  mutate(name = as.numeric(name))
colnames(datas)<-c("Days","Numbers")
attach(datas)
plot(Numbers ~ Days, ylim=c(0,20))

model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 47,b2 = 0))

new.data <- data.frame(Days = seq(min(Days),max(Days),len = 45))
lines(new.data$Days,predict(model,newdata = new.data))

#Add the y points to the graph

df[, 1:2] = lapply(df[, 1:2], FUN = as_date)

get_cutoff = function(date) {
  date2 = as_date(date)
  date1 = df[1,1]
  as.numeric(date2 - date1 + 1)
}

subset_data = function(date, start_index) {
  date = as_date(date)
  if (date > df[1,1]) {
    end_index = start_index + get_cutoff(date) - 1
    df[, -c(start_index:end_index)] %>%
      filter(date2 == date)
  } else {
    return(df)
  }
}

y<-subset_data("2021-07-01", 4)
y

pivot_longer(y,
             cols=c(starts_with("DR"))) %>%
  mutate(day = parse_number(name)) -> new_y
new_y

lines(x=new_y$day, y=new_y$value, col="red")
points(x=new_y$day, y=new_y$value, col="red")

A: Make these changes:

*

*only load packages used

*can eliminate lubridate

*don't need dta

*in filter we don't need to convert dmda to Date class

*pivot_wider can transform the names

*don't use attach

*the model is linear in the parameters so use lm, not nls

*replace the new.data/lines with curve

*don't overwrite df

*simplify the cutoff calculation

*use type = "o" to reduce points/lines to just lines

*use subset in lines

Now assuming that df and dmda have been defined as in the question we have this.
library(dplyr)
library(tidyr)

datas <- df %>%
  filter(date2 == dmda) %>%
  summarize(across(starts_with("DR"), sum)) %>%
  pivot_longer(everything(), names_pattern = "DR(.+)",
    names_to = "Days", values_to = "Numbers",
    names_transform = list(Days = as.numeric))

plot(Numbers ~ Days, datas, ylim=c(0,20))

model <- lm(Numbers ~ I(Days^2), datas)
rng <- range(datas$Days)
curve(predict(model, list(Days = x)), rng[1], rng[2], add = TRUE)

# assume this for cutoff.  You may or may not need to change this line.
cutoff <- as.numeric(as.Date(dmda) - first(as.Date(df$date1))) + 1
lines(Numbers ~ Days, datas, subset = seq_len(nrow(datas)) > cutoff,
  type = "o" , col = "red")

A: I used ggplot rather than base R plotting functions since you are already working in the tidyverse. The following will do the trick to plot it all on a single graph.
dmda<-"2021-07-01"
dta<-df

## Rather than rely on column position, explicitly set the number
## of days desired for highlighting on plot
num_days <- 3

model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 47,b2 = 0))
new.data <- data.frame(Days = seq(min(Days),max(Days),len = 45)) %>%
    mutate(Numbers = predict(model, newdata = .))

datas<-dta %>%
    filter(date2 == ymd(dmda)) %>%
    summarize(across(starts_with("DR"), sum)) %>%
    ## Can convert data to numeric and create column names inside pivot_longer
    pivot_longer(everything(), names_pattern = "DR(.+)",
                 values_to = "Numbers", names_to = "Days",
                 names_transform = list(Days = as.numeric, Numbers = as.numeric)) %>%
    ## Create flag for whether the values are in the final number of days
    mutate(subs = 1:n() > (n() - num_days))

plt <- ggplot(datas, aes(x = Days, y = Numbers)) +
    geom_point(aes(color = subs)) +
    geom_line(data = filter(datas, subs == TRUE), color = "red") +
    geom_line(data = new.data, color = "black") +
    scale_y_continuous(limits = c(0, 20)) +
    scale_color_manual(values = c("black", "red"))
plt


text:
Q: using oauth in laravel gives Error: redirect_uri_mismatch i want to add google oauth to my laravel project using socialite package. i create a project in google developer console with address

http://lvh.me

which is localhost. and for callback url i add this:

http://lvh.me:8000/login/google/callback

and i added the routes and functions to my project and authController. now when i hit the address

http:lvh.me:8000/login/google

it returns for me the error:

Error: redirect_uri_mismatch
The redirect URI in the request, https://lvh.me:8000/login/google/callback, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs

what am i doing wrong?

A: This means that the redirect_uri you sent in the OAuth request doesn't match the one you have registered in the Google Cloud Console. Check and see whether either of them are wrong. They should be the same.


text:
Q: add vector as row in data.table I have a vector of length 6:
[1] "Grand Total"       "4846157.05310486"  "799995.35"         "5646152.40310486"  "34658346091.75"    "-9600.78021642406"
and a data.table with 17 objects and 6 variables
I can usually append the vector to the data table with rbind(table,list(vector))
but when i do it I get this message:
Error in rbindlist(l, use.names, fill, idcol) :
  Item 2 has 1 columns, inconsistent with item 1 which has 6 columns. To fill missing columns use fill=TRUE.

I have been able to do this in the past with exactly the same scenario but with this it wont work

A: solved by @MichaelChirico in the comments:
rbind(table,as.list(vector))


text:
Q: Non-inferiority testing without normal approximation I am performing a non-inferiority test on two binomial trials. I want to determine if my test proportion, pT, is not worse than my control, pC, by more than an amount d. Assuming nT trials of my test and nC trials of my control, the standard statistic for such a test is given by (da Silva 2009)
$$
z = \frac{pT - pC + d}{\sqrt{\frac{pT(1-pT)}{nT} + \frac{pC(1-pC)}{nC}}},
$$
which is distributed according to a standard normal distribution. However, this equation assumes that the binomial distributions generated by (pT, nT) and (pC, nC) are approximately Gaussian. My test and control proportions are both very close to one so this approximation doesn't hold. Is there a way of performing such a test exactly using the actual binomial distributions?


text:
Q: Run sgen on a 5MB assembly with many classes with the same name I'm trying to generate the XmlSerializers assembly for a project that outputs a 5MB dll. This project has many classes with different .Net namespaces but with the same name, so sgen is returning the error message "The top XML element 'XXXX' from namespace '' references distinct types XXXX and XXXX.
So I'm adding the TypeName property to the XmlTypeAttribute of every repeating class. The problem is, every time I run the SGEN command, it takes at least 15 minutes to show any feedback.
Do you have any suggestions?
Thanks.

A: sgen is a single-threaded tool, it runs in two phases - in first, it generates source code for serialization assembly, and in second phase it compiles generated assembly.
Probably you can get some performance boost if you will separate and compile your classes into several assemblies (equal to number of CPU cores), run sgen in parallel for each assembly, and then merge resulting dlls into one xml serializer using ILMerge.


text:
Q: Pop() etiquette Situation: I'm implementing a list-like container that supports a Pop() function that should return the user the const char* stored at the front of the container.  However, I'm not sure as an implementer whether or not I should be returning the original const char* (deleting the node pointer from the container but not calling delete on the const char* itself), or whether I should allocate new memory and return a copy of the element.
From class and projects, I've encountered those who espouse always copying, so that no previously returned references (from getters, etc.) and pointers to the const char* can alter the popped version, but since this approach requires an extra allocation and strcpy, I thought I'd ask whether simply returning the original, undeleted pointer to const char without deleting it is really a problem.  Here's a code snippet of the approach WITH allocation and copy (and deleting the original reference afterwards):
const char* LinkedList::PopHeadString()
{
    node* deletehead = head_;
    char* output = NULL;

    if (head_ != NULL && GetHeadType() == STRING) {
        output = new char[strlen(head_->en.data.str) + 1];
        strcpy(output, head_->en.data.str);
        head_ = head_->next;
        delete deletehead->en.data.str;
        delete deletehead;
        --nEntries_;
    }
    return output;
}

Since Pop() is a common container operation, I thought I'd ask what the general approach is.

A: If you return the pointer without copying you have to decide who owns the pointer. The one who owns it is responsible for deleting it when it is no longer needed. This can be a very hard problem, especially if your code gets more complex. Copy-semantics are much simpler to reason about.
In your specific example, the first thing to change would be to use std::string instead of const char * to represent strings. If you return an std::string by value, it will take care of the copying for you.
If you really want to prevent the copy, but still manage the lifetime elegantly, you should consider using an std::shared_ptr<std::string> (or boost::shared_ptr<std::string> if you don't have a C++11-compiler). A shared_ptr uses reference-counting to determine when the object it points to should be released, thus taking the burden of manual memory management from you, which is a Good Idea.


text:
Q: How to add a key val pair string -> []float64 to a map? I want to create a map from string keys to float64 array values. I initialize and assign:
gloveEmbeddings := make(map[string][]float64)
gloveEmbeddings["a"] := []float64{1.0, 2.0, 3.0}

But the second line gives the error:
./server.go:51:18: non-name gloveEmbeddings["a"] on left side of :=
How do I assign a float64 vector to the key "a" of the gloveEmbeddings map?

A: You assign by using assignment =, not short variable declaration (:=):
gloveEmbeddings := make(map[string][]float64)
gloveEmbeddings["a"] = []float64{1.0, 2.0, 3.0}

Try it on the Go Playground.
The := is to create new variables, and you don't want to create a new variable on the 2nd line, but only assign a value to a key in the already created map.


text:
Q: Best email server solutions on Windows We are currently use mdaemon and we have over than 1000 box of email. mdaemon seen to rich is limit because is always crash.
We are looking for another email server, could be exchange or other, support imap, pop3, smtp, syncrhonize calendar
Did you have some mail server to suggest ?
I need the solutions are compatible with windows server solutions

A: ~1000 Mailbox's and a Windows solution. While zimbra and google are good, I'm going to give Microsoft this one.
Exchange & Windows server are built for each other. I've seen an Exchange 2000 server still running on Windows 2000 server up until mid '09... It was only replaced because they wanted to use all the new bells and whistles in Outlook 2007!
So for that volume of users, go Exchange. Server 2008 R2 is a fantastic server OS, and Exchange 2007 will do wonders!
Things to consider with exchange: I'm going to assume that they are already running an active directory environment? Are all users located in the 1 building or spread across several... if several, what is the bandwidth like? All the users will need to use Outlook... Exchange does, however, have a nice Outlook Web Access client.
Exchange works of a MAPI protocol, so if 1000 people have outlook open, that 1000 open connections to your exchange server... make sure exchange has it's own server, and plenty of CPU and memory, not to mention storage!
Whats the budget like for this too? Licensing will be the biggest cost for exchange (next to the hardware).

A: You should consider Zimbra. It will do every you mentionned.

A: You told Antoine you need a Mircosoft solution, and if that is true, it's Exchange all the way. "imap, pop3, smtp, syncrhonize calendar", it does all that as well. There are tons of other options out, but for M$ products it is Exchange.
If you can reach out of M$, look at SmarterMail:
http://www.smartertools.com/SmarterMail/Features/Windows-Mail-Server-Software-Webmail-Exchange-Alternative.aspx
Runs on Windows just fine and it's pretty flexible.

A: What about google apps enterprise?

A: Preferred mail system/server for a company?

A: Nobody has mentioned this yet, but I'll throw modusMail out there for consideration as well.  It's designed for Windows, is a commercially supported product, and has one of the best spam filters that I have ever seen (and they are constantly pushing down updates to the filters if you're on a support plan).  It has a lot of bells and whistles out of the box and lots of options to customize it.  The only downside is that the webmail application that it ships with is rather weak and does not support any sort of calendar or shared notes, etc. like Exchange does.  It is available as software you can download and install or as a managed appliance you can connect to your network.  It is expensive compared to some of the others mentioned but worth every penny.

A: Exchange will do all you need, and will give you Active Directory integration as well (which you really should be using with 1000 mailboxes).  If you've nothing against using Exchange then I think this decision makes itself.

A: SmarterMail is honestly the most affordable and a very good solution. See the SmarterTools web site for more information. My web host runs this mail server and it's fast and works great.


text:
Q: Recover an array of integer saved as a string This is an example array i stored in a string property:
[12, 15, 75, 60]
When i tried to retrieve it
and access the index number, it included every character that denotes the array, for example if i ask for array[0], it gives me '[', instead of '12', array[3] gives me ',' array[6] gives me '5' and so on.
How can blender Python read the string like it does with array?
I tried enclosing things in int(), it throws a message "string indices must be integers" or "invalid literal for int() with base 10
Thank for your advance response!
I didn't include any code snippet as this problem is simple enough to understand, thanks, more power

A: If you want a string array let's convert it this way.
a = '[12, 15, 75, 60]'
b = a[1:len(a)-1].split(",")

print(b[0])

If you want a int array let's convert it this way.
a = '[12, 15, 75, 60]'
b = list(map(int, a[1:len(a)-1].split(",")))

print(b[0])


text:
Q: New function by adding two functions Is it possible to create a new function from the addition of two other functions in Julia? I want to do something like this:
function quadratic(x)
  return x^2
end

function cubic(x)
  return x^3
end

f::Function = quadratic + cubic
# such that f(x) returns x^2 + x^3

A: There is the less magic solution which is f(x) = quadratic(x) + cubic(x)

A: Every function[1] in Julia is a multimethod and can be extended after-the-fact. If we try to do quadratic + cubic, we get a message
ERROR: MethodError: no method matching +(::typeof(quadratic), ::typeof(cubic))

This isn't saying there will never be a way to make that work; it's saying nobody has bothered to do it yet. Let's write a version that works on functions.
# Extend the existing +, don't shadow it
import Base.+

+(f::Function, g::Function) =
    (args...; kwargs...) -> f(args...; kwargs...) + g(args...; kwargs...)

Now we can write
fn = quadratic + cubic
println(fn(10)) # 1100

[1] Technically, there are a handful of low-level bootstrapping functions that are deep magic and can't be extended, but + is not one of those.


text:
Q: wso2 identity server support for XACML (DLP/NAC) Profile Version 1.0 I have planned to implement NAC integration with xacml language. And I know Oasis support this as "XACML Data Loss Prevention / Network Access Control (DLP/NAC) Profile Version 1.0". My question is that there is a way to use this new xacml language in wso2 identity server? If not what could be solution NAC integration with xacml in wso2 identity server.

A: No, WSO2 has not attested to the XACML DLP/NAC profile. The profile was written by Boeing, Axiomatics, and Oracle. I would check their implementations.
The implementation needs to support the following datatypes and functions:

*

*urn:oasis:names:tc:xacml:3.0:data-type:ipAddress-value

*urn:oasis:names:tc:xacml:3.0:data-type:ipAddress-pattern

*urn:oasis:names:tc:xacml:3.0:function:ipAddress-match

*urn:oasis:names:tc:xacml:3.0:function:ipAddress-endpoint-match

*urn:oasis:names:tc:xacml:3.0:function:ipAddress-value-equal

*urn:oasis:names:tc:xacml:3.0:function:ipAddress-network-match

*urn:oasis:names:tc:xacml:3.0:data-type:dnsName-value

*urn:oasis:names:tc:xacml:3.0:data-type:dnsName-pattern

*urn:oasis:names:tc:xacml:3.0:function:dnsName-match

*urn:oasis:names:tc:xacml:3.0:function:dnsName-endpoint-match

*urn:oasis:names:tc:xacml:3.0:function:dnsName-value-equal

The Axiomatics implementation can be extended to support these (disclaimer: I work for Axiomatics and I am one of the coauthors of the profile)


text:
Q: Advanced parsing with python (Multiple Lines) I am stuck here with a parsing problem on python 2.7, let me explain:
I am parsing events from the incapsula API. The goal is to make them readable in an excel table, for making stats and graph.
On the signature field, you can read the type of event/attack and a number.
The number includes the number of attacks, so I decided to multiply each line by its corresponding sum of attack's number after the 'signature=' field.
Like this capture :
 visit_id=324001290181618591, src_country=Ukraine, event_timestamp=1484493309742, src_ip=91.223.133.30, dest_name=www.xxx.com, dest_id=1551642, signature={api.threats.sql_injection=3}
 visit_id=324001290181618591, src_country=Ukraine, event_timestamp=1484493309742, src_ip=91.223.133.30, dest_name=www.xxx.com, dest_id=1551642, signature={api.threats.sql_injection=3}
 visit_id=324001290181618591, src_country=Ukraine, event_timestamp=1484493309742, src_ip=91.223.133.30, dest_name=www.xxx.com, dest_id=1551642, signature={api.threats.sql_injection=3}

So far everything goes as expected, I got the right count of attacks.
BUT
On some rare events, they are multiple values on the signature field, like this capture :
 visit_id=324001290181618591, src_country=Ukraine, event_timestamp=1484493309742, src_ip=91.223.133.30, dest_name=www.xxx.com, dest_id=1551642, signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
 visit_id=324001290181618591, src_country=Ukraine, event_timestamp=1484493309742, src_ip=91.223.133.30, dest_name=www.xxx.com, dest_id=1551642, signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
 visit_id=324001290181618591, src_country=Ukraine, event_timestamp=1484493309742, src_ip=91.223.133.30, dest_name=www.xxx.com, dest_id=1551642, signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
 visit_id=324001290181618591, src_country=Ukraine, event_timestamp=1484493309742, src_ip=91.223.133.30, dest_name=www.xxx.com, dest_id=1551642, signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
 visit_id=324001290181618591, src_country=Ukraine, event_timestamp=1484493309742, src_ip=91.223.133.30, dest_name=www.xxx.com, dest_id=1551642, signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
 visit_id=324001290181618591, src_country=Ukraine, event_timestamp=1484493309742, src_ip=91.223.133.30, dest_name=www.xxx.com, dest_id=1551642, signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
 visit_id=86001060468746692, src_country=Netherlands, event_timestamp=1483867285054, src_ip=178.22.232.53, dest_name=www.yyy.com, dest_id=1551642, signature={api.threats.bot_access_control=1, api.threats.illegal_resource_access=3,}
 visit_id=86001060468746692, src_country=Netherlands, event_timestamp=1483867285054, src_ip=178.22.232.53, dest_name=www.yyy.com, dest_id=1551642, signature={api.threats.bot_access_control=1, api.threats.illegal_resource_access=3,}
 visit_id=86001060468746692, src_country=Netherlands, event_timestamp=1483867285054, src_ip=178.22.232.53, dest_name=www.yyy.com, dest_id=1551642, signature={api.threats.bot_access_control=1, api.threats.illegal_resource_access=3,}
 visit_id=86001060468746692, src_country=Netherlands, event_timestamp=1483867285054, src_ip=178.22.232.53, dest_name=www.yyy.com, dest_id=1551642, signature={api.threats.bot_access_control=1, api.threats.illegal_resource_access=3,}

I still got the right count of attacks on those rare lines too, but I want to arrange the signature field from this :
signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
signature={api.threats.bot_access_control=1, api.threats.illegal_resource_access=3,}
signature={api.threats.bot_access_control=1, api.threats.illegal_resource_access=3,}
signature={api.threats.bot_access_control=1, api.threats.illegal_resource_access=3,}
signature={api.threats.bot_access_control=1, api.threats.illegal_resource_access=3,}

To this:
signature={api.threats.sql_injection}
signature={api.threats.sql_injection}
signature={api.threats.sql_injection}
signature={api.threats.bot_access_control}
signature={api.threats.illegal_resource_access}
signature={api.threats.cross_site_scripting}
signature={api.threats.bot_access_control}
signature={api.threats.illegal_resource_access}
signature={api.threats.illegal_resource_access}
signature={api.threats.illegal_resource_access}

(the first six lines are the first event duplicated 6 times (3+1+1+1 =6), the last 4 are the second event duplicated 4 times (1+3=4)
My current source code:
#count the number of attack per line
f = open('monthlyLogShort.txt','r')
g = open("count.txt", 'w')
kensu = f.readlines()
f.close()
for line in kensu:
        st = line.find('signature=')
        end = line.find('}')
        unprecise = line[st:end+1]
        #count = int(re.search(r'\d+', unprecise).group())
        count = sum(map(int,re.findall(r'[0-9]+', unprecise)))
        print >> g, count

g.close()

#replicate lines according to the number of attack
h = open('flog.txt','w')

with open("monthlyLogShort.txt") as textfile1, open("count.txt") as textfile2:
    for x, y in izip(textfile1, textfile2):
        x = x.strip()
        y = y.strip()
        print >> h, x * int(y)
h.close()

A: If I read your requirements correctly, you are trying to emit one line for each threat occurrence while preserving the rest of the record.  This solution does not output the counts directly, instead it transforms the data so that it is uniformly one threat per line.
Code:
sig_str = 'signature={'
for line in kensu:
    record, signature = line.split(sig_str)
    threats = signature.split('}')[0]
    for counts in threats.split(','):
        if '=' in counts:
            threat, count = tuple(counts.split('='))
            for i in range(int(count)):
                print '%s%s%s}' % (record, sig_str, threat.strip())

Sample data:
kensu = [x.strip() for x in """
    record=0, signature={api.threats.sql_injection=1}
    record=1, signature={api.threats.sql_injection=3, api.threats.bot_access_control=1, api.threats.illegal_resource_access=1, api.threats.cross_site_scripting=1,}
    record=2, signature={api.threats.bot_access_control=1, api.threats.illegal_resource_access=3,}
""".split('\n')[1:-1]]

Output:
record=0, signature={api.threats.sql_injection}
record=1, signature={api.threats.sql_injection}
record=1, signature={api.threats.sql_injection}
record=1, signature={api.threats.sql_injection}
record=1, signature={api.threats.bot_access_control}
record=1, signature={api.threats.illegal_resource_access}
record=1, signature={api.threats.cross_site_scripting}
record=2, signature={api.threats.bot_access_control}
record=2, signature={api.threats.illegal_resource_access}
record=2, signature={api.threats.illegal_resource_access}
record=2, signature={api.threats.illegal_resource_access}


text:
Q: .Net assembly mapping policy purpose what is the reason/purpose for doing assembly mapping? changing version policy?. I understand that if your app.exe wanted to use a new assembly version you could redirect assembly version, but why would you want to?. Wouldn't the new version of dependent assembly change?
Suppose there is a calc.dll and app.exe. app.exe depends on calc.dll. If calc.dll was rebuild and bunch of methods renamed wouldn't app.exe fail when ran when redirected to calc.dll new version?

A: Since authors that care about customers strive to keep interfaces/types of the same assembly backward-compatible then using newer versions of the same assembly is generally not a problem.
Main issue is other assemblies depending on older versions.
Lets say there is common "Shared.dll" which has multiple compatible versions (well known sample - JSON.Net) and used by your code as well by some other DLL your code needs:
ThridParty.dll (v1) -> Shared.dll (v1)
YourApp.exe -> Shared.dll (latest = v5), ThirdParty.dll (v1)

Now you need 2 versions of Shared.dll but both have same file name (solvable by manually loading one) and inability to use objects produces by mixed versions (Shared.Type1 from v1 is not the same as Shared.Type1 from v5 by .Net rules).
To solve you use assembly redirect and say "whenever anyone asks for Shared.dll v1 use Shared.dll v5". This way ThridParty.dll continue to work just fine and you no longer face problems with 2 files/versions loaded at the same time.


text:
Q: Evaluate $\int x \cos x^2 dx$ Hay I have hit this in my book
Evaluate $\int x \cos x^2 dx$.
I got $x^2 \sin(x^2) / 2 $
But I used a online calculator to check it and it is giving me $\sin(x^2)/2 $
Where dose my X go?

A: U-substitution allows us to "reverse"/invert the process one uses with the chain rule in differentiating.
Challenge: Try differentiating your answer, and then differentiating the given solution, and see which one gives you the expression in the integrand, below, in $(1)$?
Now, we have the following integral.
$$\int x \cos(x^2 )dx \tag{1}$$
Using u - substitution:
Let $\color{blue}{\bf u = x^2};\;$ then $\,du = 2x dx \implies \color{red}{x\,dx = \frac 12 du}$
Substitute: $$\int \color{red}{\bf x } \cos(\color{blue}{\bf x^2 })\color{red}{\bf \,dx} \quad = \quad \color{red}{\bf \frac 12} \int \cos \color{blue}{\bf u} \color{red}{\bf\,du} \quad = \quad \frac 12 \sin u + C$$
Back substituting: $$\frac 12 \sin u + C\; =\;\frac 12 \sin(x^2) + C \;= \;\frac{\sin(x^2)}{2} + C$$

A: Let $u=x^2$. Then $du = 2xdx$. Hence
$$
\int x \cos(x^2)\ dx = \frac{1}{2}\int \cos(u)\ du = \frac{\sin(u)}{2} + C = \frac{\sin(x^2)}{2} + C.
$$

A: $\int x \cos(x^2) dx=\int \frac{1}{2}\cos(x^2) d(x^2)=\frac{1}{2}\sin(x^2)+C$


text:
Q: Convenience methods for resizable images I've got a load of images that are resizable in my app and I use them all over the place.
Most of them have the same edge insets but some are different.
It takes a lot of code to create them too...
UIImage *buttonBGImage = [[UIImage imageNamed:@"buttonBG"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 4, 5, 4) resizingMode:UIImageResizingModeStretch];

It's only one line of code but I have to go looking for all the edge insets etc...
I'm trying to create a convenience method for it instead. Something like...
UIImage *buttonBGImage = [blah resizableButtonBG];

Where would be the best place for these? I could create a singleton called "ImageManager". That way each resizable image would only get instantiated once and then would be held in memory. Is that overkill?
I could add a category to UIImage called...
+(UIImage *)resizableButtonBG;

Can anyone provide any advice on this? Is my singleton idea a good one? Are there any cons against using a Singleton?

A: A category method is definitely a good solution. Many people use this for creating fonts and colors which are used in multiple places in an application.
Using a singleton is not necessary. There is no associated instance data so you might as well stick with simple category methods which return the appropriate image.


text:
Q: Oracle Apex Interactive Grid When delete set column null/any value Can we modify interactive grid such that when we select and delete a row, instead of deleting the entire row, a column of that row gets updated to a particular value?
If it can be done using dynamic actions can you please suggest how?
Ex of my interactive grid->

So when i select the 3 lines next to check box and choose option to delete row, it shows the row as strike off.
But actually instead of deleting it would set Approver column to 'Not Approver'

A: Here's how you can do by creating a button and then defining a dynamic action.
1)Set the static ID of your IG
2)Create a button and set it to Defined by Dynamic Action
3)Set the True action to execute Javascript Code. Now, your Javascript code should include to set the value of a column in a record by using the setValue method.


text:
Q: Function didn't return the desired value when it is used more than once When I used the sortAsc_byPosition function twice
public class stringArraySort {
    public static String[] sortAsc_byPosition(String[] str, int charPosition) {
        for(int r=0; r<str.length-1; r++) {
            for(int i=r+1; i<str.length; i++) {
                int j=charPosition;
                while (str[r].charAt(j)==str[i].charAt(j)) {
                    j++;
                }
                if (str[r].charAt(j)>str[i].charAt(j)) {
                    String tmp=str[i];
                    str[i]=str[r];
                    str[r]=tmp;
                }
            }
        }
        return str;
    }

    public static void main(String[] args) {
        String[] productID= {"Xcra-S1836", "Zkda-D3426", "Ypdu-B5654", "Akdr-Z5075", "Jhbd-K4051"};
        String[] result1=sortAsc_byPosition(productID, 5);
        String[] result2=sortAsc_byPosition(productID, 6);

        System.out.println("Result of array sorted by character position at 5 :" + Arrays.toString(result1));
        System.out.println("Result of array sorted by character position at 6 :" + Arrays.toString(result2));
    }

to get the desired result, the function failed to make it.
But, when I used the function only once, it works.
public static void main(String[] args) {
        String[] productID= {"Xcra-S1836", "Zkda-D3426", "Ypdu-B5654", "Akdr-Z5075", "Jhbd-K4051"};
        String[] result1=sortAsc_byPosition(productID, 5);

        System.out.println("Result of array sorted by character position at 5 :" + Arrays.toString(result1));
    }

What is the main cause of this problem? What is the correct way to make it? Thanks for the answer...

A: Your sortAsc_byPosition method accepts an array, makes changes to that array and returns the same array. This means result1 == result2 (both variables are references to the same array object).
Therefore, when you execute the method twice, the result you'll see in the end is the sort order used by the second call.
You should return a copy of the array if you want to have two different arrays having different order.
For example:
public static String[] sortAsc_byPosition(String[] str, int charPosition) {
    String[] result = Arrays.copy(str,str.length);
    for(int r=0; r<result.length-1; r++) {
        for(int i=r+1; i<result.length; i++) {
            int j=charPosition;
            while (result[r].charAt(j)==result[i].charAt(j)) {
                j++;
            }
            if (result[r].charAt(j)>result[i].charAt(j)) {
                String tmp=result[i];
                result[i]=result[r];
                result[r]=tmp;
            }
        }
    }
    return result;
}


text:
Q: How to build a macro that return the absolute value of an argument of another macro? How can I build a macro that return the absolute value of an argument of another macro? I would like that the \abs macro return the absolute value of the its argument.
\RequirePackage{tikz}
\newcommand{\abs}[1]{<implementation>}
\newcommand{\command}[2]{\raisebox{\numexpr\abs{#1}*#1\relax\baselineskip}[0pt][0pt]{}{}}

So whether I use a positive or negative number as argument, the expression \abs{#1} will always be positive.

A: --1 is legal in \numexpr, equivalent to 1. So
\newcommand{\absval}[1]{\ifnum#1<0 -\fi#1}

is what you're looking for. Then
\newcommand{\command}[2]{%
  \raisebox{\numexpr\absval{#1}\relax\baselineskip}[0pt][0pt]{}{}}

will do.


text:
Q: resize cover image through css in web view I am working on a reader and I have an issue with latest generation of android devices which comes with high resolution. The pictures on webViews are showing very small, while on older devices their size seemed acceptable. I cannot manipulate the content of the HTML files, I can only manipulate the webView's settings and the .css file linked to the webView.
Initially when I open the book the image shows very small, but when I manipulate the image it gets over magnified and becomes trimmed in both sides.
img
{
    max-width: 100%;
    width:auto;
    height: auto;
}

I also tried:
 img
 {
     min-width: 100%;
     height: auto;
 }

This is the webView settings:
testWV = (WebView) findViewById(R.id.mywebview1);
testWV.setDelegate(this);

testWV.setVerticalScrollBarEnabled(false);
testWV.setHorizontalScrollBarEnabled(false);
testWV.getSettings().setDefaultZoom(ZoomDensity.FAR);

A: Okay, try this, you may remove the head tag if you wish, the style is the important part
String content = "Your Content"; // I assume your content is a string

testWV = (WebView) findViewById(R.id.mywebview1);
testWV.setDelegate(this);

testWV.setVerticalScrollBarEnabled(false);
testWV.setHorizontalScrollBarEnabled(false);
testWV.getSettings().setDefaultZoom(ZoomDensity.FAR);

String head = "<head><meta name='viewport' content='target-densityDpi=device-dpi'/></head>";

String style =  "<style> " +
                "img { height:auto !important; width:100% !important; } " +
                "</style>";

testWV.loadDataWithBaseURL("", head + style + content, "text/html", "UTF-8", "");


text:
Q: Get
* value and assign to url parameter in iframe using jquery onclick It's a question related to this.
From

featured

hey

wish

To

onclick

A: Try this

featured

hey

wish

A: you can use like this

featured

hey

wish


text:
Q: List all filenames from windows file share using python Can someone guide me on how to list all filenames in a windows shared folder using python.
Connecting to this network drive requires a username and password.
Which python libraries do I need?
I'm assuming I need something like:
import os

files = []
with open(r"\\12.xxx.xx.123\files",'r') as ff:
    # r = root, d = directories, f = files
    for r, d, f in os.walk(path):
        for file in f:
            print("element f = " + f)
            files.append(os.path.join(r, file))

if my path requires a username and password, how can I pass those credentials to get a successful connection. Currently, I am getting permission denied.
Thanks.


text:
Q: AngularJS set css to tag in directive (Bootstrap sticky footer) I am developing my first AngularJS app using Bootstrap as the responsive framework. The app needs an bs sticky footer. Normally i use jQuery to calculate the outerHeight of the footer and set the value to the body tag as padding bottom in css.
I don't want to use jQuery so i've been fiddling to make this work in pure AngularJS.
HTML

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <meta name=viewport content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=0">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/style.min.css" rel="stylesheet" type="text/css" media="all" />

JS
var app = angular.module("ngApp", [])
  // footer height
  .directive('footerHeight', function() {
    return {
      link: function(scope, element) {
        scope.$watch(function() {
          var footerHeight = element[0].offsetHeight;
          var elBody = angular.element(document).find('body')
          elBody.css('padding-bottom', footerHeight);
          console.log(footerHeight);
        });
      }
    };
  }); // end app

The height of the footer is calculated correctly as seen in the console but the value is not being set to the body tag.

A: I think you need to create your own directive and you can put on your div
app.directive('outerHeight', function(){
  return{
    restrict:'A',
    link: function(scope, element){
       return angular.element(element).prop('offsetHeight');
    }
  };
});


text:
Q: strlwr() function in C not working despite library included and linked? I'm on Linux Gallium OS 4.16.18 using VSCode following a beginner's tutorial in C.
The code example is:
#include <stdio.h>
#include <string.h>

int main(){

    char string1[] = "Bro";
    char string2[] = "Code";

    strlwr(string1, string2);

    printf("%s", string1);

    return 0;
}

Warning:
warning: implicit declaration of function 'strlwr'; did you mean 'strlen'? [-Wimplicit-function-declaration]
 strlwr(string1, string2);
 ^~~~~~

Refuses to compile:
undefined reference to 'strlwr'
collect2: error: ld returned 1 exit status

The fact that string2 is not being used shouldn't concern us, it's there for the next step in his tutorial. This program should compile anyway but for me it doesn't.
What's interesting is that an earlier tutorial using the <math.h> library didn't work for me either. I looked up the error and found out that my VSCode doesn't link the libraries like I want it to. I wasn't smart enough to configure it correctly, but I was able to circumvent the problem:
For just this one example using the <math.h> library I compiled the code outside VSCode using
GCC myprogram.c -o myprogram -lm

In this case -lm was needed to link the math library and the program compiled!
Now I've tried the same thing with this <string.h> library but to no avail.
https://www.qnx.com/developers/docs/7.1/#com.qnx.doc.neutrino.lib_ref/topic/s/strlwr.html
This site says 'strlwr' belongs to the library 'libc':

Use the -l c option to qcc to link against this library. This library
is usually included automatically.

But like I mentioned, adding -lc to my GCC compiling command didn't work. What's even weirder is that Wikipedia says 'strlwr' isn't even part of the <string.h> library.
https://en.wikipedia.org/wiki/C_string_handling
and this site seems to agree (in German though).
https://www2.hs-fulda.de/~klingebiel/c-stdlib/string.htm
But in every tutorial I find online it works like a charm using only <string.h>.
If I use strcat which IS found in <string.h> my program compiles even in VSCode without error or warning.
What's going on here?

A: As user alex01011 pointed out 'strlwr' is a Microsoft library and I was using Linux.
Solved.


text:
Q: $f$ integrable and $E_n=\{x\in X: f(x)>2n\}$ I have to calculate this 2 limits:
$$\lim_{n\to\infty}\int_{E_n}fd\mu \ \text{and} \ \lim_{n\to\infty}n\mu(E_n).$$
For the first one I do:
$$\lim_{n\to \infty} \int_{E_n} f d\mu = \lim_{n\to \infty} \int_X f\chi_{E_n}d\mu$$
Being $f\chi_{E_n}$ this sequence of function:
$$f\chi_{E_n}=\left\{\begin{matrix}
f &x\in E_n \\
0 & x\notin E_n
\end{matrix}\right.$$
By MCT, we have
$$\lim_{n\to \infty} \int_X f\chi_{E_n}d\mu=\int_X \left(\lim_{n\to \infty} f\chi_{E_n}\right)d\mu=\int_X 0d\mu=0$$
Now, calculating the second limit in the same way,
$$\lim_{n\to\infty}n\mu(E_n)=\lim_{n\to\infty}n\int_X\chi_{E_n}d\mu=\lim_{n\to\infty}\int_X n\chi_{E_n}d\mu$$
By MCT, we have
$$\lim_{n\to\infty}\int_X n\chi_{E_n}d\mu=\int_X \lim_{n\to\infty}\left(n\chi_{E_n}\right)d\mu$$
But this limit is an indeterminacy, right?

A: Since $f \chi_{E_n} \geq 2n\chi_{E_n}$ we get  $\int_{E_n} f \geq \int_{E_n} 2n = 2n \mu (E_n)$ and $\int_{E_n} f  \to 0$ so $\lim n \mu(E_n)=0$.


text:
Q: reconciling Facebook PHP SDK with zend framework so I'm using the Facebook PHP SDK for authenticating my user....
and I'm trying to logout my user using the destroySession() method in base_facebook.php
These are some relevant excerpts in the PHP SDK's base_facebook.php: https://github.com/facebook/php-sdk/blob/master/src/base_facebook.php
      public function destroySession() {
        $this->setAccessToken(null);
        $this->user = 0;
        $this->clearAllPersistentData();
      }

  protected function clearAllPersistentData() {
    foreach (self::$kSupportedKeys as $key) {
      $this->clearPersistentData($key);
    }
  }

  protected function clearPersistentData($key) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to clearPersistentData.');
      return;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    unset($_SESSION[$session_var_name]);
  }

but everytime I try to do so, Zend Framework would complain
Fatal error: Uncaught exception 'Zend_Session_Exception' with message 'session has already been started by session.auto-start or session_start()'

Zend_Session_Exception: session has already been started by session.auto-start or session_start()

How do I go about clearing my facebook session without triggering all these errors?

A: In order to make it work with Zend_Session, I modified the facebook.php source code and replace
    session_start()

by
    $this->session = new Zend_Session_Namespace();
    $this->session->fb = array();

Then replace all occurences of
    $_SESSION"

by
    $this->session->fb

A: The prerequisite for using Zend_Session is the session must not be initiated yet. Facebook initiates it. As a solution, call session_write_close() before using Zend_Session.
Alternatively, call session_destroy() to logout the facebook user. It destroys all of the data associated with the current session.


text:
Q: How to set camera orientation in Android? I've looked at other questions where people have asked this, but I wasn't sure what the best way to solve this problem was. After going through Android's guide to implement the camera, the camera preview I have is locked into landscape. I wanted to know how to adjust the camera orientation to mirror the orientation of the phone.
I tried this
camera.setDisplayOrientation(90);

And that locked the camera into portrait mode, so I need another solution (preferably one that works for most devices).
Also, how can I make it so the saved image shows up the same way as the preview? Right now if I use that line of code above to make the preview go to portrait, the saved image is still rotated for a landscape.

A:  Camera.Parameters params= mCamera.getParameters();
 params.set("rotation", 90);
 mCamera.setParameters(params);

A: You need to take the orientation into account when determining what preview size to choose. For example, the getOptimalPreviewSize() from the CameraPreview of ApiDemos is oblivious to orientation, simply because their version of that app has the orientation locked to landscape. If you wish to let the orientation float, you need to reverse the target aspect ratio to match. So, where getOptimalPreviewSize() has this
double targetRatio=(double)width / height;

And
if (displayOrientation == 90 || displayOrientation == 270) {
  targetRatio=(double)height / width;
}

where displayOrientation is a value from 0 to 360, that I am determining from about 100 lines of some seriously ugly code, which is why I am wrapping all of this up in a reusable component that I'll publish shortly.
Second, you need to take that display orientation into account when controlling the aspect ratio of the SurfaceView/TextureView that you are using. The CameraPreview activity from ApiDemos has its own Preview ViewGroup that handles the aspect ratio, and there you need to reverse the aspect ratio for use in portrait:
if (displayOrientation == 90
        || displayOrientation == 270) {
      previewWidth=mPreviewSize.height;
      previewHeight=mPreviewSize.width;
    }
    else {
      previewWidth=mPreviewSize.width;
      previewHeight=mPreviewSize.height;
    }

where displayOrientation is that same value (90 and 270 being portrait and reverse-portrait respectively, and note that I haven't tried getting reverse-portrait or reverse-landscape to work, so there may be more tweaking required).
Third - you must start the preview before calling setPictureSize() on the Camera.Parameters. Otherwise, it's as if the aspect ratio of the picture is applied to the preview frames, screwing things up.
Camera.Parameters parameters=camera.getParameters();
Camera.Size pictureSize=getHost().getPictureSize(parameters);

parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);

camera.setParameters(parameters);
camera.startPreview();

parameters=camera.getParameters();
parameters.setPictureSize(pictureSize.width, pictureSize.height);
parameters.setPictureFormat(ImageFormat.JPEG);
camera.setParameters(parameters);

A: I fixed this using the Google's camera app. It gets the phone's orientation by using a sensor and then sets the EXIF tag appropriately. The JPEG which comes out of the camera is not oriented automatically.
Also, the camera preview works properly only in the landscape mode. If you need your activity layout to be oriented in portrait, you will have to do it manually using the value from the orientation sensor.
I'd recommend checking the photo's exif data and looking particularly for
ExifInterface exif = new ExifInterface(SourceFileName);   //API Level 5
String exifOrientation = exif.getAttribute(ExifInterface.TAG_ORIENTATION);

Leave comment and Let me know if this helps you.


text:
Q: The font, "riffic free-bold" doesn't work in p5.js So I'm doing the obvious...
var font;
function preload() {
    font = loadFont('assets/text/riffic.ttf');
}
function setup() {
    createCanvas(600, 600);
}

and then to call it I use...
function draw() {
    textFont(font);
    text("Hello", 100, 100);
}

When I try to use this font, the console tells me this...
Uncaught TypeError: Cannot read property 'length' of undefined
at Substitution.getDefaultScriptName (p5.js:31993)
at Font.stringToGlyphs (p5.js:27954)
at Font.forEachGlyph (p5.js:28069)
at Font.getAdvanceWidth (p5.js:28144)
at p5.Font._textWidth (p5.js:63498)
at p5.Font._handleAlignment (p5.js:63523)
at p5.Font._getPath (p5.js:63339)
at p5.Font._renderPath (p5.js:63458)
at p5.Renderer2D._renderText (p5.js:48828)
at p5.Renderer2D.text (p5.js:48788)

but no matter where I get it from the font style "Riffic free-bold just will not work with p5.js for me! Is there some kind of reason for this? Is riffic free-bold different from other fonts? If so, how? (I REQUIRE riffic free-bold, so I can't just use another font.)