How to add control the cache of a restful service operation by operation?

Question: I've written a rest service using WCF. The service contains several operations. Some are GET based ([WebGet]), others are POST based ([WebInvoke]).
The service is working as expected. However, the GET based operations are put in the client cache, which is not desirable for all operations.
After a bit a search, I've found How to prevent the browser from caching WCF JSON responses. This is working, but I found it's not very reusable.
My platform does not allows me to update the web.config. Actually, my service is part of a SharePoint project. and updating the web.config file is hard to implement properly. This forbid me to use the [WebCache] attribute.
So I implemented a custom MessageInspector which fix the proper headers:
public class CacheAttribute : Attribute, IServiceBehavior
{
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase host)
    {
        foreach (ChannelDispatcher cDispatcher in host.ChannelDispatchers)
        {
            foreach (EndpointDispatcher eDispatcher in cDispatcher.Endpoints)
            {
                eDispatcher.DispatchRuntime.MessageInspectors.Add(new CacheInspector(m_CacheEnabled, CacheDuration));
            }
        }
    }
     /*...
        Other code omitted for brievty
     */

}

public class CacheInspector : IDispatchMessageInspector
{
     /*...
        Code omitted for brievety
     */

    public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        var cache = HttpContext.Current.Response.Cache;

        if (m_CacheEnabled)
        {
            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.UtcNow + CacheDuration.Value);

        }
        else
        {
            cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            cache.SetNoStore();
        }

    }
}

This code is working as expected, but it applies to all operations in the service.
How can I code an attribute based class that apply the same logic, but at the operation scope ?
I've tried to find something useful in the IOperationBehavior interface, but I did not find the appropriate implementation.
Full code (.net 4.5):
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public class CacheAttribute : Attribute, IServiceBehavior
{

    private readonly bool m_CacheEnabled;

    public bool CacheEnabled  { get { return m_CacheEnabled; } }

    public TimeSpan? CacheDuration { get; set; }

    public CacheAttribute(bool cacheEnabled)
    {
        this.m_CacheEnabled = cacheEnabled;
    }
    public CacheAttribute(TimeSpan cacheDuration) : this(true)
    {
        this.CacheDuration = cacheDuration;
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase host)
    {
        foreach (ChannelDispatcher cDispatcher in host.ChannelDispatchers)
        {
            foreach (EndpointDispatcher eDispatcher in cDispatcher.Endpoints)
            {
                eDispatcher.DispatchRuntime.MessageInspectors.Add(new CacheInspector(m_CacheEnabled, CacheDuration));
            }
        }
    }

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }

}

public class CacheInspector : IDispatchMessageInspector
{
    private readonly bool m_CacheEnabled;
    private readonly TimeSpan? CacheDuration;

    public CacheInspector(bool m_CacheEnabled, TimeSpan? CacheDuration)
    {
        this.m_CacheEnabled = m_CacheEnabled;
        this.CacheDuration = CacheDuration;
    }
    public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
    {
        return null;
    }

    public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        var cache = HttpContext.Current.Response.Cache;

        if (m_CacheEnabled)
        {
            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.UtcNow + CacheDuration.Value);

        }
        else
        {
            cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            cache.SetNoStore();
        }

    }
}

Answer: I think this is what your are looking for.
[AttributeUsage(AttributeTargets.Method)]
public class CacheAttribute : Attribute, IOperationBehavior, IParameterInspector
{
    public TimeSpan CacheLifetime { get; private set; }

    public CacheAttribute(double lifetime)
    {
        this.CacheLifetime = TimeSpan.FromSeconds(lifetime);
    }

    #region IOperationBehavior Members

    public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) {}

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) {}

    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
        dispatchOperation.ParameterInspectors.Add(this);
    }

    public void Validate(OperationDescription operationDescription) {}

    #endregion

    #region IParameterInspector Members

    public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
    {
        if (this.CacheLifetime == TimeSpan.Zero) {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", "no-cache");
        } else {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", string.Format("max-age={0}",this.CacheLifetime.TotalSeconds));
        }
    }

    public object BeforeCall(string operationName, object[] inputs)
    {
        return null;
    }

    #endregion
}

usage
[ServiceContract]
public interface ICacheTestService
{
    [OperationContract]
    [WebGet(UriTemplate = "CurrentTime")]
    [Cache(0)]
    string GetCurrentTime();

    [OperationContract]
    [WebGet(UriTemplate = "CurrentTimeCached")]
    [Cache(30)]
    string GetCurrentTimeCached();

    [OperationContract]
    [WebGet(UriTemplate = "CurrentTimeNoCC")]
    string GetCurrentTimeNoCC();
}


Root full on UBUNTU 14.04

