text:
Q: Converting timezones using pytz on Pandas Series I am trying to convert the timezone of a pandas Series. I am using the pytz package to do so, however I am getting a value that is off by a few minutes.
The code I am currently using can be found in the answer here: Converting Items from Pandas Series to Date Time
Other answers suggest using the localize() function to make this work, however this does not work in my code. I tried using the normalize() function to solve this issue but I am getting an error using a pandas series.

Error message: AttributeError: 'Series' object has no attribute
  'tzinfo'

Sample input:
dfNY = pd.DataFrame({'TimeSeries': [13:00, nan, 06:00, 'Morning', 'Afternoon', nan, nan, 01:30]})

Desired output:
dfLondon = pd.DataFrame({'TimeSeries': [18:00, nan, 11:00, 'Morning', 'Afternoon', nan, nan, 06:30]})

Current code:
    import pandas as pd
    from pytz import timezone
    dfNY = pd.DataFrame({'TimeSeries': [13:00, nan, 06:00, 'Morning', 'Afternoon', nan, nan, 01:30]})
    tzDestination = "Europe/London"
    dtTimeSeries = pd.to_datetime(dfNY.TimeSeries, errors='coerce', format='%H:%M').dt.tz_localize(tzOrigin)
    tzChange = timezone(tzDestination)
    convertedTime = tzChange.normalize(dtTimeSeries).dt.strftime('%H:%M')
    dyNY = convertedTime.copy()
    dfNY = timeSeries.where(~convertedTime.ne('NaT'), convertedTime)

Thanks for any help

A: When I run the code from the previous answer it works just fine.  Compare your code to IMCoins' and see where the difference is (you create a separate time series whereas IMCoins keeps everything within the dataframe).
Second, regarding why the time stamp is off by four minutes, see the answer here.  How can you fix this?  Well, I doubt you have data from the year 1900, so you could set the date as something AFTER 1-Jan. 1902.


text:
Q: Broadcastreceiver does not start activity My application basically detects screen unlock and pops up a toast. Its working fine with a toast but when I implent an Intent and call another activity it crashes..
package com.androidexample.screenonoff;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class AEScreenOnOffService extends Service  {
    BroadcastReceiver mReceiver=null;

        @Override
        public void onCreate() {
            super.onCreate();

            // Toast.makeText(getBaseContext(), "Service on create", Toast.LENGTH_SHORT).show();

            // Register receiver that handles screen on and screen off logic
            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            mReceiver = new AEScreenOnOffReceiver();
            registerReceiver(mReceiver, filter);

        }

        @Override
        public void onStart(Intent intent, int startId) {

            boolean screenOn = false;

            try{
                // Get ON/OFF values sent from receiver ( AEScreenOnOffReceiver.java )
                screenOn = intent.getBooleanExtra("screen_state", false);

            }catch(Exception e){}

             //  Toast.makeText(getBaseContext(), "Service on start :"+screenOn,
                    //Toast.LENGTH_SHORT).show();

            if (!screenOn) {

                // your code here
                // Some time required to start any service
                Toast.makeText(getBaseContext(), "Begin ", Toast.LENGTH_LONG).show();

Here I am adding an intent to start an activity.
Intent intent = new Intent(AEScreenOnOffService.this,postlockscreen.class);
            startActivity(intent);

            } else {

                // your code here
                // Some time required to stop any service to save battery consumption
                //Toast.makeText(getBaseContext(), "Screen off,", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
        }
}

I have checked the xml for the new activity the class all seems to be fine but nothing seems to be working.

A: try this way
  Intent yourintent = new Intent(this, MyActivity.class);
            yourintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(yourintent);

Hope this helps you

redpajama_set_name: RedPajamaStackExchange


text:
Q: Relations between the trace elements in the cyclic permutations It is well known that the trace is invariant under cyclic permutations, i.e.
$tr(ABCD)=tr(BCDA)=tr(CDAB)=tr(DABC)$ here $A,B,C,$ and $D$ are matrices.
Now, let assume that I define the operator $H1=ABCD$ in the basis $\{a_1,a_2...,a_{n-1},a_n\}$ and $H2=DABC$, what will be the basis of $H2$ with respect to the original basis?. In other words, we know that $tr(H1)=tr(H2)$ but individual elements of the diagonal are not the same i.e. $H1(i,i)\neq H2(i,i)$ but $\sum_{i=1}^n H1(i,i)= \sum_{i=1}^n H2(i,i)$. So, is it possible to find a relation between the elements on the diagonal  of  $H1$ and $H2$ such that if I know  all the diagonal  elements of $H1(i,i)$ I can immediately calculate each element on the diagonal of $H2(i,i)$?
I think there should be a unitary transformation that connect the basis of $H1$ and $H2$ but don not know how to find it!


text:
Q: Do notation without monads: possible? I have a stateful type with the >> and >>= operators, which is nearly a monad. The intended use is to generate code for another language, and having the do-notation available will be very appropriate.
However, there is no well-defined return function, as values are only supposed to be produced along with side-effects. So, if I fake a return function, the return function should return an error only, and it breaks the monad laws. ( I.e. it is never valid to use a return function. )
What I observe is that the do-notation only sugars two operators, the >> and >>= operators.
Is there a way to retain something like the do notation for only those 2 operators, or something as clean as it, but without making a monad?
NOTE: Below the line are details that are not necessary for the question in the title. It's the context for why I asked the question, replies to which I'm interested in. Others who browse this topic would probably prefer to ignore it.

CORRECTION: I'm not generating code into an imperative language, although it shouldn't matter. I'm generating code into Javascript.
CLARIFICATION (in response to bdonlan): My type is (m a), which carries a state (which is the code to be generated given various parameters, similar to the state monad) and will return a value (the variable names in the generated code, with a haskell type attached). Thus, there shouldn't be a way to return values, which are associated with variable names, without generating code that defines the variable names. * This is solely due to my design, which might be inferior to others which I have not thought of.
In response to the responses: There seems to be two kinds of responses to this. First, is whether it is indeed possible, and perhaps the best way to go about using the do notation. The second is on whether it is better to use a monad, and define a return (or whether it even makes sense to not do so - perhaps at a later point in time, I would find that a return is required).
Example of what I would be doing:
data JsState = JsState { code :: String , vidCount :: Int }
-- vidCount is for generating unique variable names

newtype JsStmt = JsStmt ( JsState -> JsState )

newtype JsMonad a = JsMonad ( JsState -> ( a , JsState ) )

def :: (JsValue a) => a -> JsMonad a

-- Outputs "var " ++ toUniqueVarName vidCount ++ " = " toCode a ++ ";"

-- Returns JsMonad with the variable name as the value,
-- with a type attached, and the JsState's vidCount is incremented by 1.

alertJsInt :: JsIntE -> JsMonad ()

-- Outputs something like "alert(" ++ toCode JsIntE ++ ");"

do
  x <- def $ JsIntL 2
  y <- def $ JsIntL 4
  alertJsInt (x + y)

A: The idiomatic solution would be to use two monads Writer and State - Writer to accumulate the code "String" and State to track the variable counter.
You can combine the two monads into one amalgamated monad if you don't want to use a monad transformer library:
-- There are better types to use rather than String...
type Output = String
type St  = Int

newtype JsMonad a = JSMonad { getJSMonad :: St -> (a, St, Output) }

[As you are using the standard combination of two standard monads the obvious definition of return and bind won't break the monad laws.]
This is quite a common pattern for building embedded DSLs that use the do-notation, see Andy Gill's Dot library on Hackage for instance. Oleg Kiselyov also has an XML library in this style (CSXML - not on Hackage).
As you don't care about about the final answer, it is common to write a "run" function that ignores it:
runJS :: JSmonad a -> Output
runJS ma = post $ getJSMonad ma 0
  where
    post (_,_,w) = w

One thing to note is that the output code is just a "log" - you cannot inspect it as you are building it, so this does limit some of the things you can do.

A: It would be very difficult to use do notation without return. Consider the common pattern of:
foo = do
    x <- bar
    y <- quux
    return $ x + y

Without return it is impossible to define this. Recall that >>= has type (>>=) :: Monad m => m a -> (a -> m b) - it must return a value inside the monad. So even if we write this out without do notation, we have the same problem:
foo = bar >>= \x -> quux >>= \y -> (???????) (x + y)

So it's not a good idea to use do-notation for this. Particularly, there's nothing to stop the compiler implementation from introducing returns with transformations conforming to the monad laws (which assume the presence of return).
Moreover, even defining >>= will be difficult for you. How will you translate it to your imperative language? Remember that >>= takes an arbitrary function on its right argument; you are unable to inspect this function to tell what it might do, and thus cannot translate the body of this function into an imperative language. I suppose you could constrain the type of the argument to some kind of traced datatype and try to figure out the effects of the function, but now this means the function can't inspect its argument. In short, it's just not going to work very well.
One alternate approach you might consider is to create a Monad that represents the process of building an imperative function. It might, for example, look like this:
emitAddAndPrint varA varB = do
    varTmp <- allocateTempVariable
    emitOp (Add varTmp varA varB)
-- if you want to be fancy, emitOp (varTmp :=: varA :+: varB) or something
    emitCall "print" [varTmp]

A: It sounds like you have an arrow.  In a monad you need to be able to write:
do
   x <- return $ f y
   if x then something else notSomething

The "if" condition gets evaluated as part of the evaluation of the "do", and the result is either "something" or "notSomething", but not both at once.  However for code generation you probably want the "if" to be translated into your generated code with both branches evaluated to produce code that can make the choice at its run-time.
The equivalent code for an arrow desugars into use of the the ArrowChoice class in which you have access to both the condition and both branches, which is what you need here.

A: If you can make your type an instance of Monad, even with a missing return then the do notation works.  I've done it (e.g.BASIC), and it's an excellent way to get imperative notation for a DSL.

A: Well, the sort of structure you're working with does already exist; a relevant type class can be found on Hackage, in fact. I don't recommend trying to force it into an instance of Monad, though, for the reasons that bdonlan gives. The existence of return is pretty fundamental and you're likely to run into trouble everywhere trying to use standard functions for Monads.
....however! That said, if you really want do notation, consider this quote from the GHC user guide:

"Do" notation is translated using whatever functions (>>=), (>>), and fail, are in scope (not the Prelude versions).

...in other words, you're right that using do notation makes sense, because nowhere does it actually use return when desugared. That section is about the RebindableSyntax extension, which does exactly what it claims. If you don't mind giving up do notation for Monad, you can use that extension, define your own functions, and use do notation all you like.


text:
Q: how to get the first element of a list in laravel? My problem is not difficult :) i use Laravel 4, and i just want to get the first element of my list, my code is :
public function index()
{
    $userid = User::lists('id'); // here i want to get the first element of my list
    $services = User::find($userid)->service;
    $username = User::lists('username');

    return View::make('services.index',array('services'=> $services,'username'=>$username));
}

so if someone has any idea i will be very appreciative :)

A: Within Laravel, the 'lists' method returns an array. So, you may simply access the first object in the array by using something like:
$userid[0] = $firstUserId;

A: If you don't need the list but just the first item:
$user = User::first();

$userid = $user->id
$services = $user->service;
$username = $user->username;

A: Get first item/instance
$user = User::first();
//or
$user = User::find(1); //by id
//or
$user = User::findOrFail(1); //it will throw an error

$user_id = $user->id;
$service = $user->service;
$username = $user->username;


text:
Q: Background image not showing CSS/PHP The background image is not showing. I must be missing something but going a bit cross-eyed trying to work out what it is.
This is what I have:

<?php echo $slide['slide_title']; ?>

    <?php echo $slide[ 'slide_desc']; ?>

  <img style="background-image:url(<?php echo $slide['slide_image']; ?>)">

And this is the CSS:
.hero_text img {
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;
    height: 600px;
}

A: I think you want to use:
<img src="<?php echo $slide['slide_image']; ?>" />

The img tag is for adding images to HTML.
If you actually want it as a background image, set it on a div:
<div style="background-image:url('<?php echo $slide['slide_image']; ?>')">


text:
Q: Flex DropDownList doesn't select item I have an implementation for a drop-down list. All the values are there, however it doesn't allow the user to select an item with the mouse instead of just with the arrow keys.

    <s:FormItem label="Food:">

        <s:DropDownList id="dropDownList"
                        dataProvider="{foodList.lastResult.Food_Display_Table.Food_Display_Row}"
                        labelField="Display_Name"
                        />
        <s:DropDownList id="TEST">
            <s:dataProvider>
                <mx:ArrayList>
                    <fx:String>Red</fx:String>
                    <fx:String>Orange</fx:String>
                    <fx:String>Yellow</fx:String>
                    <fx:String>Blue</fx:String>
                    <fx:String>Green</fx:String>
                </mx:ArrayList>
            </s:dataProvider>
        </s:DropDownList>
    </s:FormItem>
</s:Form>

The first drop-down list is my actual implementation. The second one is a test. I have the same problem with both drop-down lists.

A: The DropdownList is not supported in the mobile device profile. There are some opensource implementations that add support for this, and they're quite good : https://www.flextras.com/index.cfm?event=ProductHome&productID=21


text:
Q: Handle constructors in Java Springboot framework I am working on the following code where I have two java files A.java and m.java. Code is as follows and I am going into a cycle because of the above code change. I tried to remove the cycle by using @inject for A class object in m.java but it gives me null exception when doing _a.doSomething().
Code is as follows:
A.java
class A {

    A(x,y,z,m){
    /* do the necessary initialization */
    }

    A (x, y, z){
    this(x,y,z,m(new A(x,y,z)))
    }
}

m.java
class m {
    _a
    public m(A a){
     _a = a;
    }

    public void func(){
        _a.doSomething();
    }
}

Please suggest how can I handle such scenario.

A: Cycle is caused by second A constructor. Let's analyze it:
class A {

    A(x,y,z,m){
        /* do the necessary initialization */
    }

    A (x, y, z){
        this(x,y,z,m(new A(x,y,z)))
    }
}

On second constructor, you have three params, and the unique line indicates a call to first constructor, with a new m instance. But the problem is this instance calls second constructor again, so you execute the same again: the unique line calls first constructor, with a new m instance that calls second constructor... and so on. Then, this execution will be interrupted by a java.lang.StackOverflowError exception. I suggest you must only use first constructor and remove the second one.


text:
Q: Exception in calling finder() method I created a method inside StudentLocalServiceImpl like:
public static java.util.List<com.meera.dbservice.model.Student> getStudentByGenderMale() throws SystemException
{
    return StudentUtil.findByGender(1);
}

I am calling this method as StudentLocalServiceImpl.getStudentByGenderMale() inside my portlet, but I am getting an exception. The stack trace is as follows:
com.liferay.portal.kernel.exception.SystemException: org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    at com.liferay.portal.service.persistence.impl.BasePersistenceImpl.processException(BasePersistenceImpl.java:251)
    at com.meera.dbservice.service.persistence.StudentPersistenceImpl.findByGender(StudentPersistenceImpl.java:250)
    at com.meera.dbservice.service.persistence.StudentPersistenceImpl.findByGender(StudentPersistenceImpl.java:121)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:320)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at com.liferay.portal.dao.shard.advice.ShardPersistenceAdvice.invoke(ShardPersistenceAdvice.java:54)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy920.findByGender(Unknown Source)
    at com.meera.dbservice.service.persistence.StudentUtil.findByGender(StudentUtil.java:122)
    at com.meera.dbservice.service.impl.StudentLocalServiceImpl.getStudentByGenderMale(StudentLocalServiceImpl.java:37)
    at com.meera.liferaymvc.StudentMVCPortletAction.addStudent(StudentMVCPortletAction.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.liferay.portal.kernel.portlet.LiferayPortlet.callActionMethod(LiferayPortlet.java:148)
    at com.liferay.util.bridges.mvc.MVCPortlet.callActionMethod(MVCPortlet.java:247)
    at com.liferay.portal.kernel.portlet.LiferayPortlet.processAction(LiferayPortlet.java:78)
    at com.liferay.util.bridges.mvc.MVCPortlet.processAction(MVCPortlet.java:210)
    at com.liferay.portlet.FilterChainImpl.doFilter(FilterChainImpl.java:71)
    at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:48)
    at com.liferay.portal.kernel.servlet.PortletServlet.service(PortletServlet.java:112)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:116)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:96)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:605)
    at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:544)
    at com.liferay.portlet.InvokerPortletImpl.invoke(InvokerPortletImpl.java:583)
    at com.liferay.portlet.InvokerPortletImpl.invokeAction(InvokerPortletImpl.java:628)
    at com.liferay.portlet.InvokerPortletImpl.processAction(InvokerPortletImpl.java:308)
    at com.liferay.portlet.PortletContainerImpl._doProcessAction(PortletContainerImpl.java:402)
    at com.liferay.portlet.PortletContainerImpl.processAction(PortletContainerImpl.java:110)
    at com.liferay.portlet.SecurityPortletContainerWrapper.processAction(SecurityPortletContainerWrapper.java:109)
    at com.liferay.portlet.RestrictPortletContainerWrapper.processAction(RestrictPortletContainerWrapper.java:75)
    at com.liferay.portal.kernel.portlet.PortletContainerUtil.processAction(PortletContainerUtil.java:115)
    at com.liferay.portal.action.LayoutAction.processLayout(LayoutAction.java:378)
    at com.liferay.portal.action.LayoutAction.doExecute(LayoutAction.java:200)
    at com.liferay.portal.action.LayoutAction.execute(LayoutAction.java:95)
    at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
    at com.liferay.portal.struts.PortalRequestProcessor.process(PortalRequestProcessor.java:178)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at com.liferay.portal.servlet.MainServlet.callParentService(MainServlet.java:549)
    at com.liferay.portal.servlet.MainServlet.service(MainServlet.java:526)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:116)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.servlet.filters.secure.SecureFilter.processFilter(SecureFilter.java:293)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.servlet.filters.jsoncontenttype.JSONContentTypeFilter.processFilter(JSONContentTypeFilter.java:42)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:96)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
    at com.liferay.portal.servlet.FriendlyURLServlet.service(FriendlyURLServlet.java:156)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:116)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.servlet.filters.strip.StripFilter.processFilter(StripFilter.java:359)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.servlet.filters.gzip.GZipFilter.processFilter(GZipFilter.java:123)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.servlet.filters.secure.SecureFilter.processFilter(SecureFilter.java:293)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.servlet.filters.i18n.I18nFilter.processFilter(I18nFilter.java:243)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.servlet.filters.jsoncontenttype.JSONContentTypeFilter.processFilter(JSONContentTypeFilter.java:42)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.servlet.filters.autologin.AutoLoginFilter.processFilter(AutoLoginFilter.java:267)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.servlet.filters.sso.ntlm.NtlmPostFilter.processFilter(NtlmPostFilter.java:83)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.sharepoint.SharepointFilter.processFilter(SharepointFilter.java:88)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:169)
    at com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter.processFilter(VirtualHostFilter.java:226)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:59)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:185)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
    at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:738)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:204)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:109)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:165)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:165)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:185)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:96)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run