Question: After installing some operating system updates my root partition is full. I'm a new user of UBUNTU so I'm sure this is an easy fix.
Comment: possible duplicate of [Root drive is running out of disk space. How can I free up space?](http://askubuntu.com/questions/57994/root-drive-is-running-out-of-disk-space-how-can-i-free-up-space)
Comment: ... or is that /boot ?
Answer: First find the directory that has used most of your hard disk space by running
# du -sh /*.
Let assume it is /var dir.
Now you could add additional hard disk & create a brand new partition on it by running
# fdisk /dev/sdb (here it is assumed the newly connected hard disk is /dev/sdb)
Let assume the created partition is /dev/sdb1 and it is formated with ext4 filesystem.
Now, let the system /var dir's mount point is to be that partition

edit the /etc/fstab with your favorite editor (nano or vi)
add the following and save it and reboot to see the effected changes
/dev/sdb1  /var  ext4 default 0 0

Root full on UBUNTU 14.04


Delphi Java Bridge - how to instance a class and call a method on it

Question: I'm trying to use a .jar file in my Delphi project for Android. Unfortunately, there is no information on the Internet talking about this clearly.
I create the Bridge as Embarcadero wrote in their documentation about using Java2OP, and I got the .pas file. All I want to know is, how do I use the interface JPrintUtilClass? I don't know how this file works, or how to use it.
Here is the .pas file:
unit SdkPrint;

interface

uses
  Androidapi.JNIBridge,
  Androidapi.JNI.Bluetooth,
  Androidapi.JNI.GraphicsContentViewText,
  Androidapi.JNI.JavaTypes;

type
// ===== Forward declarations =====

  Jprint_sdk_BuildConfig = interface;//com.example.print_sdk.BuildConfig
  JEscUtils = interface;//com.example.print_sdk.EscUtils
  JEscUtils_1 = interface;//com.example.print_sdk.EscUtils$1
  JSerialManager_OnDataReceiveListener = interface;//com.example.print_sdk.SerialManager$OnDataReceiveListener
  JPrintUtil = interface;//com.example.print_sdk.PrintUtil
  JPrintUtil_1 = interface;//com.example.print_sdk.PrintUtil$1
  JPrintUtil_Singleton = interface;//com.example.print_sdk.PrintUtil$Singleton
  JSerialManager = interface;//com.example.print_sdk.SerialManager
  JSerialManager_1 = interface;//com.example.print_sdk.SerialManager$1
  JSerialManager_ReadThread = interface;//com.example.print_sdk.SerialManager$ReadThread
  JSerialManager_Singleton = interface;//com.example.print_sdk.SerialManager$Singleton
  JALIGN_MODE = interface;//com.example.print_sdk.enums.ALIGN_MODE
  JBARCODE_1D_TYPE = interface;//com.example.print_sdk.enums.BARCODE_1D_TYPE
  JFONT_ID = interface;//com.example.print_sdk.enums.FONT_ID
  JMODE_ENLARGE = interface;//com.example.print_sdk.enums.MODE_ENLARGE
  JOnPrintEventListener = interface;//com.example.print_sdk.interfaces.OnPrintEventListener
  JBitmapToByteUtils = interface;//com.example.print_sdk.util.BitmapToByteUtils
  JBitmapToByteUtils_1 = interface;//com.example.print_sdk.util.BitmapToByteUtils$1
  JBitmapToByteUtils_PAlign = interface;//com.example.print_sdk.util.BitmapToByteUtils$PAlign
  JByteUtils = interface;//com.example.print_sdk.util.ByteUtils
  JSerialPort = interface;//com.lcserial.www.SerialPort
  JSerialPortFinder = interface;//com.lcserial.www.SerialPortFinder
  JSerialPortFinder_Driver = interface;//com.lcserial.www.SerialPortFinder$Driver
  JSerialPortTool = interface;//com.lcserial.www.SerialPortTool
  JVector = interface;//java.util.Vector

// ===== Interface declarations =====

  Jprint_sdk_BuildConfigClass = interface(JObjectClass)
    ['{4AF7C67A-A9C7-4D40-AC55-59A00B9F9037}']
    {class} function _GetBUILD_TYPE: JString; cdecl;
    {class} function _GetDEBUG: Boolean; cdecl;
    {class} function _GetLIBRARY_PACKAGE_NAME: JString; cdecl;
    {class} function init: Jprint_sdk_BuildConfig; cdecl;//Deprecated
    {class} property BUILD_TYPE: JString read _GetBUILD_TYPE;
    {class} property DEBUG: Boolean read _GetDEBUG;
    {class} property LIBRARY_PACKAGE_NAME: JString read _GetLIBRARY_PACKAGE_NAME;
  end;

  [JavaSignature('com/example/print_sdk/BuildConfig')]
  Jprint_sdk_BuildConfig = interface(JObject)
    ['{3EF30B8F-3139-41C1-A3E1-97FEA126AAEE}']
  end;
  TJprint_sdk_BuildConfig = class(TJavaGenericImport<Jprint_sdk_BuildConfigClass, Jprint_sdk_BuildConfig>) end;

  JEscUtilsClass = interface(JObjectClass)
    ['{9E23270C-7339-4000-B628-36F5AB13F947}']
    {class} function esc_barcode_1D_print(P1: JString; P2: JBARCODE_1D_TYPE): Integer; cdecl;//Deprecated
    {class} function esc_barcode_2D_print(P1: Integer; P2: Integer; P3: Integer; P4: JALIGN_MODE; P5: JString): Integer; cdecl;//Deprecated
    {class} function esc_barcode_height(P1: Integer): Integer; cdecl;//Deprecated
    {class} function esc_barcode_width(P1: Integer): Integer; cdecl;//Deprecated
    {class} procedure esc_buffer_clear; cdecl;//Deprecated
    {class} function esc_char_bold(P1: Boolean): Integer; cdecl;//Deprecated
    {class} function esc_char_enlarge(P1: JMODE_ENLARGE): Integer; cdecl;//Deprecated
    {class} function esc_char_font(P1: JFONT_ID): Integer; cdecl;//Deprecated
    {class} function esc_default_print: Integer; cdecl;//Deprecated
    {class} function esc_enable_mark(P1: Boolean): Integer; cdecl;//Deprecated
    {class} function esc_enter_print: Integer; cdecl;//Deprecated
    {class} function esc_exit_unicode: Integer; cdecl;//Deprecated
    {class} function esc_feature_list: Integer; cdecl;//Deprecated
    {class} function esc_feed_paper(P1: Boolean; P2: Integer): Integer; cdecl;//Deprecated
    {class} function esc_init_print: Integer; cdecl;//Deprecated
    {class} function esc_length_get: Integer; cdecl;//Deprecated
    {class} function esc_lib_version: Integer; cdecl;//Deprecated
    {class} function esc_main_mark: Integer; cdecl;//Deprecated
    {class} function esc_no_paper_print_status(P1: Byte): Integer; cdecl;//Deprecated
    {class} function esc_open_one_vote_one_control(P1: Integer): Integer; cdecl;//Deprecated
    {class} function esc_print_align(P1: JALIGN_MODE): Integer; cdecl;//Deprecated
    {class} function esc_print_hri: Integer; cdecl;//Deprecated
    {class} function esc_print_languageList: Integer; cdecl;//Deprecated
    {class} function esc_print_left_margin(P1: SmallInt): Integer; cdecl;//Deprecated
    {class} function esc_print_line_space(P1: Boolean; P2: Byte): Integer; cdecl;//Deprecated
    {class} function esc_print_state: Integer; cdecl;//Deprecated
    {class} function esc_psam_info(P1: Integer): Integer; cdecl;//Deprecated
    {class} function esc_psam_send(P1: Integer; P2: TJavaArray<Byte>; P3: Integer): Integer; cdecl;//Deprecated
    {class} function esc_select_sensor_stop_print: Integer; cdecl;//Deprecated
    {class} function esc_set_black(P1: Integer; P2: Integer): Integer; cdecl;//Deprecated
    {class} function esc_set_concentration(P1: Integer): Integer; cdecl;//Deprecated
    {class} function esc_set_encode(P1: Byte): Integer; cdecl;//Deprecated
    {class} function esc_set_language(P1: Byte): Integer; cdecl;//Deprecated
    {class} function esc_set_sn(P1: TJavaArray<Byte>): Integer; cdecl;//Deprecated
    {class} function esc_set_sn_end: Integer; cdecl;//Deprecated
    {class} function esc_test: Integer; cdecl;//Deprecated
    {class} function esc_text_print(P1: JString): Integer; cdecl;//Deprecated
    {class} function getEscBuffer: TJavaArray<Byte>; cdecl;//Deprecated
    {class} function init(P1: Integer): JEscUtils; cdecl;//Deprecated
  end;

  [JavaSignature('com/example/print_sdk/EscUtils')]
  JEscUtils = interface(JObject)
    ['{154063F4-5B7B-4A21-9B2B-2CA70F9D0861}']
  end;
  TJEscUtils = class(TJavaGenericImport<JEscUtilsClass, JEscUtils>) end;

  JEscUtils_1Class = interface(JObjectClass)
    ['{CCEFF579-0236-4ED3-97C8-4BDFCE28377C}']
  end;

  [JavaSignature('com/example/print_sdk/EscUtils$1')]
  JEscUtils_1 = interface(JObject)
    ['{263CB672-7EE1-4F22-9E10-16D8DDA2F77E}']
  end;
  TJEscUtils_1 = class(TJavaGenericImport<JEscUtils_1Class, JEscUtils_1>) end;

  JSerialManager_OnDataReceiveListenerClass = interface(IJavaClass)
    ['{A1E769AF-2EBA-4A18-9B09-2B5F75D3116E}']
    {class} procedure onDataReceive(P1: TJavaArray<Byte>; P2: Integer); cdecl;//Deprecated
  end;

  [JavaSignature('com/example/print_sdk/SerialManager$OnDataReceiveListener')]
  JSerialManager_OnDataReceiveListener = interface(IJavaInstance)
    ['{4CE95D9C-BC11-43A8-8D64-C9908138973A}']
  end;
  TJSerialManager_OnDataReceiveListener = class(TJavaGenericImport<JSerialManager_OnDataReceiveListenerClass, JSerialManager_OnDataReceiveListener>) end;

  JPrintUtilClass = interface(JSerialManager_OnDataReceiveListenerClass)
    ['{197C02F8-45F1-4961-B34E-E714AD84E558}']
    {class} function _GetWIDTH_PIXEL: Integer; cdecl;
    {class} function _Getcheck_paper: Boolean; cdecl;
    {class} procedure _Setcheck_paper(Value: Boolean); cdecl;
    {class} procedure closeDev; cdecl;//Deprecated
    {class} function esc_text_print(P1: JString): Integer; cdecl;//Deprecated
    {class} procedure exitUnicode; cdecl;//Deprecated
    {class} function getClient: JPrintUtil; cdecl;//Deprecated
    {class} function getGbk(P1: JString): TJavaArray<Byte>; cdecl;//Deprecated
    {class} function getInstance: JPrintUtil; cdecl;//Deprecated
    {class} function getOffset(P1: JString): Integer; cdecl;//Deprecated
    {class} procedure getTemperature; cdecl;//Deprecated
    {class} procedure getVersion; cdecl;//Deprecated
    {class} function init: JPrintUtil; cdecl;//Deprecated
    {class} procedure initPrinter; cdecl;//Deprecated
    {class} procedure initSDK; cdecl;//Deprecated
    {class} function isChinese(P1: JString): Boolean; cdecl; overload;//Deprecated
    {class} function isChinese(P1: Char): Boolean; cdecl; overload;//Deprecated
    {class} procedure onDataReceive(P1: TJavaArray<Byte>; P2: Integer); cdecl;//Deprecated
    {class} procedure print(P1: TJavaArray<Byte>); cdecl;//Deprecated
    {class} procedure printAlignment(P1: JALIGN_MODE); cdecl;//Deprecated
    {class} procedure printAutoEnableMark(P1: Boolean); cdecl;//Deprecated
    {class} procedure printBackPaper(P1: Integer); cdecl;//Deprecated
    {class} procedure printBarcode(P1: JString; P2: Integer; P3: Integer); cdecl; overload;//Deprecated
    {class} procedure printBarcode(P1: JString; P2: JBARCODE_1D_TYPE; P3: Integer; P4: Integer); cdecl; overload;//Deprecated
    {class} procedure printBarcode2(P1: JBitmap); cdecl;//Deprecated
    {class} procedure printBitmap(P1: JBitmap); cdecl;//Deprecated
    {class} procedure printBitmap2(P1: JBitmap); cdecl;//Deprecated
    {class} procedure printConcentration(P1: Integer); cdecl;//Deprecated
    {class} procedure printDashLine; cdecl;//Deprecated
    {class} procedure printEnableCertificate(P1: Boolean); cdecl;//Deprecated
    {class} procedure printEnableMark(P1: Boolean); cdecl;//Deprecated
    {class} procedure printEncode(P1: Integer); cdecl;//Deprecated
    {class} procedure printEndNumber; cdecl;//Deprecated
    {class} procedure printFeatureList; cdecl;//Deprecated
    {class} procedure printFontSize(P1: JMODE_ENLARGE); cdecl;//Deprecated
    {class} procedure printFourColumn(P1: JString; P2: JString; P3: JString; P4: JString); cdecl;//Deprecated
    {class} procedure printGoToNextMark; cdecl;//Deprecated
    {class} procedure printImage(P1: JBitmap); cdecl;//Deprecated
    {class} procedure printLanguage(P1: Integer); cdecl;//Deprecated
    {class} procedure printLargeText(P1: JString); cdecl;//Deprecated
    {class} procedure printLine; cdecl; overload;//Deprecated
    {class} procedure printLine(P1: Integer); cdecl; overload;//Deprecated
    {class} procedure printMarginLeft(P1: Integer); cdecl;//Deprecated
    {class} procedure printNoBarcodeText; cdecl;//Deprecated
    {class} procedure printQR(P1: JBitmap); cdecl;//Deprecated
    {class} procedure printQR2(P1: Integer; P2: Integer; P3: Integer; P4: JALIGN_MODE; P5: JString); cdecl;//Deprecated
    {class} procedure printStartNumber(P1: Integer); cdecl;//Deprecated
    {class} procedure printState; cdecl;//Deprecated
    {class} procedure printTabSpace(P1: Integer); cdecl;//Deprecated
    {class} procedure printText(P1: JString); cdecl;//Deprecated
    {class} procedure printTextBold(P1: Boolean); cdecl;//Deprecated
    {class} procedure printThicken(P1: Boolean); cdecl;//Deprecated
    {class} procedure printThreeColumn(P1: JString; P2: JString; P3: JString); cdecl;//Deprecated
    {class} procedure printTwoColumn(P1: JString; P2: JString); cdecl;//Deprecated
    {class} procedure printUnderscore(P1: Integer); cdecl;//Deprecated
    {class} procedure resetPrint; cdecl;//Deprecated
    {class} function resetPsam(P1: Integer; P2: TJavaArray<Byte>): Integer; cdecl;//Deprecated
    {class} function sendApdu(P1: Integer; P2: JString; P3: TJavaArray<Byte>): Integer; cdecl;//Deprecated
    {class} procedure setEncoding(P1: JString); cdecl;//Deprecated
    {class} function setLocation(P1: Integer): TJavaArray<Byte>; cdecl;//Deprecated
    {class} procedure setPrintDefLineSpacing; cdecl;//Deprecated
    {class} procedure setPrintEventListener(P1: JOnPrintEventListener); cdecl;//Deprecated
    {class} procedure setPrintLineSpacing(P1: Byte); cdecl;//Deprecated
    {class} procedure setPrintSpeed(P1: Integer); cdecl;//Deprecated
    {class} procedure setSocket(P1: JBluetoothSocket; P2: JString); cdecl;//Deprecated
    {class} procedure showBarcodeHRI(P1: Boolean); cdecl;//Deprecated
    {class} procedure sleep(P1: Integer); cdecl;//Deprecated
    {class} property WIDTH_PIXEL: Integer read _GetWIDTH_PIXEL;
    {class} property check_paper: Boolean read _Getcheck_paper write _Setcheck_paper;
  end;

  [JavaSignature('com/example/print_sdk/PrintUtil')]
  JPrintUtil = interface(JSerialManager_OnDataReceiveListener)
    ['{F62A814D-3547-4B21-905D-C9624753E306}']
  end;
  TJPrintUtil = class(TJavaGenericImport<JPrintUtilClass, JPrintUtil>) end;

  JPrintUtil_1Class = interface(JRunnableClass)
    ['{8FD0FAD7-0D4A-4242-87DB-3E30B5FB2909}']
    {class} function _Getthis: JPrintUtil; cdecl;
    {class} function _Getvalsize: Integer; cdecl;
    {class} function init(P1: JPrintUtil; P2: TJavaArray<Byte>; P3: Integer): JPrintUtil_1; cdecl;//Deprecated
    {class} procedure run; cdecl;//Deprecated
    {class} property this: JPrintUtil read _Getthis;
    {class} property valsize: Integer read _Getvalsize;
  end;

  [JavaSignature('com/example/print_sdk/PrintUtil$1')]
  JPrintUtil_1 = interface(JRunnable)
    ['{5E560D8E-9C5D-4F73-92D2-0543822C26C2}']
  end;
  TJPrintUtil_1 = class(TJavaGenericImport<JPrintUtil_1Class, JPrintUtil_1>) end;

  JPrintUtil_SingletonClass = interface(JEnumClass)
    ['{8A00925F-0E6C-4820-BA88-D8A9FAA4D66B}']
    {class} function _GetINSTANCE: JPrintUtil_Singleton; cdecl;
    {class} function valueOf(P1: JString): JPrintUtil_Singleton; cdecl;//Deprecated
    {class} function values: TJavaObjectArray<JPrintUtil_Singleton>; cdecl;//Deprecated
    {class} property INSTANCE: JPrintUtil_Singleton read _GetINSTANCE;
  end;

  [JavaSignature('com/example/print_sdk/PrintUtil$Singleton')]
  JPrintUtil_Singleton = interface(JEnum)
    ['{F8B01F89-4515-4C9E-80AA-AD23F4756141}']
  end;
  TJPrintUtil_Singleton = class(TJavaGenericImport<JPrintUtil_SingletonClass, JPrintUtil_Singleton>) end;

  JSerialManagerClass = interface(JObjectClass)
    ['{93E1233C-BFD5-4A4F-AEF8-81AD41133888}']
    {class} function _GetBAUTRATE: Integer; cdecl;
    {class} function _GetPATH: JString; cdecl;
    {class} function _Getextvcc: JString; cdecl;
    {class} procedure _Setextvcc(Value: JString); cdecl;
    {class} function _GetmOutputStream: JOutputStream; cdecl;
    {class} procedure _SetmOutputStream(Value: JOutputStream); cdecl;
    {class} function _GetmSerialPort: JSerialPort; cdecl;
    {class} procedure _SetmSerialPort(Value: JSerialPort); cdecl;
    {class} function _GetserialPortTool: JSerialPortTool; cdecl;
    {class} procedure _SetserialPortTool(Value: JSerialPortTool); cdecl;
    {class} function _GetsetSam: JString; cdecl;
    {class} procedure _SetsetSam(Value: JString); cdecl;
    {class} function Bytes2HexString(P1: TJavaArray<Byte>): JString; cdecl;//Deprecated
    {class} procedure close; cdecl;//Deprecated
    {class} function escCommand(P1: TJavaArray<Byte>): Boolean; cdecl; overload;//Deprecated
    {class} function escCommand(P1: JString): Boolean; cdecl; overload;//Deprecated
    {class} function escCommand(P1: TJavaArray<Byte>; P2: Integer): Boolean; cdecl; overload;//Deprecated
    {class} function getClient: JSerialManager; cdecl;//Deprecated
    {class} function getInputStream: JInputStream; cdecl;//Deprecated
    {class} function getOutputStream: JOutputStream; cdecl;//Deprecated
    {class} function init: JSerialManager; cdecl;//Deprecated
    {class} function open: Boolean; cdecl;//Deprecated
    {class} function receivePsam(P1: TJavaArray<Byte>; P2: Int64): Integer; cdecl;//Deprecated
    {class} procedure setOnDataReceiveListener(P1: JSerialManager_OnDataReceiveListener); cdecl;//Deprecated
    {class} procedure startReadThread; cdecl;//Deprecated
    {class} property BAUTRATE: Integer read _GetBAUTRATE;
    {class} property PATH: JString read _GetPATH;
    {class} property extvcc: JString read _Getextvcc write _Setextvcc;
    {class} property mOutputStream: JOutputStream read _GetmOutputStream write _SetmOutputStream;
    {class} property mSerialPort: JSerialPort read _GetmSerialPort write _SetmSerialPort;
    {class} property serialPortTool: JSerialPortTool read _GetserialPortTool write _SetserialPortTool;
    {class} property setSam: JString read _GetsetSam write _SetsetSam;
  end;

  [JavaSignature('com/example/print_sdk/SerialManager')]
  JSerialManager = interface(JObject)
    ['{DCBA525F-7998-455B-92E3-BAAA93D6F749}']
  end;
  TJSerialManager = class(TJavaGenericImport<JSerialManagerClass, JSerialManager>) end;

  JSerialManager_1Class = interface(JObjectClass)
    ['{DBE7BCE2-AE43-4DC9-BC96-8C0292D0696C}']
  end;

  [JavaSignature('com/example/print_sdk/SerialManager$1')]
  JSerialManager_1 = interface(JObject)
    ['{B2EB9959-6F2D-413C-9CAD-971E08400A3E}']
  end;
  TJSerialManager_1 = class(TJavaGenericImport<JSerialManager_1Class, JSerialManager_1>) end;

  JSerialManager_ReadThreadClass = interface(JThreadClass)
    ['{F130A205-F0BE-4DF5-A4BB-E089587F5944}']
    {class} function init(P1: JSerialManager; P2: JSerialManager_1): JSerialManager_ReadThread; cdecl;//Deprecated
    {class} procedure run; cdecl;//Deprecated
  end;

  [JavaSignature('com/example/print_sdk/SerialManager$ReadThread')]
  JSerialManager_ReadThread = interface(JThread)
    ['{8B080BC4-4080-47ED-9D86-D0C87F833EF4}']
  end;
  TJSerialManager_ReadThread = class(TJavaGenericImport<JSerialManager_ReadThreadClass, JSerialManager_ReadThread>) end;

  JSerialManager_SingletonClass = interface(JEnumClass)
    ['{04AFBD2A-5EC3-4896-B143-D540D3FB8985}']
    {class} function _GetINSTANCE: JSerialManager_Singleton; cdecl;
    {class} function valueOf(P1: JString): JSerialManager_Singleton; cdecl;//Deprecated
    {class} function values: TJavaObjectArray<JSerialManager_Singleton>; cdecl;//Deprecated
    {class} property INSTANCE: JSerialManager_Singleton read _GetINSTANCE;
  end;

  [JavaSignature('com/example/print_sdk/SerialManager$Singleton')]
  JSerialManager_Singleton = interface(JEnum)
    ['{3F2E8946-1CF2-4295-A93F-FBA4F91E66DD}']
  end;
  TJSerialManager_Singleton = class(TJavaGenericImport<JSerialManager_SingletonClass, JSerialManager_Singleton>) end;

  JALIGN_MODEClass = interface(JEnumClass)
    ['{DD57EF9B-D9BD-4800-B9E0-8DCF6CB20C6C}']
    {class} function _GetALIGN_CENTER: JALIGN_MODE; cdecl;
    {class} function _GetALIGN_LEFT: JALIGN_MODE; cdecl;
    {class} function _GetALIGN_RIGHT: JALIGN_MODE; cdecl;
    {class} function &Get: Integer; cdecl;//Deprecated
    {class} function valueOf(P1: JString): JALIGN_MODE; cdecl;//Deprecated
    {class} function values: TJavaObjectArray<JALIGN_MODE>; cdecl;//Deprecated
    {class} property ALIGN_CENTER: JALIGN_MODE read _GetALIGN_CENTER;
    {class} property ALIGN_LEFT: JALIGN_MODE read _GetALIGN_LEFT;
    {class} property ALIGN_RIGHT: JALIGN_MODE read _GetALIGN_RIGHT;
  end;

  [JavaSignature('com/example/print_sdk/enums/ALIGN_MODE')]
  JALIGN_MODE = interface(JEnum)
    ['{2E72216B-8E1A-4FB0-9A18-112C0077FE14}']
  end;
  TJALIGN_MODE = class(TJavaGenericImport<JALIGN_MODEClass, JALIGN_MODE>) end;

  JBARCODE_1D_TYPEClass = interface(JEnumClass)
    ['{964C5000-043A-4EC1-B98A-FEEBCE464B69}']
    {class} function _GetCODE128: JBARCODE_1D_TYPE; cdecl;
    {class} function _GetCODE39: JBARCODE_1D_TYPE; cdecl;
    {class} function _GetCODE93: JBARCODE_1D_TYPE; cdecl;
    {class} function _GetEAN13: JBARCODE_1D_TYPE; cdecl;
    {class} function _GetEAN8: JBARCODE_1D_TYPE; cdecl;
    {class} function _GetITF25: JBARCODE_1D_TYPE; cdecl;
    {class} function _GetUPCA: JBARCODE_1D_TYPE; cdecl;
    {class} function _GetUPCE: JBARCODE_1D_TYPE; cdecl;
    {class} function &Get: Integer; cdecl;//Deprecated
    {class} function valueOf(P1: JString): JBARCODE_1D_TYPE; cdecl;//Deprecated
    {class} function values: TJavaObjectArray<JBARCODE_1D_TYPE>; cdecl;//Deprecated
    {class} property CODE128: JBARCODE_1D_TYPE read _GetCODE128;
    {class} property CODE39: JBARCODE_1D_TYPE read _GetCODE39;
    {class} property CODE93: JBARCODE_1D_TYPE read _GetCODE93;
    {class} property EAN13: JBARCODE_1D_TYPE read _GetEAN13;
    {class} property EAN8: JBARCODE_1D_TYPE read _GetEAN8;
    {class} property ITF25: JBARCODE_1D_TYPE read _GetITF25;
    {class} property UPCA: JBARCODE_1D_TYPE read _GetUPCA;
    {class} property UPCE: JBARCODE_1D_TYPE read _GetUPCE;
  end;

  [JavaSignature('com/example/print_sdk/enums/BARCODE_1D_TYPE')]
  JBARCODE_1D_TYPE = interface(JEnum)
    ['{71202FD9-B725-4FDF-8E31-2FFAB7C47186}']
  end;
  TJBARCODE_1D_TYPE = class(TJavaGenericImport<JBARCODE_1D_TYPEClass, JBARCODE_1D_TYPE>) end;

  JFONT_IDClass = interface(JEnumClass)
    ['{FFC9C28D-7FFD-4B8B-9BD6-AF5B94E03F74}']
    {class} function _GetFONT_ASCII_12x24: JFONT_ID; cdecl;
    {class} function _GetFONT_ASCII_9x17: JFONT_ID; cdecl;
    {class} function &Get: Integer; cdecl;//Deprecated
    {class} function valueOf(P1: JString): JFONT_ID; cdecl;//Deprecated
    {class} function values: TJavaObjectArray<JFONT_ID>; cdecl;//Deprecated
    {class} property FONT_ASCII_12x24: JFONT_ID read _GetFONT_ASCII_12x24;
    {class} property FONT_ASCII_9x17: JFONT_ID read _GetFONT_ASCII_9x17;
  end;

  [JavaSignature('com/example/print_sdk/enums/FONT_ID')]
  JFONT_ID = interface(JEnum)
    ['{E952A2D8-831D-45C0-9856-1B5DE9E11C81}']
  end;
  TJFONT_ID = class(TJavaGenericImport<JFONT_IDClass, JFONT_ID>) end;

  JSerialPortToolClass = interface(JObjectClass)
    ['{18F19FB3-9A40-422C-B9AD-F04076C51CCE}']
    {class} function _GetmSerialPortFinder: JSerialPortFinder; cdecl;
    {class} procedure closeSerialPort; cdecl;//Deprecated
    {class} function getSerialPort(P1: JString; P2: Integer): JSerialPort; cdecl;//Deprecated
    {class} function init: JSerialPortTool; cdecl;//Deprecated
    {class} property mSerialPortFinder: JSerialPortFinder read _GetmSerialPortFinder;
  end;

  [JavaSignature('com/lcserial/www/SerialPortTool')]
  JSerialPortTool = interface(JObject)
    ['{01A9F76E-F9DA-41FB-99F3-5A11D273A5D4}']
  end;
  TJSerialPortTool = class(TJavaGenericImport<JSerialPortToolClass, JSerialPortTool>) end;

  JVectorClass = interface(JAbstractListClass)
    ['{AF3067AC-4EA6-496A-9A93-E5D96BDDDECD}']
    {class} function init: JVector; cdecl; overload;//Deprecated
    {class} function init(capacity: Integer): JVector; cdecl; overload;//Deprecated
    {class} function init(capacity: Integer; capacityIncrement: Integer): JVector; cdecl; overload;//Deprecated
    {class} function init(collection: JCollection): JVector; cdecl; overload;//Deprecated
    {class} procedure add(location: Integer; object_: JObject); cdecl; overload;
    {class} function add(object_: JObject): Boolean; cdecl; overload;
    {class} function addAll(location: Integer; collection: JCollection): Boolean; cdecl; overload;
    {class} procedure clear; cdecl;
    {class} function clone: JObject; cdecl;
    {class} function &contains(object_: JObject): Boolean; cdecl;
    {class} function elements: JEnumeration; cdecl;//Deprecated
    {class} procedure ensureCapacity(minimumCapacity: Integer); cdecl;//Deprecated
    {class} function hashCode: Integer; cdecl;//Deprecated
    {class} function indexOf(object_: JObject): Integer; cdecl; overload;//Deprecated
    {class} function indexOf(object_: JObject; location: Integer): Integer; cdecl; overload;//Deprecated
    {class} function lastIndexOf(object_: JObject): Integer; cdecl; overload;//Deprecated
    {class} function lastIndexOf(object_: JObject; location: Integer): Integer; cdecl; overload;//Deprecated
    {class} function remove(location: Integer): JObject; cdecl; overload;//Deprecated
    {class} function removeElement(object_: JObject): Boolean; cdecl;//Deprecated
    {class} procedure removeElementAt(location: Integer); cdecl;//Deprecated
    {class} function retainAll(collection: JCollection): Boolean; cdecl;//Deprecated
    {class} function size: Integer; cdecl;
    {class} function subList(start: Integer; end_: Integer): JList; cdecl;
    {class} function toArray: TJavaObjectArray<JObject>; cdecl; overload;
  end;
 overload;
    function toString: JString; cdecl;
    procedure trimToSize; cdecl;
  end;
  TJVector = class(TJavaGenericImport<JVectorClass, JVector>) end;

implementation

procedure RegisterTypes;
begin
  TRegTypes.RegisterType('SdkPrint.Jprint_sdk_BuildConfig', TypeInfo(SdkPrint.Jprint_sdk_BuildConfig));
  TRegTypes.RegisterType('SdkPrint.JEscUtils', TypeInfo(SdkPrint.JEscUtils));
  TRegTypes.RegisterType('SdkPrint.JEscUtils_1', TypeInfo(SdkPrint.JEscUtils_1));
  TRegTypes.RegisterType('SdkPrint.JSerialManager_OnDataReceiveListener', TypeInfo(SdkPrint.JSerialManager_OnDataReceiveListener));
  TRegTypes.RegisterType('SdkPrint.JPrintUtil', TypeInfo(SdkPrint.JPrintUtil));
  TRegTypes.RegisterType('SdkPrint.JPrintUtil_1', TypeInfo(SdkPrint.JPrintUtil_1));
  TRegTypes.RegisterType('SdkPrint.JPrintUtil_Singleton', TypeInfo(SdkPrint.JPrintUtil_Singleton));
  TRegTypes.RegisterType('SdkPrint.JSerialManager', TypeInfo(SdkPrint.JSerialManager));
  TRegTypes.RegisterType('SdkPrint.JSerialManager_1', TypeInfo(SdkPrint.JSerialManager_1));
  TRegTypes.RegisterType('SdkPrint.JSerialManager_ReadThread', TypeInfo(SdkPrint.JSerialManager_ReadThread));
  TRegTypes.RegisterType('SdkPrint.JSerialManager_Singleton', TypeInfo(SdkPrint.JSerialManager_Singleton));
  TRegTypes.RegisterType('SdkPrint.JALIGN_MODE', TypeInfo(SdkPrint.JALIGN_MODE));
  TRegTypes.RegisterType('SdkPrint.JBARCODE_1D_TYPE', TypeInfo(SdkPrint.JBARCODE_1D_TYPE));
  TRegTypes.RegisterType('SdkPrint.JFONT_ID', TypeInfo(SdkPrint.JFONT_ID));
  TRegTypes.RegisterType('SdkPrint.JMODE_ENLARGE', TypeInfo(SdkPrint.JMODE_ENLARGE));
  TRegTypes.RegisterType('SdkPrint.JOnPrintEventListener', TypeInfo(SdkPrint.JOnPrintEventListener));
  TRegTypes.RegisterType('SdkPrint.JBitmapToByteUtils', TypeInfo(SdkPrint.JBitmapToByteUtils));
  TRegTypes.RegisterType('SdkPrint.JBitmapToByteUtils_1', TypeInfo(SdkPrint.JBitmapToByteUtils_1));
  TRegTypes.RegisterType('SdkPrint.JBitmapToByteUtils_PAlign', TypeInfo(SdkPrint.JBitmapToByteUtils_PAlign));
  TRegTypes.RegisterType('SdkPrint.JByteUtils', TypeInfo(SdkPrint.JByteUtils));
  TRegTypes.RegisterType('SdkPrint.JSerialPort', TypeInfo(SdkPrint.JSerialPort));
  TRegTypes.RegisterType('SdkPrint.JSerialPortFinder', TypeInfo(SdkPrint.JSerialPortFinder));
  TRegTypes.RegisterType('SdkPrint.JSerialPortFinder_Driver', TypeInfo(SdkPrint.JSerialPortFinder_Driver));
  TRegTypes.RegisterType('SdkPrint.JSerialPortTool', TypeInfo(SdkPrint.JSerialPortTool));
  TRegTypes.RegisterType('SdkPrint.JVector', TypeInfo(SdkPrint.JVector));
end;

initialization
  RegisterTypes;
end.

Comment: What is you underlying problem? Want to print something? Describe the environment. Maybe [the answer to this question](https://stackoverflow.com/questions/30234595/wifi-printing-in-android-is-not-working) would help?
Comment: My Problem is how to call the class of the  "JPrintUtilClass" interface
Comment: What .jar file did you process?
Comment: printer jar SDK
Comment: "printer jar SDK" doesn't tell us anything unless you indicate who produced it, and/or where it is located
Comment: The SDK came with documentation tell which methods and description for them ,  http://svoton.com/a/PRODUCTS/Mobile_Terminal/Android_Mobile_Terminal/2021/0413/43.html
Answer: The JPrintUtilClass interface is meant to represent the static methods/properties of the Java PrintUtil class, whereas the JPrintUtil interface is meant to represent the non-static instance methods/properties instead.  You need to use the JavaClass property of the generated TJPrintUtil Delphi wrapper class in order to access the static members of the Java PrintUtil class, eg:
uses
  SdkPrint;

TJPrintUtil.JavaClass.useSomeMemberHere;
...

Based on your recent comment, a correct translation of the example you provided from the SDK documentation would look like this in Delphi:
uses
  ..., SdkPrint;

var
  pUtil: JPrintUtil;
begin
  try
    pUtil := TJPrintUtil.JavaClass.getClient;
    pUtil.printState;
    pUtil.printAlignment(TJALIGN_MODE.JavaClass.ALIGN_LEFT);
    pUtil.printTextBold(false);
    pUtil.printTwoColumn(StringToJString('Time: '), StringToJString('2021-05-09 15:50:41'));
    pUtil.printTwoColumn(StringToJString('order number:'), StringToJString('1'));
    pUtil.printText(StringToJString('unit price'));
    pUtil.printThreeColumn(StringToJString('iphoneXII'), StringToJString('1'), StringToJString('4999.00'));
    pUtil.printThreeColumn(StringToJString('MAC PRO'), StringToJString('1'), StringToJString('4999.00'));
    pUtil.printTwoColumn(StringToJString('order amount:'), StringToJString('9998.00'));
    pUtil.printEndNumber;
  except
  end;
end;

However, this won't work in your case, because most of these PrintUtil methods are non-static instance methods, but the generated Delphi code from Java2OP that you provided is treating them all as static class methods instead. Which means Java2OP is not importing the JAR correctly.  This is actually a known issue, see the following bug reports:
RSP-15473: Java2Op emits erroneous code
RSP-21462: Java2OP outputting Class declarations instead of procedures
RSP-24029: Regression in Java2OP so that instance methods are treated as class methods
So, you will have to manually correct the mistakes in the generated code to move only the non-static instance methods/properties from the JPrintUtilClass interface to the JPrintUtil interface (and probably do the same for many of the other interfaces in the same unit).  Then the above code should work.
Comment: this is an example from the SDK : try
 {
 PrintUtil pUtil = PrintUtil.getClient ();
 pUtil. printState ();
 pUtil.printAlignment (ALIGN_MODE.ALIGN_LEFT);
 pUtil.printTextBold (false);
 pUtil.printTwoColumn ("Time: ", "2021-05-09 15:50:41");
 pUtil.printTwoColumn ("order number:", "1");
 pUtil.printText ("unit price");
 pUtil.printThreeColumn ("iphoneXII", "1", "4999.00");
 pUtil.printThreeColumn ("MAC PRO", "1", "4999.00");
 pUtil.printTwoColumn ("order amount:", "9998.00");
 pUtil.printEndNumber ();
 }
 catch (IOException e) { }
 }
Comment: Thank you , was great and it was really what you explain and i deployed the .so file and working fine , thanks again


Parse error posting data with cURL in PHP

Question: I am attempting to POST data to an API using PHP and cURL like so:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://sandbox.api.myAPIsite.com/values?api_key=MyAPIKey");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);

$data = array(
    "configuration"=> {
         "vehicleId"=> 382245,
         "vehicleOptionIds"=> [5154080]
    },
    "mileage"=> 100000,
    "zipCode"=> "02101",
    "valuationDate"=> "2019-04-08T23:59:21.803Z"
);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);

However, the log says parse error had occurred. What would the correct syntax be to solve this?
Log details:
PHP Parse error:  syntax error, unexpected '{' in /home/78ds6f76f8fds6f/public_html/desktop/values.php on line 11

Comment: Any parse error details in the logs ?
Comment: I updated the question to show the log details, says unexpected '{' on line 11 which is the line with "configuration" => {
Answer: You are (incorrectly) using JavaScript's object notation instead of PHP's array notation inside your 'configuration' array key, to fix this, simply change your $data array to the following:
$data = array(
    "configuration"=> [
         "vehicleId"=> 382245,
         "vehicleOptionIds"=> [5154080]
    ],
    "mileage"=> 100000,
    "zipCode"=> "02101",
    "valuationDate"=> "2019-04-08T23:59:21.803Z"
);

Comment: FYI ...you used right object syntax from javascript but not work in php ;)


Getting different answers to a problem when using different methods. Cannot find a problem with either.

Question: The question I'm solving is:

A student jogs from home to the store. She runs at 1 m/s for 1/3 of the time and 1.5 m/s for the remaining time. On her way back home she runs at 1 m/s for half the distance and at 1.5 m/s for the rest of the trip. Find her average speed for the round trip.

The way I approached this first was by defining:

$d$ as the distance between the house and the store
$t_1$ as the time to get there on the first leg
$t_2$ as the time to get back