I also tried to call the method like StudentLocalServiceUtil.getStudentByGenderMale() but then it gives compilation error that the method could not be resolved. How do I call the finder method since we can't call it directly from StudentUtil?

A: I solved it..It might be useful to others also going through same type of problem...I removed the static keyword as Parkash and KLajdPaja mentioned and called the method as StudentLocalServiceUtil.getStudentByGenderMale().Error gone...


text:
Q: Can we verify a method is called on one of the several objects using Mockito I have a list of Object
List<MyClass> list = <an array of MyClass instances>

The MyClass class contains a method invokeMe();
Is there any way I can verify that the invokeMe method is called on one and only one of these MyClass instances in the list using Mockito?
Any of these classes could be called as they are accessed by different threads.v

A: Assuming I correctly understood your question you can do this as follows:
(...)

@Mock
MyClass mock1;

@Mock
MyClass mock2;

@Mock
MyClass mock3;

private List<MyClass> list = Arrays.asList(mock1, mock2, mock3);

(...)

@Test
public void whatever() {
  (...)

  verify(this.mock1, times(1)).invokeMe();
  verify(this.mock2, never()).invokeMe();
  verify(this.mock3, never()).invokeMe();
}


text: Q: How to check with Linux the duration on battery since last full charge? On laptop running Linux Debian based, how to check ,or get, the whole duration running on battery since the last full charge? Easy to get the time remaining or battery level, but the total duration on battery since last charge is what I wish to know. In comparison, on Android device, we get the value in battery stats "Last full charge" picture attached. Thanks in advance.


text:
Q: Error in R dataframe: first column translated I've a problem loading a data frame:
I've, shortly, 3 variables: Country, Capital, Population.
When I use
data=read.csv(file="data.csv", head=T, sep=",")

or
data=read.csv(file="data.csv")

I obtain
that
the names of the columns are translated, like first column is a row names.
How I can fix that?


text:
Q: substring pandas column between the same character I have a pandas dataframe with the following column value:
data - test - data

I need to create the new column which includes string between '-'
test

I've tried:
df['column'] = df['column2'].apply(lambda st: st[st.find("-"):st.find("-")])

but it returns null (this is the same character and code treat it as the same character).

A: You can use split and take the first index in the list that is returned.
df['column'] = df['column2'].apply(lambda s: s.split('-')[1].strip())


text:
Q: Error 'unable to connect to the remote server' when accessing Azure MSI IMDS endpoint in App Service I have enabled the Managed Service Endpoint for the App Service and I am able to see the MSI_ENDPOINT and the MSI_SECRET injected into the environment. am able to get the azure AD access token also when invoking the MSI_ENDPoint.
But as per the Azure documentation, we have to use the IMDS endpoint going forward.
When accessing the URL http://169.254.169.254/metadata/identity/oauth2/token properly with api-version and the metadata via PowerShell, I am getting an error that unable to connect to the remote server though I am able to get access token from the same PowerShell instance when hitting the MSI_Endpoint which is http://localhost:XXXX/MSI/token where XXXX is the port number.

A: IMDS (Instance Metadata Service) is only available for Azure Virtual Machine and Virtual Machine Scale Set resources. You won't be able to call IMDS from within an App Service. The documentation to migrate from localhost:xxxx to IMDS is only relevant for Virtual Machine and Virtual Machine Scale Set resources.
Here are the docs specific to App Services. Note that MSI_ENDPOINT is used here.


text:
Q: python system to dynamically load variables and modules i am trying to build an infrastructure which uses a text file to dynamically setup an environment in which code should run. the text file will contain paths of python modules to load AND variables which other parts of my code will need.  thus, i am trying to use one mechanism for loading modules and variables (versus virtualenv just for modules and another scheme for variables)
my code would look like:
my_script_which_uses_env.py:
import envcontrol_module
import some_other_module_whose_path_is_unknown_at_run_time

def main():
     my_envcontrol = envcontrol_module.EnvControlClass()
     my_variable = my_envcontrol.get_value("SOME_VARIABLE")

those using my infrastructure would be required to "import envcontrol_module" as the first line in their code.  after that import is done, then the syspath has already been modified to include the paths of the modules to load, ie when import envcontrol_module returns, the sys path has the path for some_other_module_whose_path_is_unknown_at_run_time.
at a high level, i think the following is needed:
1. need "import envcontrol_module" to cause a reading of my config text file.  this would create a dict with the variable names and values. here i could modify sys.path
2. somehow keep this dict around such that when an instance of EnvControlClass is created, this class is able to access the dict
envcontrol_module.py
def main():
    config_dict = read_config_file()
    modify_sys_path(config_dict)

class EnvControl():
    self.config_dict = config_dict

how can i do the above in a python friendly way:
1. config dict is not global to envcontrol_module
2. maintain the need for this to be transparent to programmers, they simply do "import envcontrol_module" first and then do subsequent imports normally
i know i can do the following, but then the programmers would do the imports in their main() rather than at top of file, which will be different/not as nice/not python-esque:
my_script_which_uses_env.py:
import envcontrol_module

def main():
    my_envcontrol = envcontrol_module.EnvControlClass()
    import some_other_module_whose_path_is_unknown_at_run_time
    my_variable = my_envcontrol.get_value("SOME_VARIABLE")

envcontrol_module.py
class EnvControl():
    def __init__(self):
    self.config_dict = read_config_file()
    modify_sys_path(config_dict)

not sure if i explained this well.  if i haven't, let me know and i can clarify more.
thanks!


text:
Q: Disable Contact Form 7 form submit I'm using a contact form for my WP website. I want to call some function before I submit the form.
I thought I could disable the submit form by using the following code:
let form = document.querySelector('form');
form.addEventListener('submit', function(ev){
    ev.preventDefault();
    //some more functions
});

For some reason this isn't working and CF7 is still submiting my form.
Does someone know how to prevent the submit function.
I don't want to use the disabled function on the button cause this way the form loses it's orignal function.

A: I tried it on my page and had the same problem.
Try it with input[type=submit] instead of form.
let form = document.querySelector('input[type=submit]');
form.addEventListener('click', function(e) {
    e.preventDefault();
})

Edit:
This would work if you only use 1 form in your HTML:
window.addEventListener('submit', function(e) {
    e.preventDefault();
}, true)

A: Option is to block 'clicking' on the submit input. So not 100% what you needed, but for me it does the job.
Not sure if that is not against your condition to avoid 'disabled function on the button' but for me the form keeps the original function, just depends on user decision.

var submit = document.getElementsByClassName('wpcf7-submit')[0];

submit.addEventListener('click', function(e) {
  var confirmMessage = 'If you require a response, please make sure you have completed the 'Name' and 'Email' fields.';

  if (!confirm(confirmMessage)) {
    e.preventDefault();
  }
});
<form method="post" class="wpcf7-form" enctype="multipart/form-data" novalidate="novalidate">

 Name

    <input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text" aria-invalid="false">

 Email address

    <input type="email" name="your-email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-email" aria-invalid="false">

<input type="submit" value="Send" class="wpcf7-form-control wpcf7-submit">

</form>

A: Quickfix, should be refactored by extending this js. As UX i've added a GIF image instead of the button after first submit click.
For anyone who haven't found a solution in contact-form-7/includes/js/scripts.js search for line 499 now, probably changing meantime, you have wpcf7.clearResponse, inside in this function add :
var str = '';

$('.wpcf7-submit').replaceWith(str);

This will replace your button after click with the image with path path_of_file.


text:
Q: Setting up VirtualHost for MAMP server? Problem
I need to setup some VirtualHost records for a MAMP server I have installed on my Mac. In short, rather than using http://localhost:8888/dkbtherapy/index.html I want to use http://l.dkbtherapy.com. However, with the configuration I've done it doesn't work.
VirtualHost Configuration
In the /Applications/MAMP/conf/Apache folder I modified the httpd.conf file an added this VirtualHost configuration:
<VirtualHost *:8888>
  DocumentRoot /Applications/MAMP/htdocs/dkbtherapy
  ServerName l.dkbtherapy.com