This means that the answer I would be looking for could be defined as $\frac{2d}{t_1+t_2}$
Setting

$d=1\frac{m}{s}\cdot\frac{1}{3}t_1+1.5\frac{m}{s}\cdot\frac{2}{3}t_1$
and $t_2=\frac{\frac{1}{2}d}{1\frac{m}{s}}+\frac{\frac{1}{2}d}{1.5\frac{m}{s}}$

I was able to simplify both down to

$d=\frac{4}{3}\frac{m}{s}t_1$
$t_2=\frac{ds}{2m}+\frac{ds}{3m}$

Solving for $t_2$ in terms of $t_1$ by substituting in my value for $d$, I yielded $t_2 = \frac{14}{3}t_1$.
Then, plugging all my values into $\frac{2d}{t_1+t_2}$, all units cancelled providing me with $v_{avg}=\frac{8}{17}m/s$.
This is apparently incorrect. However, I cannot find anything wrong with this approach.
The other option to tackling this problem is to calculate the average velocities of each individual leg of the trip.
By defining $v_1=\frac{1\frac{m}{s}\cdot\frac{1}{3}t_1+1.5\frac{m}{s}\cdot\frac{2}{3}t_1}{t_1}$ where $v_1$ is the velocity of the first leg of the trip, $v_1$ can be computed at $\frac{4}{3}\frac{m}{s}$.
The trip back can be divided into sections A and B, with variables $d$, $v$, and $t$ representing the distance, velocity, and time. Since $d_A=d_B$, $d_A=v_At_A$, and $d_B=v_Bt_B$,
$v_At_A=v_Bt_B$
$\therefore t_A=1.5t_B$
Solving for the velocity from here yields:

$v_2=\frac{\Delta x}{\Delta t}$
$v_2=\frac{v_At_A + v_Bt_B}{t_A+t_B}$
$v_2=\frac{1\frac{m}{s}1.5t_B + 1.5\frac{m}{s}t_B}{1.5t_B+t_B}$

Simplifying gives $v_2 = \frac{6}{5}\frac{m}{s}$ or $1.20\frac{m}{s}$
Averaging $v_1$ and $v_2$ yields $1.26\frac{m}{s}$, a wildly different answer then the about $0.47\frac{m}{s}$ from the first method.
I am told that the answer yielded by the second method is correct, yet I cannot find any problems with the first. Can someone help with this?
Answer: Found it. Made an algebra mistake. In the first method, when substituting $d$ in for $t_2$ to solve for $t_2$ in terms of $t_1$, I should have gotten $t_2=\frac{10}{9}t_1$. That then provides the correct answer.
Comment: Good recovery. Please either accept your answer or delete the question so that it does not remain on the unanswered queue.