</VirtualHost>

so that should setup the routing for it (I thought). Then I modified my hosts file and added this:
127.0.0.1:8888  l.dkbtherapy.com

but when I type in l.dkbtherapy.com into Safari I get:

Safari can't find the server.

Now, I rebooted the Apache server after making the changes, but I haven't rebooted my Mac. Though I don't think I need to reboot my Mac. What did I miss in the above configuration?
NOTE: after making the changes http://localhost:8888/dkbtherapy/index.html doesn't work now either, I get a 404 returned with this message:

The requested URL /dkbtherapy/index.php was not found on this server.

EDIT: after looking at my Windows box, where I've configured this and it's working, I noticed I missed a line of configuration -it appeared -so I added this to the one on the Mac too:
NameVirtualHost *:8888

EDIT RELATING TO http://localhost:8888/dkbtherapy/index.html: when I look at the error log for Apache I see this error when I try and navigate to that path:

[Fri May 31 11:23:41 2013] [error] [client ::1] File does not exist: /Applications/MAMP/htdocs/dkbtherapy/dkbtherapy

so for some reason it thinks that dkbtherapy is the absolute root for the server it appears -how did I manage that?

A: Well, you've defined /Applications/MAMP/htdocs/dkbtherapy as the DocumentRoot for the virtual host, which means that that directory maps to the URL 127.0.0.1:8888/ -- so when you visit 127.0.0.1:8888/dkbtherapy/index.html, Apache maps that to /Applications/MAMP/htdocs/dkbtherapy/dkbtherapy/index.html, which doesn't exist, thus the error you see in the log.
You have two options. One is to change the DocumentRoot value to /Applications/MAMP/htdocs/, which will cause the .../dkbtherapy URL to point where you want it to.
The other option, and in my opinion the preferable one, would be simply to strip /dkbtherapy off your URL, and visit e.g. http://127.0.0.1:8888/index.html instead. (I say that's preferable because it seems likely the site, when in production, will have its own domain name, and its URLs won't need to contain /dkbtherapy/. If that's the case, and given that it's always preferable for the development environment to be as close to identical with the production environment as possible, then the second option comes closer to producing that result, and is therefore better than the first.)
One other note regarding your /etc/hosts file: you cannot specify a port number in that file, only an IP address. The "Host not found" error occurs because the TCP stack is unable to parse the entry, and therefore ignores it. The following will work:
127.0.0.1      l.dkbtherapy.com

With that change in place, as well as the previously described change to the DocumentRoot, http://l.dkbtherapy.com:8888 should reach the index page of your site.
(Also, you probably don't need the NameVirtualHost line unless you're actually using name-based virtual hosting, which doesn't sound like it's the case right now. It probably won't hurt anything to leave it there until you get around to actually setting up name-based virtual hosts, but removing it shouldn't make a difference to how Apache is behaving, either.)

A: For those who will land on this page in future :
The first step in removing :8888 from your URLs is editing /Applications/MAMP/conf/apache/httpd.conf & changing the Listen directive to Listen 80.
To set up VirtualHost, still in that same file above, search for Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf, make sure that it's not commented out i.e. remove the # in front of it if any. Then go to the file /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf to set up your virtual hosts.


text:
Q: How to hide the content that's outside the parent div with aside? I have the following snippet:

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>

                One

                Two

There is a parent div with fixed width (w-32) and a child aside that is double the width of the parent. So I want only one half, the one that's inside the area of the parent div to be shown
How can I do that?

A: If you are planning to toggle between those two-child div, You can do something like this.

*

*Make one div to display none.

*and make another one to display block(I used active class).

*set main parent div(h-screen) to overflow-hidden.

*and toggle between active class on click.

$(document).ready(function () {
  $(".h-screen aside div").click(function(){
    $(".h-screen aside div").toggleClass("active");
  });
});
.h-screen{
  overflow:hidden;
}
aside div {display:none}
aside div.active {display:block}
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>

                One

                Two

A: So you can just simple add style to toggle you want hide at this moment :
sample code:
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>

                One

                Two

Just added :style="display:none;" inside ONE - in result the only Two is visible :) You can do that in both ways ofc.
and resul looks like :

@EDIT 1 :
HTML code:
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>

                One

                Two

CSS code:
.two {

  background: red;
    width: 50%;
    float: right;
    height: 250px;
    position: absoulte;
}

.one {

  background: blue;
  width: 50%;
  float: left;
  height: 250px;
  position: absoulte;
}

JS code to show and hide ONE and TWO
let subsWrapper = document.getElementById("one");
subsWrapper.remove();
document.getElementById("element_id").remove();


text:
Q: How to extract state from an array of struct views? SwiftUI I'm having an issue grabbing the state out of an array of SwiftUI structs.
I have a struct for cards that contain topText and bottomText. I have another struct that is a form for input components such as the card. I store these cards in an array, appending more and more as a + button is clicked. In the parent view I have a foreach over that array so they render dynamically.
I'm having an issue with trying to extract the state value from these structs. The cards contain state for the topText and bottomText. When a save button is clicked in the parent array (where the array of cards exists), it iterates over the array of cards, and prints their state through a get method. However, it is not printing the current state of those cards. It prints a blank string. I believe this is happening because when I append the struct, it's merely copying a dead struct, and not the real stateful struct.
Do I have my assumptions correct? Or is this a bug in swiftUI? Does anyone have any ideas on a proper way to do this? I just want to get the input out of the cards whenever the button is clicked. It needs to be dynamic though, as the user can click the + button however many times they want and continue making more cards.
Heres the code for the card stuct:
struct memeCard: View, Identifiable{
    @State private var topText = ""
    @State private var bottomText = ""

    let id = UUID()

    //  TODO: figure out how to make text wrap so it doesn't go on one line forever.

    var body: some View{
        VStack(spacing: 30){
            TextField("Top text...", text: $topText).multilineTextAlignment(.center)
            Divider()
            TextField("Bottom text...", text: $bottomText)
        }
        .frame(width: 300, height: 350, alignment: .center).multilineTextAlignment(.center)
        .background(Color.white)
        .cornerRadius(20)
        .shadow(color: Color.gray, radius: 4, x: 4, y: 4)
    }

    func getBottomText() -> String{
        return self.bottomText
    }

    func getTopText() -> String{
        return self.topText
    }
}

And here is the parent view:

struct CreateMemePage: View {
    @Environment(\.presentationMode) var presentation

    let realm = try! Realm()
    @State private var sectionInput = ""
    @State private var memeTitleInput = ""
    @State private var offsetValue: CGFloat = 0.0
    @State private var createCards: [memeCard] = [memeCard()]

    var body: some View {

NavigationView{
            VStack(spacing: 30){
                ScrollView{
                    TextField("Section...", text: $sectionInput)
                        .multilineTextAlignment(.center)
                        .frame(width: 350, height: 75, alignment: .center)
                        .background(Color.white)
                        .cornerRadius(15)
                        .shadow(color: Color.gray, radius: 4, x: 4, y: 4)

                    TextField("Meme Title...", text: $memeTitleInput)
                        .multilineTextAlignment(.center)
                        .frame(width: 350, height: 75, alignment: .center)
                        .background(Color.white)
                        .cornerRadius(15)
                        .shadow(color: Color.gray, radius: 4, x: 4, y: 4)

                    ForEach(0..<self.createCards.count, id: \.self){ item in
                        self.createCards[item].padding()
                    }

                    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
                }

                Button(action: {
                    self.createCards.append(memeCard())
                }) {
                    Image(systemName: "plus")
                        .accentColor(Color.white)
                        .frame(width: 50, height: 50, alignment: .center)
                        .background(LinearGradient(gradient: Gradient(colors: [ .red, .purple]), startPoint: .top, endPoint: .trailing))
                        .cornerRadius(60)
                        .shadow(color: Color.gray, radius: 2, x: 3, y: 3)
                }
            }
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
            .keyboardSensible($offsetValue)

            .navigationBarTitle("Create meme")
            .navigationBarItems(trailing:
                Button(action: {

                 for item in createCards{
                     print(item.getBottomText())
                     print(item.getTopText())
              }
                }){
                    Text("Save")
                }
            )        }

    }

}

A: You need to know how to use ObservableObject, @ObservedObject, @State, and @Binding.
But for simplicity, let's take a look how we can make your memeCard functions work.
Creating a model
class Model: ObservableObject {
    var topText: String = ""
    var bottomText: String = ""

    init(top: String, bottom: String) {
        self.topText = top
        self.bottomText = bottom
    }
}

Using a model instance inside memeCard View.
struct memeCard: View, Identifiable{
    @ObservedObject var model = Model(top: "", bottom: "")