python social auth: get email from Google OAuth2

Question: I configured the login with google in a Django project. I'm able to get the name and last name but the user is saved with an empty email. I configured the scope in this way:
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
    'profile',
    'email'
]

But the email continues saving as "". Am I writing the scopes in bad way?
Answer: Try this
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'
]

it will collect user email and profile name store it into USER model.
Comment: where to add this?


Vim map  to comment code

Question: I installed nerd commenter, but couldn't make it work with the key bindings I used to.
I don't need to use the above plugin, but what I am trying to acheive (In MAC OSX)

map  (command + /) to toggle comment (//) of the current line (in Insert mode atleast)
Do the same on all lines if multiple lines are selected.
It is great if multiple lines are selected to use the block comment (/* .. */)

thanks for any help.
EDIT: below mappings kind of solved 1 and 2. Now, I wish I could use block comment when select multiple lines, and (//) otherwise.
imap <D-/> <esc>,c<space>i
vmap <D-/> ,c<space>gv
map <D-/> ,c<space>

Answer: this should work:
map <D-/> \c<space><CR>
imap <D-/> \c<space><CR>

or for sexy comments (aka /* */):
map <D-/> \cc<space><CR>
imap <D-/> \cc<space><CR>

you can check all the possible comments maps writing :help NERDCommenter and just remap them to what you like.
Comment: The `imap` one seems to need the `` prefix and `i` suffix to work as expected, so `imap  \ci`

Vim map  to comment code


Qcustomplot Display coordinates of selected points using mouse event

Question: I need to display a set of points(nearly 200) on my custom plot. Thereafter when I click on a specific point ,it should display its coordinates using mouse event. The mouse event should be able to display only those points coordinates where I click and not the remaining empty region. I have tried using event->pos().x() to a pixeltocoord. But no use. I need a help in mouse event.
Answer: Your question its a little vague, 'but not use' meaning what ? Did you received the event and the information is not useful ? or you never got an event ? Or the value is wrong for some perspective ? Is it your custom plot a QWidget ?
Well, I try anyway ...
If your custom plot is a QWidget:
First you need to enable Mouse tracking in your widget
CustomPlotWidget->setMouseTracking(true);

Then you should store the coordinates in the mouse press event, you do that by overriding the event handler
CustomPlotWidget::mousePressEvent(QMouseEvent *event)
{
   save_coords=event->pos;
}

Then when you paint the widget you use that coordinates to display some text there, or you can pop a QToolTip in that location (that is what I do, and it looks really nice)
According to your comment if you went with the solution of drawing yourself the coordinates you just need to redraw the section where you previously draw them. You can store the rectangular area when you draw before, then you redraw everything under that area but the coordinates.
CustomPlotWidget::mousePressEvent(QMouseEvent *event)
{
   ...
   save_coords=event->pos;
   update(areaWhereYouPreviouslyDrawCoordinates);
   update(areaWhereYouWantToDrawNewCoordinates);
}
CustomPlotWidget::paintEvent(QPaintEvent *event)
{
...
   if (event->rect().insersect(areaWhereYouWantToDrawNewCoordinates))
   {
        drawCoordinates();
        areaWhereYouPreviouslyDrawCoordinates=areaWhereYouWantToDrawNewCoordinates;
   }
...
}

If you go with the solution using QToolTip:
CustomPlotWidget::mousePressEvent(QMouseEvent *event)
{
   ...
   if (needToDrawCoordinates)
        QToolTip::showText(Where,Coordinates);
   else
        QToolTip::hideText();
}

Comment: Thank you Pablo! Yes,I recieved the event.The problem from my side is ,I have to select a single point from a set of points and that specific point should display its coordinates and when I click on some other point,the previous coordinates should be disappeared and the current selected point's coordinates  should be displayed.


TCPDF content grouping - prevent section from being on different page

Question: I am using TCPDF and using the writeHTML function to create PDF's like this:
$html = 'html content';
$pdf->writeHTML($html, true, false, true, false, '');

I have sections of content and each section is in a div and table, as the page and content automatically continues over to the next page, sometimes i get a very few lines of my content on one page and the remaining on the next page.
Is there a way in TCPDF, to tell it to make sure that the entire content of a div or table should be together? so if it needs to go to the next page, it should take the entire div to the next page?
Thanks
* UPDATE *
As olger suggested, 'page-break-inside' style attribute seems to work and do the job below:

HTML grouped content

Comment: Maybe you should look into using the 'page-break-inside' style attribute, [as shown in the first answer in this question](http://stackoverflow.com/questions/11738638/how-to-control-page-breaks-in-tcpdf). This would require you to change your source HTML instead of PHP.
Comment: Is the amount of content in the divs/tables always the same or are they for example dynamically generated from another source, so they differ in amount every time?
Comment: olger, yes they are dynamically generated so they differ every time
Comment: Awesome, just tried it and seems to work. Thanks
Answer:
   If you don't want breakable text then add this style div or table which you used. Add this style in your code style="page-break-inside:avoid;"

Comment: Please read the [code formatting guide](https://stackoverflow.com/editing-help#code) for reference on how to improve the readability of this and future answers.


EMT to outdoor ceiling fan

Question: I'm in the process of re-doing some back porch wiring to incorporate a switched receptacle for "cafe" lights, and also wanting to incorporate a ceiling fan for our back porch.
I have initially arranged things so that I have a box at the correct location under a rafter such that I can run my EMT along the rafter back to where the ceiling fan will be located, like so:

My question is, do I need to run the EMT along the rafter like this?  For alignment reasons having to do with a built-in bench (next project), I am considering moving the box a few inches to the left, which would make it not align with the rafter any more.  Is it OK to have the EMT hang in free space on its way over to the ceiling fan (a run of about 8 feet - see pic below)? Or would I need to jog it over and fasten it to the rafter?
Thanks!
Comment: "358.30(A) : EMT must be securely fastened within 3 ft. of termination fittings and at intervals not exceeding 10 ft."
Answer: The EMT will need to be anchored at that existing box or within 3' and again at the box for the fan. With the rain tight fittings and bell boxes this can be in a wet location, EMT can even be used underground now you just need the fittings like you have a recent code change.
Make sure the fan box is listed this is one thing inspectors really check,
As a professional I think it looks better to run the emt along the rafter then a "kick" or offset going into the fan box.
If you move the lower box over and run the EMT parallel with it attached to the deck this is exactly what I have in my living room.
Comment: For the fan box, it should either run along the bottom of the joist, or it needs to go a little higher than it is and you'll need a tight radius bender, +1
Comment: Installing EMT underground would be asinine. It would be rotted away completely in a year or two.
Comment: @drsparks, well it s code compliant and depending on the soil conditions will last much longer. , just a note for that don know there is really no code compliant "tight radius benders" infact there are some Chicago type benders that the 1/2" violates the minimum bend radius a sharp inspectors catch even these.
Comment: Soil conditions?? I mean water is the enemy of ferrous metal, so unless you live in a dessert, EMT, or even RMC, decidedly, is suicide
Comment: Actually maybe reading the code @drsparks nfpa70 358.10.B.1 severe corrosive influences ,,, this is not water but the soil conditions.
Answer: As long as the EMT remains our of direct exposure to rainfall you should be fine. I would never install it directly outdoors. It can certainly be run in free air as long as it's securely fastened within 3 ft of any box or terminal point and supported every 10 ft max. 1/2" EMT has a tendency to sag of supported at the bare minimum.
Comment: @tyler m  1 hole or 2 hole strap I would agree with . When you use tie-strap we want to make sure files don't think zip ties /or tie wraps can be used.
This is what I thought you were referring to at first read but believe you meant straps.
Comment: Not too worried about the EMT being outdoors (desert climate).  Securing within 3 ft of the box is probably the issue - I suppose I could install blocking between the rafters to secure it to?
Comment: @icurays1 is it not an option to support it from the ceiling? It looks like plywood above, you could use a tie-strap wrapped around the EMT and secured to the ceiling. Check out this "superstrut conduit and pipe hanger" https://www.homedepot.com/p/Superstrut-1-1-4-in-Conduit-and-Pipe-Hanger-6H2-1-2TB-15/207063286
Answer: One box solution
Slide the box to the left, and have the ceiling fan run come out of the right side of the box to a 90 degree conduit body (LB or elbow).  Either select a conduit body that's "just the right length" or just have a short EMT nipple there. Those particular EMT connectors are quite long, they make shorter ones.
Two box solution
Just get another box just like that one, and a Rigid (RMC) close nipple.  Mount the second box immediately to the left of the existing box, with just enough clearance so you can get the lids on.
That way, you can eat your cake and have it too! I.e. still get to hug the rafter, and also you won't have to move that existing line down the wall.
If you don't want 2 boxes, then replace the existing one with a 4x4 2-gang, then you can come out one of its side ports with a sweep or an LL/LR.
I just use 99 cent 4x4s, I don't really bother with those cast boxes unless it's in the weather.
Comment: So you could stay with your plan of hugging the rafter for a neater installation, not have to relocate the existing down-the-wall conduit, and also put your new line exactly where you want it.
Comment: Not sure what the purpose of the second box would be, I certainly don't need the extra space - I would just move this box over (10 minute job).
Comment: I see - no need to relocate exiting conduit, this is all new installation.
Answer: I would run along the rafter. It is a cleaner installation. Suspended conduit is fine if that's your only option and it's properly supported per your local code. Also openly suspended conduit is a path for critters and a perch for birds. You'll need a box at the fan that is designed to support the weight of the fan and for making elect. cconnection. Good luck!
Typical installation

EMT to outdoor ceiling fan


JavaScript MDN Tutorial - Example about floating point imprecision

Question: So I am looking at the JavaScript MDN re-intro tutorial and got to the point on Floating Point Imprecision.  https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
Why do they use this example?  Wouldn't you get that result in most all languages?
Comment: @j08691 that's why "if you're used to math in C or Java" sentence is wrong :)
Comment: @Sirko he wants to say the example isn't specific to javascript, he instead wants an example that works in other languages but not in javascript
Comment: @niceman Right, because I am used to math in C or Java, and the example they posted looks normal to me.
Comment: hmmm on second thought timbram, notice the dot after that sentence, I think that suggests they don't link java or C to the example but rather to the fact that javascript doesn't have integers
Comment: Some languages try to hide those problems from the user. JavaScript doesn't. Anyways, why would you take another example, if this simple one fits already?
Comment: Right, and since it specifically says, "if you're used to math in C or Java. Watch out for stuff like:" I would think that is the example they would give.  I am trying to make sure I am not missing something here.
Comment: [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken)
Answer: I think the documentation is just poorly structured. We have:
"There's no such thing as an integer in JavaScript, so you have to be a little careful with your arithmetic if you're used to math in C or Java."
This makes sense.  Then we have:
"Watch out for stuff like: 0.1 + 0.2 == 0.30000000000000004"
This also makes sense (as a general warning).
I think the documentation indented to have these as separate thoughts, but with the current formatting, it might taken as a a warning about floats specifically for C and Java programmers.
Comment: Ah okay that makes some sense. I was so confused at first glance!


How do i get the x/y coordinates of the first and last points of the drawn arc relative to the top left corner of the canvas?

Question: I have a square canvas with a width of 100 and a height of 100.
Within that square I draw an arc like so:
var canvas = document.getElementById('myCanvas');
var ctx    = canvas.getContext('2d');
ctx.clearRect(0,0,100,100) // clears "myCanvas" which is 100pixels by 100 pixels
ctx.beginPath();
ctx.arc( 50, 50, 30, 0, Math.PI*2/6 , false )
ctx.stroke();

The question is: How do i get the x/y coordinates of the first and last points of the drawn line relative to the top left corner of the canvas?
Answer: The starting point is trivially (x + radius, y). The ending point is, by simple trigonometrics, (x + radius*cos(angle), y + radius*sin(angle)). Note that the starting point in this case is a special case of the more general ending point, with angle equal to zero. These values also need to be rounded to the nearest integer, for obvious reasons.
(Note that this applies only when the anticlockwise argument is false, and assuming all coordinates are measured from the top left. If anticlockwise is true, reverse the sign of the second component of the y coordinate. If coordinates are measured from another corner, apply simple arithmetics to correct for this. Also note that this is completely backwards for any real mathematician.)
Comment: I'm pretty sure you're spot on, just to make sure I'm doing the right thing,because english is my second language, could you please elaborate the part where you say "reverse the sign of the second component of the y coordinate" ?
Comment: Well, if `anticlockwise` is true, we would have to replace the y coordinate with `y - radius*sin(angle)`, since it would effectively be mirrored in the x axis. Thus, reverse the sign. (I admit, it was a needlessly complicated wording)
Comment: Thank you by the way. Solved all my woes.


Is there an end to the Hall of Trials?

Question: I recently purchased Recettear, and I was wondering if anyone could tell me if there is an end to the Hall of Trials. I've so far made it to the third floor of the dungeon before dying. It says that if you die, you can only bring one item you found back out with you, but if you finish, you can bring everything. I'd really like to nicely stock my item shop, but I'm wondering when the end is in sight!
Comment: You've gone a long way since this question. :p
Answer: The dungeon ends on level 5.
Comment: technically, it only had 4 dungeon levels... as level 5 is *different* in a good way ;)
Answer: There certainly is an end to the hall of Trials, it is simply the introduction dungeon.
Just keep on pressing and you find it soon enough.
Answer: Yes, 5th floor.

Is there an end to the Hall of Trials?


Creating an array of objects from arrays of nested objects

Question: I'm trying to create an array of objects from an array of objects in which has nested arrays. The nested arrays are going to be subsituted for the key name followed by a dot:
for example:
const data = [ id: 5, name: "Something", obj: { lower: True, higher: False } ]
result = ["id", "name", "obj.lower", "obj.higher"]

I could manage to key the nested keys and values, but I can't seem to get the objs from the array.
For example (expected result):
const data = [ id: 5, name: "Something", obj: { lower: True, higher: False } ]
const newData = [{id: 5}, {name: "Something"}, {obj.lower: True}, {obj.higher: False}]

I have attempted:
 getValues = object => Object.entries(object).flatMap(([k, v]) => {
    if (typeof v !== "object") {
      return {[k]: v}
    }
    return v && typeof v === 'object' ? this.getKeys(v).map(s => `${k}.${s}`) : [k];
  });

I will be comparing these filtered array of objects with a user data that seems like this:
export const requiredKeys = {
  data: {
    id: null,
    status: null,
    summary: null,
    // "updated_by.id": null,
    // "updated_by.firstname": null,
    // "updated_by.lastname": null,
    // "updated_by.username": null,
    // "updated_by.blocked": null,
    // "pillars.pillarsType": null,
    // "student.created_by": null,
    // state: null,

Comment: Do you really want to get an array of little objects, each having only one property? That doesn't seem useful. Why not a single plain object with many key/value pairs?
Comment: it is because the sizes will vary, an the user will be able to select only some keys from the main array. I will need to make a comparsion between two objects, and I will filter the values later on, based on the similarity of these two objects
Answer: You could map the key/values or the pairs of the nested objects. From this entries get a new objects.

const
    getEntries = object => Object
        .entries(object)
        .flatMap(([k, v]) => v && typeof v === 'object'
            ? getEntries(v).map(([l, v]) => [`${k}.${l}`, v])
            : [[k, v]]
        ),
    data = { id: 1, item: "Item 001", obj: { name: 'Nilton001', message: "Free001", obj2: { test: "test001" } } },
    result = getEntries(data).map(pair => Object.fromEntries([pair]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Window air conditioner between living room and enclosed porch

Question: It seems like the best place to install the 12,000 BTU air conditioner in our house is in a window in the living room. On the other side of that window is an enclosed porch, approx 27x7 feet. Because the windows jut out into the room, there would be about 4-5 feet between the end of the AC and a window. Here's a diagram of the house. The porch is the lower part and the red is where the AC will go
The online consensus seems to be that installing a window AC between two rooms like this is bad news but I'm wondering if it might be more useful in this situation since the porch has some airflow and the unit would be relatively close to a window. I have two main concerns: airflow and drainage.
Drainage seems relatively easy, as I could hook a hose up to the bottom of the unit and run the water right out a window.
Airflow seems the larger issue. Even though it's almost entirely windows, would the porch heat up so fast that it would ruin efficiency (and maybe the AC unit condenser)? And if that's the case, could I try to run a duct from the back of the AC to the window about four feet away? Would that make it feasible or should I just find another window?
Your thoughts? Thank you!
Comment: A window unit is cheap, but exhausting onto a closed porch would make the porch unbearably hot, humid, and noisy. Look at low end mini-split a/c units that can run on 120 V, are quiet, can fit in a wall requiring only a 3 inch diameter hole between the air handler inside and the condensing unit outside. This hole is for the refrigerant lines, power, and condensate drain.
Comment: I believe you would definitely have to have a duct going from the condenser coils output to the window. The water could be carried outside in tubing, but the whole thing would still be noisy and would make the porch a very unpleasant space to be in.
Comment: That might work for us, @JimStewart as we never go out there. It's basically a room for junk. I will look into a mini-split system regardless but not sure we're in a position to buy new right now. If we set up a duct, would I do it from the very end of the AC unit to the window so air still flows through the vents on the side of the unit, or should the duct basically go from window all the way to window?
Comment: I believe that air flows into the unit through the side vents, or at least through one of the side vents, then out the back and maybe out the other side too. Note that the air flow paths inside and outside are completely  separate from each other. The hot air flowing out the back came from outside through one (or both?) of the outside side vents.  On the inside air flows into the unit (usually at the bottom), passes over the cold evaporator coils, and then back into the room (usually at the top).
Answer: If you have a forced air furnace for heating, you could install the window unit in another window and run the furnace fan to circulate the conditioned air throughout the house. My son did this in his first house. As for using the window you mentioned, you could do it your way if you can insure good air flow in and out of the porch area to keep that area the same temperature as the outside. Window fan/fans, may be needed. If the porch area heats and has  high humidity that will affect the operation of the A/C unit and could ruin the porch area. All window A/C units produce lots of heat and humidity when operating. So you will have to make sure you address these issues. A split system or other type of cooling unit would be preferred. Depending on where you live a 12,000 BTU unit may be a little undersized.
Answer:
If we set up a duct, would I do it from the very end of the AC unit to
  the window so air still flows through the vents on the side of the
  unit . . .?

I would say yes.  And open windows near the sides, i.e., away from where the heated a/c air goes out the window.
Comment: I've seen a throogh window air-con installed in an interior  room with ducting carring the hot exhaust across two offices to the exterior of the building, the drain went into a sink. its purpose was to a small computer room cool, so the noise wasn't a problem.


Should I play the predecessors before Assassin's Creed III?

Question: I'm thinking about trying out Assassin's Creed III, but wondering if I should play through the predecessors first.
Are they important to the story? Is there lots of things in AC3 I won't really get unless I have played through all of it?
And if so, which should I play through in what order and are they all available through Steam?
Comment: I think a prequel is typically something that comes out after the original, but chronologically occurs before the original.  Predecessor would probably be a better word in the context that you used prequel.
Comment: @Derp I'm not sure what you mean by "the stories they're based from," but, Star Wars Eps. 1-3 were prequels because they were created *after* 4-6. Assassin's Creed (1, 2, BH, etc) was released in sequential order, so they would not be prequels. turbo has the right of it by calling them predecessors.
Comment: These aren't "[prequels](http://en.wikipedia.org/wiki/Prequel)", they came out before the third game...
Comment: @Derp They came out after the original so they would be prequels
Comment: What are they then? I've always though of sequel and prequel to be sort of before and after, irregardless of when it was released.
Comment: [Wiktionary](http://en.wiktionary.org/wiki/prequel) "Prequel: In a series of works, an installment that is set chronologically before its predecessor, especially the original narrative or (perhaps improper usage) any narrative work with at least one sequel.  Most often used, not as a direct antonym of sequel, to refer to earlier works in a series, but to refer to works that are chronologically before but are created and released after; an archetypal example is the Star Wars prequel trilogy."
Answer: There are plenty of things you might not get if you played it without having an idea of the prequels. However, I wouldn't necessarily recommend playing them to get the story.
The first one is incredibly repetitive and involves many menial tasks whilst the second one struggles in aspects of the story line.
Strictly speaking, there won't necessarily be things you won't get, just things you won't notice. Most games are developed so that you would be able to understand the plot without having to play previous games (although I think most people would struggle with Metal Gear Solid 4).
I'd recommend either reading the wikis for the plots or there is a handy video here that will sum up everything brilliantly. (Obviously, don't watch if you wish to play the games instead)
Comment: @turbo I agree. Plus, in playing from the beginning, you can really tell how Ubisoft adapted to the desires of their community. Each game was, in my opinion, progressively better than the one before it. So, do you *need* to play the first three? No. *Should* you play them? Yes. =P
Comment: AC3 also has a video that catches you up to the overall plot when you start a new game.
Comment: I played AC3 with no previous knowledge of the series and found it quite enjoyable... I think I only looked up one thing the entire game and it was minor.
Comment: "the second one struggles in aspects of the story line" This is crazy talk, the second one is all-around awesome.
Comment: Despite it not being necessary, if you can pick the predecessors up for cheap, I'd highly recommend playing them!  I believe yesterday there was an Amazon lightning deal for 2/brotherhood/revelations all for $30. You don't have to do much besides the story missions, but I found them to all be very enjoyable, especially in the way that they use (bend) history.
Comment: @Derp - I thought AC2 had pretty much universal praise.  It's still sitting at 91% on Metacritic for crying out loud. ;3
Comment: @Shinrai And does that review cover all aspects or specifically the story line?
Answer: It's not really necessary to play the previous games but if you do you'll surely have a deeper experience with the story. You can also take a look at The Assassin's Creed Wiki. The main games previous to the third are (in order): AC, AC2, AC Brotherhood and AC Revelations.
Answer: There is a very interesting article that answers this question:
http://www.usgamer.net/articles/which-assassins-creed-should-i-start-with-a-gateway-guide
Basically, you can skip one and go for ACII. I started AC the first 8 years ago, but never finished it. I decided now to re-start and it looks like ACII is much better than ACI with faster action. Starting there won't affect you.
Answer: Yeah, kinda for the Desmond part. But no for the Connor part of the story.


How to let the Navigation Bar (and maybe other stuff) end on the right

Question: So I've got a problem with a navigation bar. I've set its width to 100%. But I would like to see the end, because it's got rounded corners...
So like this: | (=======) |
Not like it's now: | (==========|

    #nav {

      height: 60px;

      font-size: 30px;

      line-height: 60px;

      vertical-align: middle;

      text-align: center;

      background-color: #0080FF;

      width: 100%;

      border: 10px solid #16044E;

      border-radius: 20px;

      z-index: 1;

    }

    #nav ul {} #nav li {

      display: inline;

      text-align: center;

      margin: 20px;

    }

    #nav a {

      color: white;

      text-decoration: none;

    }

Home

Courses

Subjects

Sign Up

Log In

Comment: @HydraCles Use `@` followed by the person's name to send them a notification about your message
Comment: The surrounding container needs a width too.
Answer: You can use calc to reduce 10px from the total width (10px = border-width) But you should try box-sizing:border-box as the browser support for calc is limited Caniuse

#nav {
    height: 60px;
    font-size: 30px;
    line-height: 60px;
    vertical-align: middle;
    text-align: center;
    background-color: #0080FF;
    width: calc(100%-10px);
    border: 10px solid #16044E;
    border-radius: 20px;
    z-index: 1;
}

#nav ul {
}

#nav li {
    display: inline;
    text-align: center;
    margin: 20px;
}

#nav a {
    color: white;
    text-decoration: none;
}