    let id = UUID()
    ...

Next, we bind the model instance to the textFields.
VStack(spacing: 30){
    TextField("Top text...", text: self.$model.topText).multilineTextAlignment(.center)
    Divider()
    TextField("Bottom text...", text: self.$model.bottomText)
}

And then we can extract the data from the model class using your existing top and bottom functions, like so:
func getBottomText() -> String{
    print("BOTTOM: \(self.model.bottomText)")
    return self.model.bottomText
}

func getTopText() -> String{
    print("TOP: \(self.model.topText)")
    return self.model.topText
}

Voila! It now should work.
This answer from another question https://stackoverflow.com/a/57623488/3231194
should help you out, it's written comprehensively.


text:
Q: Is MaterialApp/Scaffold absorb my Listener? I try to code a very simple Whiteboard. When I use
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: Container(
                child: Listener(

the app isn't recognizing any mouseclick (onPointerDown()). When I use directly
  Widget build(BuildContext context) {
    return Container(
      child: Listener(

everything is ok and I can see some action in the onPointerDown(). So, I think I miss something. I want to use the MaterialApp, to get access to some of the features.
What I tried so far:
At first, I tried to minimize my function, to focus on only that problem.
So, this is my full minimized code:
import 'package:flutter/material.dart';

void main() {
  runApp(App());
}

class App extends StatefulWidget {
  @override
  AppState createState() => AppState();
}

class AppState extends State<App> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: Container(
                color: Colors.white,
                child: Listener(
                  onPointerDown: (details) {
                    print('Action');
                  },
                  child: CustomPaint(
                    painter: DrawingPainter(),
                  ),
                ))));
  }
}

class DrawingPainter extends CustomPainter {
  DrawingPainter();

  @override
  void paint(Canvas canvas, Size size) {}

  @override
  bool shouldRepaint(DrawingPainter oldDelegate) => true;
}

What I recognized, the size of the DrawingPainter is (0.0, 0.0). Maybe the Problem is that the Painter isn't span about the full size? If this is so, how can I change that? I tried to set the size, but ended with size == 0.0, 0.0 again.

A: Yes, you just have to use a SizedBox.expand or anything that will force your content to expand its size to match parent.
see https://zu4c06ylu4d0.zapp.page/#/


text:
Q: Electron NodeJS spawn error when running certain commands: spawn ENOENT So, I'm trying to use spawn in my Electron application to run the flutter --version command.
This command works perfectly fine on my terminal.
Every solution I've seen implies I don't have it in my process.env.PATH variable. But when I do a console.log( process.env.PATH );, the path to my Flutter command is there.
Here is the current code I'm trying to execute:
const flutterVer = spawn('flutter', ['--version', '/c']);

flutterVer.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

Which returns:
Uncaught Error: spawn flutter ENOENT
    at __node_internal_captureLargerStackTrace (node:internal/errors:464:5)
    at __node_internal_errnoException (node:internal/errors:594:12)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
    at onErrorNT (node:internal/child_process:477:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

I tried testing with another command, like git --version, and that worked perfectly fine.

A: I've found a neat workaround by using exec instead of spawn like so.
const { exec } = require('child_process');

const flutterVer = exec('flutter --version');

flutterVer.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

Will have too look into what the differences are between exec and spawn, but for now, it does what I need.


text:
Q: Can we be nicer to people (new and old) for whom programming is just a job? Continuing in the spirit of being nice (with all the recent pushes to be nicer to new users), I want to share something that I see frequently (I am working to build a list of examples, as per comments below). This is not limited to "new users", which of course has already been discussed to death.
A lot of times we see questions like "I want to connect my application to a database. How do I do this?" These are categorically "too broad" and by no means do they belong here. However, a lot of people (including myself) respond with snark and rudeness in addition to the appropriate close vote.
When I was in high school, I worked as a cook at Boston Market and Pizza Hut. I was cooking food, but by no means was I a chef. If I had asked a true chef, for whom cooking was an art, "I am cooking a pizza, how many pieces of pepperoni do I put on it and what is the precise oven temperature?" he would probably respond with something like "What? You don't understand cooking!" The question is almost incomprehensible to a chef who takes pride in his art form and is used to using instinct, taste, and experience to create; but the question is reasonable when one remembers that it is being asked by a person for whom cooking is just another job.
Similarly, when a person who is programming computers because it is a job asks a broad question without any apparent research effort being done, it could be because they genuinely (and validly) don't view their job as some sort of masterful art form that they are proud of, but rather as just another job (which they care about, it's just that they don't take the same approach), and they're simply looking for a solution that meets their requirements so they can move on. I think this may be a concept that isn't really aligned with the way many of the people who contribute answers here feel about programming.
These questions of course should be closed, but can we please try a little harder to consider where they are coming from and the mindset of the asker instead of being outright rude?
I had a little bit of trouble putting this into words but hopefully the spirit is coming across OK. If anybody here can improve this (especially the title, which I had difficulty with), please do.
Update in light of some answers and comments below:
I think it very easy to direct negativity towards the asker himself, but in some situations the root cause is the way the asker was trained to do his job. I realize that's way beyond anything we can or should be expected to address; but fundamental differences in the programming and training culture that an asker is a part of very much affects the attitude of the asker and how much value they place on finding answers on their own. I don't particularly agree with that culture, but the point is, an asker might not be a "lazy/stupid" person, it could just be how they were taught.
In light of this, another way to state the concerns above is: I suppose Stack Overflow has a heavy (and understandable) bias towards a certain kind of programming culture. However, it also seems that Stack Overflow has an apparent outward desire to be a global-friendly place to go for answers (see e.g. the tone of the recent Portuguese site creation blog post, which reflects a clear desire to be more inclusive). If SO outwardly stated that we only support the specific programming culture preferred by heavy answer contributors, then it would be easier to accept this kind of behavior as the norm; no false advertising. As it stands, it seems like a contradiction to an outward desire for a more tolerant attitude, and I think it will reflect positively on SO as a whole if we can try to at least show understanding (and again, these types of questions do not fit here, but it is not necessary to add a negative comment to the pool of information maintained here).
To openly not appreciate where others are coming from damages (slowly, yes, but also surely) Stack Overflow's efforts to maintain a positive global public image. As members of this community I think it is distinctly our responsibility to make sure that damage does not occur.
I believe this is what differentiates this issue from a basic "be nice to people because hurting feelings is bad" type of request. I do not and never will maintain that we need to be responsible for other people's feelings; but I do strongly maintain that we are responsible for Stack Overflow's overall culture and image.

A: You have a well written question and a state your point well. This is a critique, but not meant in a nasty way - it is simply trying to illustrate the futility of achieving what you want.

"I want to connect my application to a database. How do I do this?"

Let's flip that around a little. What would you say if a junior civil engineer came up to you and asked you how to connect a bridge to land? Would you look at them funny and mention that they should have already learned that? Or that the right way to do it depends on the situation?
Just to be absolutely clear: Stack Overflow intended to be a canonical resource for answers, but it is not a training ground for people learning to code. It's a subtle difference, sometimes there's no difference between those two except for the way the question is presented.

The question is almost incomprehensible to a chef who takes pride in his art form and is used to using instinct, taste, and experience to create;

To get to be an experienced chef, he had to try many things and he would have failed many times. At no time would he have gone to someone and said "Gimme teh pizza'z", then taken them and ran. No, he would have burnt a few, tried a few different things, asked questions along the way, and eventually learned how to do it. This is what good coders do too. There are enough recipes out there telling you exactly how to make and cook a pizza. The same goes for tutorials about connecting your application to a database. If users bothered to read those tutorials we would get a lot fewer questions about database connections.

it could be because they genuinely (and validly) don't view their job as some sort of masterful art form that they are proud of, but rather as just another job

Herein lies part of the problem. You need to flip this one around again. You are an experienced professional, and you are busy. You have your own code to write and your own deadlines and technical challenges to meet. You dedicate some time to Stack Overflow because you enjoy helping and giving back, and your boss (or wife/husband/significant other) is understanding of this. Then someone who has no real skin in the game and can't be bothered reading the thousands of tutorials out there and can't be bothered (or is incapable of) composing a half decent question rocks on up and asks "Halp! I need to connect to my database and show a value in a textbox! Halp this is urgent! It was due yesterday! Lulz!". Sit back and think, exactly what would your reaction be?
I choose not to answer these types of questions. If someone does, then I congratulate them. However lots of people out there don't necessarily have the patience to just turn their back and let someone else deal with it - their reaction will be to communicate to the user that their skillset (or question) needs some improvement (I'm phrasing this in a very polite way). This is a normal part of human behaviour.
Taking this back to your chef example...
if a part time worker for whom it is "just a job" rocked on up and said "Halp! How do you make a souffle? The customer has been waiting three hours and I was out the back smoking and gossiping for the last two of those! Lulz!", how would that chef react? What about the master civil engineer when asked about connecting the bridge to land?
TL;DR:
snarky comments are not helpful or constructive, however you can't stop them, you can merely react to them when they appear - especially when it is in response to ignorant or lazy questions. And we shouldn't encourage or reward lazy and ignorant questions. If someone fails to deliver in their "just a job" then maybe it wasn't the right job for them...

A: I'd like not to generalize, but maybe this happens when people come panicking asking for their code to get fixed.
Theoretically, StackOverflow is a place where you can share knowledge with the community, not a pastebin for outsourcing your problems.
More often than not, you can definitely see the difference between a question asked so it that can be useful to others in the future and one that just wants professional help for free.
Then, certainly it's not fun to come here and find somebody telling you to start from scratch because you are doing it wrong, but sometimes even those comments can be useful, right?


text:
Q: gpg - difference --encrypt-to and --recipient What is the difference between --encrypt-to and --recipient and what are the advantages and disadvantages of using one over the other, which one should you use for encrypting your own files and what does the following mean?

--encrypt-to
  ... The key specified by name is used only
  when there are other recipients given by the user or by use of the
  option recipient. ...

A: What is the difference between --encrypt-to and --recipient?
Summary:

With
  an --encrypt-to key designated in the Options file, GPG
  automatically encrypts messages and files to the public keys of the
  recipients you specify with the --recipient option as well as your
  own public key. The result: both you and your recipients will be able
  to decrypt the files or messages.

Please read the GPG Manual which explains the differences:

--recipient name
-r
Encrypt for user id name. If this option or --hidden-recipient is not
  specified, GnuPG asks for the user-id unless --default-recipient is
  given.

And

--encrypt-to name
Same as --recipient but this one is intended for use in the options
  file and may be used with your own user-id as an "encrypt-to-self".
  These keys are only used when there are other recipients given either
  by use of --recipient or by the asked user id. No trust checking is
  performed for these user ids and even disabled keys can be used.

Source Using the GNU Privacy Guard: GPG Key related Options

The documentation is not very detailed/examples may be useful
Here is some more explanation and an example:

"Encrypt-to-Self"
When you encrypt a file or message with the --encrypt command, you
  are encrypting with someone else's public key. Strangely enough, even
  though you encrypted the file or message yourself, you won't be able
  to decrypt that encrypted file and access the plaintext. The only
  person who can decrypt the file is the owner of the secret key that is
  the partner of the public key used to encrypt the file. That's the
  nature of asymmetric, public key encryption: you encrypt with the
  public key and decrypt with the secret key (private key). If you don't
  keep a copy of the plaintext original file yourself (and you probably
  shouldn't for security reasons), then you face being locked out of the
  very files and messages that you have encrypted and sent to other
  people. Happily, there is a solution: the --encrypt-to option.
You can include the --encrypt-to option in your Options file and
  specify your own public key. This option is often called the
  "encrypt-to-self" option, because it tells GPG to encrypt the message
  with your own public key as well as your recipient's public key. With
  an --encrypt-to key designated in the Options file, GPG
  automatically encrypts messages and files to the public keys of the
  recipients you specify with the --recipient option as well as your
  own public key. The result: both you and your recipients will be able
  to decrypt the files or messages.
To use the --encrypt-to option in your Options file, drop the
  leading dashes ( -- ) and specify your own key's Key ID. (You can get
  your own Key ID with the --list-keys command.) For example, Bob (whose
  Key ID is 0x3FAD9F1E) could include the following line in his Options
  file:
encrypt-to 0x3FAD9F1E

(Note that even though Bob's key includes an encryption subkey with a
  separate Key ID, he simply uses the Key ID for his master key.)
Now Bob can encrypt a file to his friend Phil, just as he normally
  would...
D:\TEMP>gpg --recipient Phil --encrypt my-file.txt

D:\TEMP>

...and still turn around and decrypt the file himself.
D:\TEMP>gpg --decrypt my-file.gpg

You need a passphrase to unlock the secret key for
user: "Bob Bone <bobbone@cowtownu.edu>"
2048-bit ELG-E key, ID AB53B492, created 2001-11-13 (main key ID 3FAD9F1E)

Enter passphrase: My_31337_Passphrase

gpg: encrypted with 2048-bit ELG-E key, ID 42F0A0A0, created 1997-04-07
      "Philip R. Zimmermann <prz@pgp.com>"
gpg: encrypted with 2048-bit ELG-E key, ID AB53B492, created 2001-11-13
      "Bob Bone <bobbone@cowtownu.edu>"

This is my file.

I have many such files.

But this is the file I'm working with now.

D:\TEMP>

Source GnuPG Commands - Examples


text:
Q: WHM/Cpanel SSL Certificate on Mail Server I need to have SSL on a client website mail server, so https://mail.domain.com for example.  I purchased a certificate for the primary domain and cPanel does allow for this to cover all subdomains, but the certificate itself is limited to just the primary domain.
I would prefer not to have to purchase an expensive wildcard SSL, is there a way to put a second SSL certificate on just mail.domain.com?  cPanel does not have the mail subdomain as a possibility in the dropdown for SSl certificates.
I assume maybe I would have to create a subdomain or something...not sure if anyone else has done this.

A: Well in this case you should regenerate the CSR certificate and re-issue the SSL. Most of the SSL certificates, even the cheapest ones allow you to use the SSL for the main domain + 1 subdomain, in your case mail. So go to cPanel, regenerate your CSR certificate and in the hosts field add domain.tld + mail.domain.tld on the next line. Then with the new CSR, go to your SSL provider and try to issue a new SSL certificate using your new CSR. Then the new generated SSL should cover your domain + mail.domain. And you should be all set. Even the really cheap SSL certificates from SSL2Buy can be used for domain + 1 subdomain (and they are about 9$/year for a COMODO simple SSL certificate). So give it a try

A: If you are using shared account they will offer you free ssl certificate which you can generate from Cpanel and if you are using wordpress framework for your website you can install ssl plugin there and can activate ssl on your website.


text:
Q: Glide slide breakpoints has no effect I built several slides in the same page with Glidejs:
import Glide, { Controls, Autoplay, Keyboard } from '@glidejs/glide/dist/glide.modular.esm';

let slides = document.getElementsByClassName('g-related');

for (const c of slides) {
  let gid = '#' + c.id;
  let dur = Math.floor((Math.random() * 10000) + 1000);

  new Glide(gid, {
    type: 'carousel',
    autoplay: 10,
    animationDuration: dur,
    animationTimingFunc: 'linear',
    hoverpause: true,
    perView: 5,
    breakpoints: {
      1024: {
        perView: 4,
      },
      600: {
        perView: 3,
      },
    },
  }).mount({ Autoplay })
}

And I use breakpoins as said in docs. All the slides work, but the breakpoints don't work. Why? (hoverpause doesn't work neither).
Aditional info (code in context)
JS:
https://github.com/aitormendez/futurabasura/blob/main/web/app/themes/fb/resources/scripts/singleProduct.js#L47-L67
HTML:
https://github.com/aitormendez/futurabasura/blob/main/web/app/themes/fb/resources/views/woocommerce/single-product/related.blade.php#L62-L73
Working example in staging server (scroll to bottom):
http://fb.e451.net/shop/ill-e-t/

A: I forgot import Breakpoints from ESM modules:
import Glide, { Controls, Autoplay, Keyboard, Breakpoints } from '@glidejs/glide/dist/glide.modular.esm';

Then:
mount({ Autoplay, Breakpoints })


text:
Q: Rollback issue with Neo4j I am following this tutorial but have modified the POM.xml to use version 3.1.0.RELEASE of Spring Data Neo4j. I am experiencing a problem where the graph database does not seem to be instantiated correctly. The only code modification I did from the tutorial code was to replace the deprecated EmbeddedGraphDatabase API with the GraphDatabaseService API in Application.java. Any help would be appreciated.
UPDATE
This issue with the EmbdeedGraphDatabase is fixed. Now the issue is with rollback a transaction.
Application.java
package com.me.nosql.neo4j.hello;

import java.io.File;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.impl.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Transactional;

@Configuration
@EnableNeo4jRepositories
@EnableAutoConfiguration
@ComponentScan
public class Application extends Neo4jConfiguration implements CommandLineRunner {

    @Autowired
    PersonRepository personRepository;

    public Application() {
        setBasePackage("com/me/nosql/neo4j/hello");
    }

    @Bean(destroyMethod = "shutdown")
    public GraphDatabaseService graphDatabaseService() {
        return new GraphDatabaseFactory().newEmbeddedDatabase("accessingdataneo4j.db");
    }

    public void run(String... args) throws Exception {

        Person greg = new Person("Greg");
        Person roy = new Person("Roy");
        Person craig = new Person("Craig");

        System.out.println("Before linking up with Neo4j...");
        for (Person person : new Person[]{greg, roy, craig}) {
            System.out.println(person);
        }

        try (Transaction tx = graphDatabaseService().beginTx()) {
            personRepository.save(greg);
            personRepository.save(roy);
            personRepository.save(craig);

            greg = personRepository.findByName(greg.name);
            greg.worksWith(roy);
            greg.worksWith(craig);
            personRepository.save(greg);

            roy = personRepository.findByName(roy.name);
            roy.worksWith(craig);
            // We already know that roy works with greg
            personRepository.save(roy);

            // We already know craig works with roy and greg

            tx.success();
        }

        System.out.println("Lookup each person by name...");
        for (String name : new String[]{greg.name, roy.name, craig.name}) {
            System.out.println(personRepository.findByName(name));
        }

        System.out.println("Looking up who works with Greg...");
        for (Person person : personRepository.findByTeammatesName("Greg")) {
            System.out.println(person.name + " works with Greg.");
        }
    }