Home

Courses

Subjects

Sign Up

Log In

Comment: Thank you. Solved :) - I can't give you 'This solved my problem' yet. But I'll give it as soon as possible :3.
Comment: @Akshay: You should add a note about current support of `calc()`: http://caniuse.com/#search=calc
Answer: Add this to your #nav
box-sizing: border-box;

That will make your width: 100%; apply to the border part as well.
Answer: You can use the calc() CSS function with a callback in case you need to support older browsers, here is the current support, and you have to add this to your #nav:
#nav{
    width: 98%;
    calc(100%-10px);
}

Another approach is changing the box-sizing of the #nav element, so the border will be part of the element width, you may have do update few rules in the CSS but it will work in IE8+, all mobile, and all modern browsers, here the caniuse:
#nav{
    padding-left: 10px;
    width: 100%;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

Answer: Change #nav as follows:
Change width: 100%; to width: auto;
Your #nav should look like this:
#nav {
    height: 60px;
    font-size: 30px;
    line-height: 60px;
    vertical-align: middle;
    text-align: center;
    background-color: #0080FF;
    width: auto;
    border: 10px solid #16044E;
    border-radius: 20px;
    z-index: 1;
}


How to pass hours and minutes to date command through -d option

Question: I know how to format a date in bash using the date command
date -d 20160304 +%Y%m%d

for example.  But now I want to pass a date and time and return the hours and minutes.  I know the output format I need is +%H%M, but I don't know how to format the date string and it is not in the man pages.
For example if I try any of these:
 date -d 201801010500 +%H%M
 date -d 20180101_0500 +%H%M
 date -d 2018-01-01_0500 +%H%M
 date -d 2018:01:01-05:00 +%H%M

I get an "invalid date" error.  When I search google I always find answer referring to the output format, not the input format...
Comment: `man date` is mandate.
Comment: Note that we need quotes around any argument that has spaces in it.
Answer: GNU date accepts these format, among others I'm sure
$ date -d '2018-02-16 12:34'
Fri Feb 16 12:34:00 EST 2018
$ date -d '2018-02-16T12:34:56'
Fri Feb 16 12:34:56 EST 2018
$ date -d '2018-02-16T12:34:56Z'
Fri Feb 16 07:34:56 EST 2018

In general, can't go wrong with ISO8601 time formats
I'm in Canada/Eastern time zone
Answer: The date utility is pretty impressive in making sense of different arguments for the -d option.
Here is just one example:
$ date -d "20180101 05:00:00"
Mon Jan  1 05:00:00 +07 2018

Note +07 is the local timezone.


How to load faster Parent Activity from Child Activity?

Question: actionBar.setHome function calls Application Home Activity. When it is calling, it's just like re-opening the app. I mean I have to wait to load Home Activity. I think there may be a way not to re-load, re-load Home Activity but to Home Activity hidden or store memory for Home Activity. Home Activity has font embedded,two tabs and buttons. When a button from Home Activity, the activity goes to another activity in which actionBar.setHome function redirect Home Activity just like re-loading it.

Child Activity code:
public void onCreate(Bundle savedInstanceState) {
.......................
.......................
actionBar.setHomeAction(new IntentAction(this, createIntent(this),
            R.drawable.ic_title_home_default));
  }
  //calling Parent Activity
   private static Intent createIntent(Context context) {
    Intent i = new Intent(context, CustomTabActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    return i;
  }

Logcat after calling Home Activity from another activity:
04-14 22:20:49.788: I/ActivityManager(245): Starting: Intent { flg=0x4000000 cmp=com.joshclemm.android.tabswithactivity/.CustomTabActivity } from pid 30761
04-14 22:20:49.838: D/szipinf(30761): Initializing inflate state
04-14 22:20:49.898: D/szipinf(30761): Initializing inflate state
04-14 22:20:49.908: D/szipinf(30761): Initializing inflate state
04-14 22:20:49.918: D/szipinf(30761): Initializing inflate state
04-14 22:20:49.928: D/szipinf(30761): Initializing inflate state
04-14 22:20:49.938: D/szipinf(30761): Initializing inflate state
04-14 22:20:49.958: D/szipinf(30761): Initializing inflate state
04-14 22:20:49.968: D/szipinf(30761): Initializing inflate state
04-14 22:20:49.978: D/szipinf(30761): Initializing inflate state
04-14 22:20:49.988: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.008: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.018: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.028: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.038: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.048: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.068: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.078: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.088: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.098: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.118: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.128: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.138: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.148: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.158: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.178: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.188: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.198: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.208: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.228: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.238: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.248: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.258: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.268: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.288: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.298: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.308: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.318: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.338: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.348: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.568: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.648: D/szipinf(30761): Initializing inflate state
04-14 22:20:50.678: D/skia(30761): purging 191K from font cache [28 entries]
04-14 22:20:50.718: D/skia(30761): purging 192K from font cache [27 entries]
04-14 22:20:50.978: I/ActivityManager(245): Displayed com.joshclemm.android.tabswithactivity/.CustomTabActivity: +1s172ms

What additional codes are needed in Home Activity Class-> OnCreate() or whatever method not to try re-load if once already loaded?
Or how to let Home Activity hidden if the function calls another activity?
Answer: Shit I solve my questions myself. Whatever thank you all viewers of this questions.
public void onCreate(Bundle savedInstanceState) {
.......................
.......................
actionBar.setHomeAction(new IntentAction(this, createIntent(this),
            R.drawable.ic_title_home_default));
  }
  //calling Parent Activity
   private static Intent createIntent(Context context) {
    Intent i = new Intent(context, CustomTabActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    return i;
  }

Change is: FLAG_ACTIVITY_REORDER_TO_FRONT


Why does my react page go back without the button being clicked?

Question: I have a bar at the top of my react page that displays the order number and I would also like it to contain a back button.
I have the following code but when I navigate to this page it flashes up and automatically goes back to the previous page without the button being pressed. Can someone please tell me what I have done wrong?
import React from "react";
import {  Link} from "react-router-dom";

class Messages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      isLoading: false,
    };
  }

  componentDidMount() {
    this.setState({ isLoading: true });
    const proxyurl = "https://cors-anywhere.herokuapp.com/";
    const url =
      "myURL" +
      this.props.location.state.rollNumber;
    fetch(proxyurl + url)
      .then((res) => res.json())
      .then((data) => this.setState({ data: data, isLoading: false }));
  }

  render() {
    const { data, isLoading } = this.state;

    if (isLoading) {
      return
Loading ...
;
    }

    if (data.length === 0) {
      return
 no data found
;
    }

    return (

 Order number: {this.props.location.state.orderId}

<button onClick={this.props.history.goBack()}>return to all orders</button>

Comment: Try this - `onClick={this.props.history.goBack}`
Answer: You shouldn't execute the function inside the onclick
<button onClick={this.props.history.goBack}>return to all orders</button>

Answer: Instead use onClick={this.props.history.goBack} you can use the code below:

    <Link to="/"}>return to all orders</Link>

Answer: Beceause since you wrote the code this way
<button onClick={this.props.history.goBack()}

when the component is mounted the function goBack() will be executed directly
it's like you put
{state.someArray.map(item => Name :{item.name})}

will render =>
Name: myName0
Name: myName1
Name: myName3

in the jsx, when you load the page you will see x times the Name and his values. It's executed directly.
Try to write this way
<button onClick={() => this.props.history.goBack()}

Or what UKS wrote.
This way, it will avoid the function to be launched directly when the component is mounted, and only be triggered when you click on it. Let me know if this helps


Automatic translation before serialization in symfony2 with JMSSerializerBundle

Question: I have some logic to apply after getting entities from database( by findAll() ) and before serializing the result to json.
I want to add translation on some fields. I know that I can do it manually by iterating on each entity and apply my logic in controller. But I need a better way to do it.
Is there a suggestions to make this automatic ?
Answer: I've got similar problem and tried to resolve this using custom handler but with no success, so i created compiler pass and override JsonSerializationVisitor where string values are serialized with TranslatableJsonSerializationVisitor class:
namespace tkuska\DemoBundle\Serialization;
use JMS\Serializer\JsonSerializationVisitor;
use JMS\Serializer\Context;

class TranslatableJsonSerializationVisitor extends JsonSerializationVisitor
{
    /**
     * @var \Symfony\Component\Translation\Translator;
     */
    private $translator;

    public function visitString($data, array $type, Context $context)
    {
        if (in_array('translatable', $type['params'])) {
            return (string) $this->translator->trans($data);
        }
        return (string) $data;
    }

    public function setTranslator(\Symfony\Component\Translation\Translator $translator)
    {
        $this->translator = $translator;
    }
}

and compiler:
namespace tkuska\DemoBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class TranslatableJsonSerializationCompiler implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $jmsJsonSerializationVisitor = $container->getDefinition('jms_serializer.json_serialization_visitor');
        $jmsJsonSerializationVisitor->setClass('tkuska\DemoBundle\Serialization\TranslatableJsonSerializationVisitor');

        $jmsJsonSerializationVisitor->addMethodCall('setTranslator', array(new Reference('translator')));
    }
}

in entity i set annotation for type 'string' with param 'translatable'
/**
 * @VirtualProperty
 * @Groups({"details"})
 * @Type("string<'translatable'>")
 * @return order status
 */
public function getOrderStatus(){
    return 'status.ordered';
}

Of course 'status.ordered' is my translation key.
Answer: Thank you @zizoujab. Very useful post. I made a small improvement to it to call parent method and to unset my parameters, so that i can use this way of altering data on more complex types like array, that already have parameters and used
/**
 * @VirtualProperty
 * @Groups({"details"})
 * @Type("string<translatable>")
 * @return order status
 */

instead of
/**
 * @VirtualProperty
 * @Groups({"details"})
 * @Type("string<'translatable'>")
 * @return order status
 */

to convert the string 'translatable' into a parameter name instead of parameter value thus you can pass more complex parameters like this, and allow me to unset this parameters before calling the parent method.
/**
 * @VirtualProperty
 * @Groups({"details"})
 * @Type("string<translatable<set of parameters>>")
 * @return order status
 */

Code:
<?php

namespace Mktp\DefaultBundle\Service\JmsSerializer;

use JMS\Serializer\Context;
use JMS\Serializer\JsonSerializationVisitor;
use Symfony\Component\Translation\Translator;

class TranslatableJsonSerializationVisitor extends JsonSerializationVisitor
{
    /**
     * @var Translator;
     */
    private $translator;

    /**
     * @param string $data
     * @param array $type
     * @param Context $context
     * @return string
     */
    public function visitString($data, array $type, Context $context)
    {
        $translatable = $this->getParameters('translatable', $type['params']);
        if (count($translatable)) {
            $data = (string)$this->translator->trans($data);
        }
        return parent::visitString($data, $type, $context);
    }

    /**
     * @param array $data
     * @param array $type
     * @param Context $context
     * @return array|\ArrayObject|mixed
     */
    public function visitArray($data, array $type, Context $context)
    {
        $translatable = $this->getParameters('translatable', $type['params']);

        if (count($translatable)) {
            foreach ($data as $key => $value) {
                if (is_string($value)) {
                    $data[$key] = (string)$this->translator->trans($value);
                }
            }

        }
        return parent::visitArray($data, $type, $context);
    }

    /**
     * @param Translator $translator
     */
    public function setTranslator(Translator $translator)
    {
        $this->translator = $translator;
    }