    public static void main(String[] args) throws Exception {
        FileUtils.deleteRecursively(new File("accessingdataneo4j.db"));
        SpringApplication.run(Application.class, args);
    }

}

Error Message
Exception in thread "main" java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.runCommandLineRunners(SpringApplication.java:637)
    at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:652)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:898)
    at com.me.nosql.neo4j.hello.Application.main(Application.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: org.neo4j.graphdb.TransactionFailureException: Failed to mark transaction as rollback only.
    at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly(TopLevelTransaction.java:97)
    at org.neo4j.kernel.TopLevelTransaction.failure(TopLevelTransaction.java:86)
    at org.neo4j.cypher.internal.spi.v2_0.TransactionBoundQueryContext.close(TransactionBoundQueryContext.scala:59)
    at org.neo4j.cypher.internal.compiler.v2_0.spi.DelegatingQueryContext.close(DelegatingQueryContext.scala:33)
    at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext.org$neo4j$cypher$internal$compiler$v2_0$spi$ExceptionTranslatingQueryContext$$super$close(ExceptionTranslatingQueryContext.scala:34)
    at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply$mcV$sp(ExceptionTranslatingQueryContext.scala:34)
    at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply(ExceptionTranslatingQueryContext.scala:34)
    at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply(ExceptionTranslatingQueryContext.scala:34)
    at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext.org$neo4j$cypher$internal$compiler$v2_0$spi$ExceptionTranslatingQueryContext$$translateException(ExceptionTranslatingQueryContext.scala:149)
    at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext.close(ExceptionTranslatingQueryContext.scala:34)
    at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator$$anonfun$close$1.apply$mcV$sp(ClosingIterator.scala:65)
    at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator$$anonfun$close$1.apply(ClosingIterator.scala:63)
    at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator$$anonfun$close$1.apply(ClosingIterator.scala:63)
    at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator.translateException(ClosingIterator.scala:70)
    at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator.close(ClosingIterator.scala:62)
    at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator.failIfThrows(ClosingIterator.scala:92)
    at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator.hasNext(ClosingIterator.scala:34)
    at org.neo4j.cypher.internal.compiler.v2_0.PipeExecutionResult.hasNext(PipeExecutionResult.scala:166)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
    at scala.collection.convert.Wrappers$IteratorWrapper.hasNext(Wrappers.scala:29)
    at org.neo4j.cypher.internal.compiler.v2_0.PipeExecutionResult$$anon$1.hasNext(PipeExecutionResult.scala:74)
    at org.neo4j.helpers.collection.IteratorWrapper.hasNext(IteratorWrapper.java:42)
    at com.me.nosql.neo4j.hello.Application.run(Application.java:77)
    at org.springframework.boot.SpringApplication.runCommandLineRunners(SpringApplication.java:634)
    ... 10 more
Caused by: java.lang.NullPointerException
    at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly(TopLevelTransaction.java:93)
    ... 33 more

A: I faced the similar problem and found the hint for the solution here (http://spring.io/guides/gs/accessing-neo4j-data-rest/).
I needed to add the constructor like this:
public Application() {
    setBasePackage("name/of/the/base/package");
}

The example ran, created the db and performed queries, all except the last ("Looking up who works with Greg..."). The error was:
Caused by: org.neo4j.graphdb.TransactionFailureException: Failed to mark transaction as rollback only.

I managed to resolve this by wrapping the call in the transaction, just like that:
    Transaction tx = graphDatabase.beginTx();
    try {
        //Do all the work
        tx.success();
    } finally {
        tx.close();
    }

After then, everything worked fine for me.
EDIT: In order to make all transactions persist in DB I changed the following lines to
    try (Transaction tx = graphDatabase().beginTx()) {
        System.out.println("Lookup each person by name...");
        for (String name : new String[]{greg.name, roy.name, craig.name}) {
            System.out.println(personRepository.findByName(name));
        }
        tx.success();
    }

    try (Transaction tx = graphDatabase().beginTx()) {
        System.out.println("Looking up who works with Greg...");
        for (PersonJ person : personRepository.findByTeammatesName("Greg")) {
            System.out.println(person.name + " works with Greg.");
        }
        tx.success();
    }

A: Few things you would like to check :

*

*new GraphDatabaseFactory().newEmbeddedDatabase( "accessingdataneo4j.db" ); Check if the path to the db is correct . Try with an absolute address.

*Check if you aren't running the GraphDb instance somewhere else.

A: Remove this:
@Autowired
GraphDatabase graphDatabase;

And use the bean-method instead:
graphDatabaseService()
// or
graphDatabase()

Try to use CommandlineRunner as a bean and inject the dependency there. Spring doesn't inject beans that are declared in this configuration into the same config instance.


text:
Q: How can I tell if a function is a monotonic transformation? In my Economics class, we are talking about monotonic transformations of ordered sets.  But I don't understand how I can tell if a given function will preserve the order.
My Question
What determines whether a function is monotonic and how do I show it is?
Also, if someone could help me understand what the difference is between a function and transformation that would be great because I think I am misusing terminology.

A: If $A$ and $B$ are partially ordered sets with orders $\leq_{A}$
and $\leq_{B}$, a monotone function $f\colon A\rightarrow B$
satisfies the following: whenever $x,y\in A$ with $x\leq_{A}y$, we have $f\left(x\right)\leq_{B}f\left(y\right)$.
For example, if $A=B=\left[0,\infty\right)$ with the usual order
on the real line, then $x\mapsto x^{2}$ is a monotone function. Can
you use the above definition to show that this is true?


text:
Q: Creating memorization algorithm given a fibonacci recursive function For a school assignment, we have to create a memorized fibonacci function that reuses the recursive implementation of computing the fibonacci.
What is a good way to design our memorized function such that it takes advantage of an already existing function? This is my implementation so far:
Base class:
    public int computeFibonacci(int position) {
        assertPosition(position);

        if (position < 2) {
            return 1;
        }
        return computeFibonacci(position - 1) + computeFibonacci(position - 2);
    }

Inherited class:
    public int computeFibonacci(int position) {
        assertPosition(position);

        if (position < 2) {
            return 1;
        }

        if (this.memoizedList.containsKey(position)) {
            return this.memoizedList.get(position);
        }
        int result = super.computeFibonacci(position - 1) + super.computeFibonacci(position - 2);
        this.memoizedList.put(position, result);
        return result;
    }

A: There is a confusion about reusing the recursive implementation in Base Class.
If you call the recursive implementation, it will recursively calculate fib(n) = fib(n-1) + fib(n-2) = ..., which is conflict with memo function. Memo function tries to save time for calculated ones.
For memo:
public int computeFibonacci(int position) {
        assertPosition(position);

        if (position < 2) {
            return 1;
        }

        if (this.memoizedList.containsKey(position)) {
            return this.memoizedList.get(position);
        }
        int result = computeFibonacci(position - 1) + computeFibonacci(position - 2);
        this.memoizedList.put(position, result);
        return result;
    }

For example, you try to print the first 1000 elements in fibonacci, memo function will save time on calculated ones.

A: Your sub-class version doesn't take full advantage of the cached values. For example, if you call computeFibonacci(5), and memoizedList doesn't contain that key, you would call super.computeFibonacci(4) and super.computeFibonacci(3) even if they are already cached. Instead, you should call super.computeFibonacci(5).
public int computeFibonacci(int position) {
    assertPosition(position);

    if (position < 2) {
        return 1;
    }

    if (this.memoizedList.containsKey(position)) {
        return this.memoizedList.get(position);
    } else {
        int result = super.computeFibonacci(position);
        this.memoizedList.put(position, result);
        return result;
    }
}


text:
Q: Prove that perpendiculars from D,E,F to BC,CA,AB are concurrent? Question -
If ABC and DEF be any two triangles such that the perpendiculars from the points A,B,C to the sides EF,FD,DE respectively, are concurrent. Prove that the perpendiculars from D,E,F to BC,CA,AB respectively are also concurrent.
My attempt -
First of all I know this question has already been answered but there they used carnots theorem and some other things which I haven't learn yet...
I am not able to figure it out using ceva theorem...I draw two triangles forming STAR  ...but did not get anything worth..then I draw both triangle on same plane but then things become very confusing...
I want some hint or how to draw correctly this thing...
Thankyou

A: Let $AA_1,$ $BB_1$, $CC_1,$ $DD_1$, $EE_1$ and $FF_1$ be our perpendiculars.
Thus, $$\measuredangle(AA_1,AC)=\measuredangle(EE_1,FE),$$
$$\measuredangle(AA_1,AB)=\measuredangle(FF_1,FE),$$
$$\measuredangle(FF_1,FD)=\measuredangle(BB_1,AB),$$
$$\measuredangle(BB_1,BC)=\measuredangle(DD_1,FD),$$
$$\measuredangle(DD_1,DE)=\measuredangle(CC_1,BC)$$ and
$$\measuredangle(CC_1,AC)=\measuredangle(EE_1,DE).$$
Thus, our statement follows from the Ceva's theorem in the trigonometric form.

A: This is not the answer to your question. This is the depicture of your problem description, which you had trouble in drawing. I hope this will help you to find an appropriate answer.


text:
Q: How to access RSA private key at start of an app? I want to have a RSA pair key (private and public key) saved before running so i can send my encrypted message(with public key) and when server gives me a result back, decrypt it using private key.
Obviously i want my private key to be safe from any vulnerability such as exposure. I don't want to generate/store it in Run Time(like using keystore). It should exists with application package.
bottom line  i don't want to generate RSA key pairs each time i run my app, because i want to put those in my server too and i want a secure way to store them(there are some ways to extract things.

A: I do not recommend to embed a RSA encryption/decryption keypair in your app because:

*

*If the key is compromised then the security of your system is affected completely and you will need to distribute a new app to all your users

*The ciphertext size is limited by the key length
To encrypt/decrypt messages between client and server you just need to use a TLS channel (https).


text:
Q: Azure AD multitenant permissions I have an Azure webapp that's managing it's users via Azure AD. I want the users to be able to register in my Azure AD directory to create an account (self-service), so I gave the app read-write access to the directory and setup a page using the Graph API to create the users.
Until here, everything is great. But the problem I have now is that I want to enable multi tenancy, so users of external AD directories can login to my app. This works, but I need to login as an administrator for the account because it also asks read-write access to their directory.
Is there a way to fix this? I only want read-write access to my directory to be able to create user accounts. I don't want to ask permission to touch their directory because, most probably, they wouldn't trust my app.
Thanks.

A: I found a quick and dirty solution: Add another app to the Active Directory. This app should be single tenant and have only permission to read and write the active directory. We can the use this app's credentials to access the Graph API and the other app's credentials to authenticate users.
I wait to see if someone has a better solution for this scenario...

A: sorry for the late response here.  In general, an operation to create objects in a directory (like users) requires admin permissions.  Also it looks like the web app you are creating uses app-only permissions, which definitely requires admin consent.  In the multi-tenant case, the admin of the consenting tenant must be the one to consent to this type of app - only someone in this role really has the authority to grant consent for this level of access.
Hope the helps,

A: No need to use a secondary app in lieu of the authentication role - - there may be some peculiar side effects on the authenticating user anyway such as extraneous / incomplete logging, role inconsistencies, and missing system / internal references.
What are you using for login credentials for your app (TenantID etc.)?
AD is very strict in credential management, so I would go back to the app structure.
At the query level, you could make all tables entirely separate per tenant with no shared table data and include a multitenant identifier column so no one can sql inject if you were sure to include the multitenant identifier as an explicit variable.
Then in an entity model, you could inherit a multitenant interface for everyone which referred back to the tenant identifiers (as a part of EF).
This way the burden is isolated to OAuth or other libraries on top of that to take care of the third-party authentication.


text:
Q: Rotate single page of document How do I rotate the second page of my PdF when I'm using iText.
The first and other pages I would like to stay in the same orientation.
I know of ...
Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);

But that will rotate everything.

A: From http://itextpdf.com/examples/iia.php?id=232 :
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part4.chapter13;

import java.io.FileOutputStream;
import java.io.IOException;

import part1.chapter03.MovieTemplates;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class RotatePages {

    /** The resulting PDF. */
    public static final String RESULT
        = "results/part4/chapter13/timetable_rotated.pdf";

    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     * @param dest the resulting PDF
     * @throws IOException
     * @throws DocumentException
     */
    public void manipulatePdf(String src, String dest)
        throws IOException, DocumentException {
        PdfReader reader = new PdfReader(MovieTemplates.RESULT);
        int n = reader.getNumberOfPages();
        int rot;
        PdfDictionary pageDict;
        for (int i = 1; i <= n; i++) {
            rot = reader.getPageRotation(i);
            pageDict = reader.getPageN(i);
            pageDict.put(PdfName.ROTATE, new PdfNumber(rot + 90));
        }
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        stamper.close();
        reader.close();
    }

    /**
     * Main method creating the PDF.
     * @param    args    no arguments needed
     * @throws DocumentException
     * @throws IOException
     */
    public static void main(String[] args)
        throws IOException, DocumentException {
        new MovieTemplates().createPdf(MovieTemplates.RESULT);
        new RotatePages().manipulatePdf(MovieTemplates.RESULT, RESULT);
    }
}

A: You can  use document.setPageSize() before document.addNew();.
For example:
Document document = new Document();
....
document.setPageSize(PageSie.A4);
document.newPage();
......

document.setPageSize(PageSize.A4.rotate());
document.newPage();

It worked well for me.

A: I rotate the orientation:
PdfWriter writer = new PdfWriter(out);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf, PageSize.LETTER.rotate());


text:
Q: Least sum of products of powers Numbers from the set $\{2^1, 2^2, ..., 2^{10}\}$ are somehow permuted and paired with numbers from the set $\{3^1, 3^2, ..., 3^{10}\}$. Numbers in each pair are multiplied and the products are summed. What is the least sum you can get?
It seems intuitively obvious that you have to pair least power of 2 with highest power of 3, and second least with second highest and so on. In fact, it looks like this "reversing" method works for any two geometric progressions. I wasn't able to provide a strict proof for either though.
Closest I've gotten to the solution is that when we exchange elements from two pairs, the sum gets higher. I've also tried induction, but then the induction step is not very clear.

A: More generally, if we have $a_1 < a_2 < \dotsc < a_n$ and $b_1 < b_2 < \dots < b_n$, then
$$\min \left\{ \sum_{k=1}^n a_k b_{\sigma(k)} : \sigma \in S_n\right\} = \sum_{k=1}^n a_k b_{n+1-k}.$$
There are only finitely many permutations of $n$ elements, so the minimum is attained for some permutation, and it suffices to show that none of the other permutations attains a minimum. So suppose $\tau$ is a permutation other than $k \mapsto n+1-k$. Then there are $i < j$ with $\tau(i) < \tau(j)$. But then
$$a_ib_{\tau(i)} + a_j b_{\tau(j)} - a_i b_{\tau(j)} - a_j b_{\tau(i)}
= (a_j- a_i)\bigl(b_{\tau(j)} - b_{\tau(i)}) > 0,$$
so the permutation
$$\pi \colon k \mapsto \begin{cases} \tau(j) &, k = i\\ \tau(i) &, k = j\\ \tau(k) &, k \notin \{i,j\}\end{cases}$$
yields a smaller sum than $\tau$.


text:
Q: Ubuntu 14.04 Depends: python (< 2.8) but 3.5.0-1 is installed I have tried to install python3.5 following this instructions.
$ auto-apt run ./configure
$ make
# checkinstall

Actually python3.5 works well. But during installation previous version was replaced.
# apt-get check
The following packages have unmet dependencies:
 apt-xapian-index : Depends: python (< 2.8) but 3.5.0-1 is installed
                    Depends: python:any (>= 2.7.1-0ubuntu2)
 cloud-image-utils : Depends: python:any
 compizconfig-settings-manager : Depends: python (< 2.8) but 3.5.0-1 is installed
                                 Depends: python:any (>= 2.7.1-0ubuntu2)
 duplicity : Depends: python (< 2.8) but 3.5.0-1 is installed
             Depends: python:any (>= 2.7.1-0ubuntu2)
 euca2ools : Depends: python (< 2.8) but 3.5.0-1 is installed
             Depends: python:any (>= 2.7.1-0ubuntu2)
 gconf2 : Depends: python:any
 gimp : Depends: python:any (>= 2.7.1-0ubuntu2)
 hplip : Depends: python (< 2.8) but 3.5.0-1 is installed
 hplip-data : Depends: python:any (>= 2.7.1-0ubuntu2)
 ibus : Depends: python:any (>= 2.7.1-0ubuntu2)
 ibus-pinyin : Depends: python:any (>= 2.7.1-0ubuntu2)
 ...

And lot more.
# apt-get -f install
...
After this operation, 677 MB disk space will be freed.
You are about to do something potentially harmful.
To continue type in the phrase 'Yes, do as I say!'
 ?] _

I had similar issue when I have tried to remove python at all, I still didn't recover all removed packages, so:
Well, I have build and installed python2.7.6 but now I have other issue
# apt-get upgrade | grep 'is installed'
 python-all : Depends: python (= 2.7.5-5ubuntu3) but 2.7.6-1 is installed
 python-all-dev : Depends: python (= 2.7.5-5ubuntu3) but 2.7.6-1 is installed
 python-dev : Depends: python (= 2.7.5-5ubuntu3) but 2.7.6-1 is installed
E: Unmet dependencies. Try using -f.

A: I have downloaded *.deb package for 2.7.5-5ubuntu3 and installed using dpkg instead of apt-get
$ sudo dpkg --install python_2.7.5-5ubuntu3_amd64.deb