    /**
     * @param string $type
     * @param array $parameters
     * @param bool $unsetParameters
     * @return array
     */
    protected function getParameters($type, &$parameters, $unsetParameters = true)
    {
        $result = array();
        foreach ($parameters as $key => $parameter) {
            if ($parameter['name'] == $type) {
                $result[] = $parameter;
                if ($unsetParameters) {
                    unset($parameters[$key]);
                }
            }
        }
        $parameters = array_values($parameters);
        return $result;
    }
}


Finding Green's Functions

Question: Well, I'm trying to understand how to find Green's functions for differential operators, and I'm working on the problem $Lu=-u''$ with BC's $u'(0)=u(1)=0$.  Can someone tell me if I'm doing this correctly?  In the end, I am getting that the Green's function is defined as $g(x)=(1-t)H(t-x)+(1-x)H(x-t)$ where $H(x-t)$ is the heaviside function.  Basically, the main idea is to make the function continuous at x = t and satisfy the derivative jump discontinuity, correct?
Comment: Yes, that is correct as far as I can tell.  That said, I have no idea what you did to get there.
Answer: The main idea is to satisfy the equation $$-g''=\delta_t\tag{1}$$ The fact that Green's function is continuous is something special to your one-dimensional situation; don't get too used to it. In higher dimensions, Green's functions for the Laplacian are unbounded near $t$.
Recalling that $\delta_t$ is the (distributional) derivative of $H(x-t)$, we integrate (1) to get
$$-g'(x) = H(x-t)+A\tag{2}$$
for some constant $A$. Integrate (2) again:
$$-g(x) = (x-t)^+ +Ax +B \tag{3}$$
where $(\cdot )^+ = \max(0,\cdot)$. It remains to find $A$ and $B$ to satisfy the boundary conditions. Plug $x=0$ into (2) to get
$$ 0 = 0 +A$$
hence $A=0$. Plug $x=1$ into (3) to get
$$0 = 1-t +B $$
hence $B=t-1$.
Rewrite (3) with this new information: $-g(x) = (x-t)^++t-1$, or
$$g(x)=1-t-(x-t)^+ \tag{4}$$
I find (4) easier to parse than the formula in your post. Also, (4) makes it clear that $g$ is  (Lipschitz) continuous, which is not immediate from your formula involving discontinuous $H$.
Comment: This is an old answer, but can anyone argue to be why the Green function in higher dimensions is unbounded "near t"?

Finding Green's Functions


How to make items in a DockPanel expand to fit all available space in WPF?

Question: I have a StackPanel containing a StackPanel and some other items. The first StackPanel has a vertical orientation, the the inner one has a horizontal orientation. The inner one has a TreeView and a ListView, I would like them to expand and fit the width of the window, which I set by the window and allow the user to change. I would also like the outer StackPanel to fit the height of the window. How do I do this?
Edit:
I've converted to using a DockPanel, and I've set the DockPanel.Dock properties correctly in each of the elements, and have disabled LastChildFill in both of the dockpanels, the layout still does not stretch.
The Code:
<Window x:Class="Clippy.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="400" Width="600" MinHeight="400" MinWidth="600" Loaded="Window_Loaded" SizeChanged="Window_SizeChanged">
    <DockPanel Name="wrapperDockPanel" LastChildFill="False">
        <Menu Height="22" Name="mainMenu" Width="Auto" DockPanel.Dock="Top" />
        <ToolBar Height="26" Name="mainToolBar" Width="Auto" DockPanel.Dock="Top" />
        <DockPanel Height="Auto" Name="contentDockPanel" DockPanel.Dock="Top" LastChildFill="False">
            <TreeView Name="categoryTreeView" />
            <ListView Name="clipListView" />
        </DockPanel>
        <StatusBar Height="23" Name="mainStatusBar" DockPanel.Dock="Top" />
    </DockPanel>
</Window>

Comment: Why do you set LastChildFill="False" ? The default value of True would make the ListView fill up the space.
Answer: Use a DockPanel instead.  StackPanel explicitly doesn't care about visible space, whereas DockPanel does all of it's size calculation based on available space.
Update:
In addition, in my experience, putting the body of the window into a View, and only having the View in the Window makes for a better Auto Size experience.
For some reason putting all of the children directly into the Window seems to not auto size very well.
Update 2:
I would remove the explicit DockPanel.Dock attribute from the element that you want to stretch (fill) the unused space.
Answer: This should do it - I set it up so that the TreeView and the ListView shared the main view 50/50; if you don't want that, set it to 'Auto' and '*' or something. Use "LastChildFill" to your advantage!
<Window x:Class="Clippy.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="400" Width="600" MinHeight="400" MinWidth="600" Loaded="Window_Loaded" SizeChanged="Window_SizeChanged">

    <DockPanel LastChildFill="True">
        <Menu Width="Auto" DockPanel.Dock="Top" />
        <ToolBar Width="Auto" DockPanel.Dock="Top" />
        <StatusBar DockPanel.Dock="Bottom" />

        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="0.5*" />
                <RowDefinition Height="0.5*" />
            </Grid.RowDefinitions>

            <TreeView Name="categoryTreeView" Grid.Row="0" />
            <ListView Name="clipListView" Grid.Row="1" />
        </Grid>
    </DockPanel>

</Window>

Answer: Set width and height properties to "auto"


slow internet download on Ubuntu 15.10

Question: I installed on Ubuntu 15.10 on a fresh computer, and on the first 2 days, the wifi download speed was normal (torrent download was about 2mb/s).
But today, my download speed is no more than 100kb/s. I've tried most of the solutions posted online, but it doesn't seem to work.
I've just reformatted my computer and reinstalled Ubuntu 15.10 again, but the problem still persists.
I've also reset the modem as well.
What should I do?
Comment: It has nothing to do with the OS.
Answer: Try updating your network drivers
How to I update Ralink 5390 adapter driver via terminal?
Check the seeders/leechers for the torrent you are downloading.
try changing the trackers.
Try port forwarding (most likely the problem )
http://www.pcworld.com/article/244314/how_to_forward_ports_on_your_router.html

slow internet download on Ubuntu 15.10


Group default.plymouth is broken

Question: If I try to change the plymouth theme I get this error and plymouth is displayed only in text mode:
sudo update-alternatives --config default.plymouth

update-alternatives: warning: forcing reinstallation of alternative
/lib/plymouth/themes/ubuntu-logo/ubuntu-logo.plymouth because link group default.plymouth is broken.
update-alternatives: warning: not replacing /lib/plymouth/themes/default.plymouth with a link.

How to fix this?
I am using ubuntu 11.04
Answer: This error message indicates that you have somehow replaced the /lib/plymouth/themes/default.plymouth symlink, which is managed by the plymouth theme packages, with a real file.  Since you want to select a different theme, you can accomplish this by running:
sudo rm -f /lib/plymouth/themes/default.plymouth
sudo update-alternatives --config default.plymouth

If the contents of /lib/plymouth/themes/default.plymouth are something you care about preserving, you can move the file aside instead of removing it.
Answer: try to gksu nautilus and go to lib/plymouth/themes and open your default.plymouth file and make sure it has all the right filenames
[Plymouth Theme]
Name=INT2MIL-Ubuntu-10.10-Eng theme #this should right the name of the folder of your theme
Description=Ubuntu plymounth theme
ModuleName=script

[script]
ImageDir=/lib/plymouth/themes/INT2MIL-Ubuntu-10.10-Eng
ScriptFile=/lib/plymouth/themes/INT2MIL-Ubuntu-10.10-Eng/mdv.script

make sure it is correct and also check the directory for your current theme and see if any files are missing.
Ohh and instead of doing a sudo update-alternatives --config default.plymouth  you can edit the default.plymouth file and change the theme name, image directory and script directory to your new theme and the just sudo update-initramfs -u
And on your next boot you will see the new Plymouth splash if all went well. Good luck

Group default.plymouth is broken


Power series in a differential equation

Question: I have a differential equation that I'm having trouble wrapping my head around.
Use a power series to solve
$$
(1-x)y'(x) + y(x) = 0
$$
with the initial condition that $y(\frac{1}{2}) = 17.$
I've tried setting up the power series as $\sum_{k=0}^\infty a_k x^k$ and differentiating from there, but I'm not managing to land anywhere useful. Some pointers as to where to go from here would be appreciated.
Comment: Hint: Most of your terms will end up vanishing, there is no recurrence relation.
Answer: Let's instead use the series
$$y=\sum_{k\ge0}a_kz^k\implies y'=\sum_{k\ge0}(k+1)a_{k+1}z^k$$
where $z=x-\frac12$. This is so we can make use of the given initial value; if $x=\frac12$, then all but the constant terms in the series vanish, so $y\left(\frac12\right)=a_0=17$. The ODE becomes
$$\left(\frac12-z\right)y'+y=0$$
Plug in the series:
$$\begin{align*}
0&=\left(\frac12-z\right)y'+y\\[1ex]
&=\frac12\sum_{k\ge0}(k+1)a_{k+1}z^k-\sum_{k\ge0}(k+1)a_{k+1}z^{k+1}+\sum_{k\ge0}a_kz^k\\[1ex]
&=\frac12\left(a_1+\sum_{k\ge1}(k+1)a_{k+1}z^k\right)-\sum_{k\ge1}ka_kz^k+\left(a_0+\sum_{k\ge1}a_kz^k\right)\\[1ex]
&=\frac{a_1}2+a_0+\sum_{k\ge1}\left(\frac12(k+1)a_{k+1}-(k-1)a_k\right)z^k
\end{align*}$$
It follows that
$$\frac{a_1}2+a_0=0\implies a_1=-34$$
The remaining coefficients are governed by the recurrence relation,
$$\frac12(k+1)a_{k+1}-(k-1)a_k=0\implies a_{k+1}=\frac{2(k-1)}{k+1}a_k$$
Notice that when $k=1$, we have $a_2=0$, and this forces $a_n=0$ for all $n\ge2$.
Hence

 $$y(z)=17-34z\iff y(x)=34-34x$$
Comment: Thank you! One minor question. I'm having a bit of trouble parsing the last step of the plug-in (before "It follows that...") I see that you're taking the first element out of the 3/2 series, but the others aren't connecting for me right now. Would you mind explaining that step a bit further? Thanks again!
Comment: I've added a step to clarify what happened. It's just a matter of adjusting the starting index of each series so that we can condense all three into one. (Incidentally, I seemed to have dropped a factor of $\frac32$, which I'll fix now.)
Comment: I see, thank you!

How about that x^k on the same line? Is that meant to be z^k, or do you already swap back to x here?

Also, just to make sure I understand: How does it follow that the first two terms are equal to zero?
Comment: Yes, that's a typo. All coefficients are equal to $0$ because the left hand side is $0$. We're essentially equating two polynomials, which are equal if the coefficients of same-degree terms are equal.
Comment: One more typo; with $z=x-\frac12$, we should have $1-x=\frac12-\left(x-\frac12\right)=\frac12-z$. I've corrected this, too.

Power series in a differential equation


Prove indexed set and Cartesian product

Question: I have a problem as follows:

And this is my work:

Can some one suggest a way to do the opposite direction:
Starting with: Conversely, suppose $P\ \in\bigcup{\ (A}_i\times\ S)$ for some $i\ \in I$.
Thank you so much!
Comment: @BrianM.Scott Thank you, I do sometimes just reverse my steps but need to make sure I do not make any misconception "assuming the conclusion in order to prove the conclusion"
Comment: You can actually just reverse your steps; Mark Saving's answer does exactly that.
Answer: Suppose $P \in \bigcup\limits_{i \in I} (A_i \times S)$. Then take some $i \in I$ such that $P \in A_i \times S$. Then we can write $P = (a, s)$ for $a \in A_i$ and $s \in S$. Then $a \in \bigcup\limits_{i \in I} A_i$. Then $P = (a, s) \in (\bigcup\limits_{i \in I} A_i) \times S$.
Thus, we see that $\bigcup\limits_{i \in I} (A_i \times S) \subseteq (\bigcup\limits_{i \in I} A_i) \times S$.

Prove indexed set and Cartesian product