text:
Q: Android: Socket not connecting and throws exception I am having the following Android code which connects with a web socket program. Web Socket is running on as Java application. Both socket and android code is in Eclipse.
The problem is, Android program is not connecting this socket at all. It is handled under button click as mentioned in the code below. After this line socket = new Socket("192.168.1.21", 8081);  it is throwing to exception, not sure why. I tried to refer all sample code from internet, but i couldn't see any strange issue in the below code.
Could someone please help me on solving this please?
Android code:
mHandler = new Handler();

clientthread = new ClientThread();

        Button connectBtn = (Button) findViewById(R.id.button2);
        connectBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //Start contacting Socket
                 mHandler.post(mUpdate);

}
        });

private Runnable mUpdate = new Runnable() {

    public void run() {

            try {

                clientthread.run();

                pw = new PrintWriter(socket.getOutputStream(), true);
                EditText randTxtField = (EditText) findViewById(R.id.editText1);
                        pw.println(randTxtField.getText().toString());
                                pw.flush();

                }
                catch (Exception ex) {
                    ex.printStackTrace();
                }

                // Read randrom ID returned by Socket
                BufferedReader socketReader;
                try {
                    socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    msgStr = socketReader.readLine();
                    Log.d("msgStr: ", msgStr);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

    }

    };

class ClientThread implements Runnable {
        @Override
        public void run()
        {

            try {
             // Exception throw when executing this line itself...
                socket = new Socket("192.168.1.21", 8081);
            }
            catch (UnknownHostException e1) {
                e1.printStackTrace();
            }
            catch (IOException e1) {
                e1.printStackTrace();
            }

         }
    }

Exception:
 03-24 14:51:54.672: D/dalvikvm(21673): GC_FOR_ALLOC freed 295K, 4% free 9800K/10128K, paused 19ms, total 20ms
03-24 14:54:19.974: D/socketServerIP(21673): 192.168.1.21
03-24 14:54:19.984: W/System.err(21673): android.os.NetworkOnMainThreadException
03-24 14:54:19.984: W/System.err(21673):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
03-24 14:54:19.984: W/System.err(21673):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
03-24 14:54:19.984: W/System.err(21673):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
03-24 14:54:19.984: W/System.err(21673):    at libcore.io.IoBridge.connect(IoBridge.java:112)
03-24 14:54:19.984: W/System.err(21673):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
03-24 14:54:19.984: W/System.err(21673):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
03-24 14:54:19.984: W/System.err(21673):    at java.net.Socket.startupSocket(Socket.java:567)
03-24 14:54:19.984: W/System.err(21673):    at java.net.Socket.<init>(Socket.java:226)
03-24 14:54:19.984: W/System.err(21673):    at com.example.cobrowseandroid.RandomIDActivity$ClientThread.run(RandomIDActivity.java:262)
03-24 14:54:19.984: W/System.err(21673):    at com.example.cobrowseandroid.RandomIDActivity$1.run(RandomIDActivity.java:152)
03-24 14:54:19.984: W/System.err(21673):    at android.os.Handler.handleCallback(Handler.java:733)
03-24 14:54:19.984: W/System.err(21673):    at android.os.Handler.dispatchMessage(Handler.java:95)
03-24 14:54:19.984: W/System.err(21673):    at android.os.Looper.loop(Looper.java:136)
03-24 14:54:19.984: W/System.err(21673):    at android.app.ActivityThread.main(ActivityThread.java:5017)
03-24 14:54:19.984: W/System.err(21673):    at java.lang.reflect.Method.invokeNative(Native Method)
03-24 14:54:19.984: W/System.err(21673):    at java.lang.reflect.Method.invoke(Method.java:515)
03-24 14:54:19.984: W/System.err(21673):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-24 14:54:19.984: W/System.err(21673):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-24 14:54:19.984: W/System.err(21673):    at dalvik.system.NativeStart.main(Native Method)
03-24 14:54:19.984: D/AndroidRuntime(21673): Shutting down VM
03-24 14:54:19.984: W/dalvikvm(21673): threadid=1: thread exiting with uncaught exception (group=0x415efba8)
03-24 14:54:19.984: E/AndroidRuntime(21673): FATAL EXCEPTION: main
03-24 14:54:19.984: E/AndroidRuntime(21673): Process: com.example.cobrowseandroid, PID: 21673
03-24 14:54:19.984: E/AndroidRuntime(21673): java.lang.NullPointerException
03-24 14:54:19.984: E/AndroidRuntime(21673):    at com.example.cobrowseandroid.RandomIDActivity$1.run(RandomIDActivity.java:179)
03-24 14:54:19.984: E/AndroidRuntime(21673):    at android.os.Handler.handleCallback(Handler.java:733)
03-24 14:54:19.984: E/AndroidRuntime(21673):    at android.os.Handler.dispatchMessage(Handler.java:95)
03-24 14:54:19.984: E/AndroidRuntime(21673):    at android.os.Looper.loop(Looper.java:136)
03-24 14:54:19.984: E/AndroidRuntime(21673):    at android.app.ActivityThread.main(ActivityThread.java:5017)
03-24 14:54:19.984: E/AndroidRuntime(21673):    at java.lang.reflect.Method.invokeNative(Native Method)
03-24 14:54:19.984: E/AndroidRuntime(21673):    at java.lang.reflect.Method.invoke(Method.java:515)
03-24 14:54:19.984: E/AndroidRuntime(21673):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-24 14:54:19.984: E/AndroidRuntime(21673):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-24 14:54:19.984: E/AndroidRuntime(21673):    at dalvik.system.NativeStart.main(Native Method)

A: You should not invoke network stuff on UI thread.
you are calling
mHandler.post(mUpdate)
which runs in current thread (UI thread) method "run". use for e.g. instead:
Thread t = new Thread(mUpdate);
t.start();

to run network code in separated thread...
Also then don't forget to call UI related code in UI thread (for e.g. getActivity().runOnUiThread()).


text:
Q: Python If-statement returning ValueError I'm using Python3 to call an API to get a list of trains if certain conditions are met it sends me a notification on pushover.
The list I receive looks like this:
[
    {
        "Car": "8",
        "Destination": "Vienna",
        "DestinationCode": "K08",
        "DestinationName": "Vienna/Fairfax-GMU",
        "Group": "2",
        "Line": "OR",
        "LocationCode": "D1",
        "LocationName": "Town",
        "Min": "4"
    },
    {
        "Car": "8",
        "Destination": "NewCrltn",
        "DestinationCode": "D13",
        "DestinationName": "New Carrollton",
        "Group": "1",
        "Line": "OR",
        "LocationCode": "D1",
        "LocationName": "Town",
        "Min": "6"
    },
    {
        "Car": "6",
        "Destination": "Vienna",
        "DestinationCode": "K08",
        "DestinationName": "Vienna/Fairfax-GMU",
        "Group": "2",
        "Line": "OR",
        "LocationCode": "D1",
        "LocationName": "Town",
        "Min": "BRD"
    }
]

I have the following for loop and nested if statement to narrow down trains that are going to K08, don't have an 'ARR', 'BRD', or null for the 'Mins' variable, and within 10-20 mins:
for x in list:

        if x['DestinationCode'] == "K08":

                if x['Min'] != "" or "ARR" or "BRD":

                        if int(x['Min']) > 10 and int(x['Min']) < 20:
                                #pushover script

The first if statement works on the Destination variable. However, I get the following error on any with ARR, BRD, or null:
Traceback (most recent call last):
  File "./test.py", line 23, in <module>
    if int(x['Min']) > 10 and int(x['Min']) < 15:
ValueError: invalid literal for int() with base 10: 'BRD'

This leads me to believe that my nested if is passing 'ARR', 'BRD', and Null to the final if statement which will not accept anything but integers.

A: This is explained very well aswell in this SO answer, thanks @MisterMiyagi
The problem is that some unexpected values for x['Min'] seem to appear, while you thought you filtered them out. In fact, one of your boolean is misleading:
if x['Min'] != "" or "ARR" or "BRD":

This is only checking for x['Min'] != "". Indeed, or "ARR" does not do anything because the boolean bool("ARR") is always True! The same applies for or "BRD" and that explains why you end up having BRD values trying to be cast as integers later on your loop. See the following, if you replace x['Min'] by a value you'd want to skip:
>>> xmin = "BRD"
>>> xmin != "" or "ARR" or "BRD"
True

While you'd want False!
If you wish to say that x['Min'] must not be either "" or ARR or BRD then you may use the following:
if x['Min'] not in ["", "ARR", "BRD"]:

Or
if x['Min'] and x['Min'] not in ["ARR", "BRD"]:

Proof:
>>> xmin = "BRD"
>>> xmin not in ["", "ARR", "BRD"]
False

A: The issue was in if x['Min'] != "" or "ARR" or "BRD".
You do something like this.
data_dict_list = [
    {
        "Car": "8",
        "Destination": "Vienna",
        "DestinationCode": "K08",
        "DestinationName": "Vienna/Fairfax-GMU",
        "Group": "2",
        "Line": "OR",
        "LocationCode": "D1",
        "LocationName": "Town",
        "Min": "14"
    },
    {
        "Car": "8",
        "Destination": "NewCrltn",
        "DestinationCode": "D13",
        "DestinationName": "New Carrollton",
        "Group": "1",
        "Line": "OR",
        "LocationCode": "D1",
        "LocationName": "Town",
        "Min": "12"
    },
    {
        "Car": "6",
        "Destination": "Vienna",
        "DestinationCode": "K08",
        "DestinationName": "Vienna/Fairfax-GMU",
        "Group": "2",
        "Line": "OR",
        "LocationCode": "D1",
        "LocationName": "Town",
        "Min": "BRD"
    }
]

for data_dict in data_dict_list:
    if data_dict['DestinationCode'] == "K08":
        if data_dict['Min'] not in ("", "ARR", "BRD"):
            if 10 < int(data_dict['Min']) < 20:
                print("")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Duplicate or Copy publishing pages (Pages document library) I want to duplicate an existing WebPart page from the Pages document library (Publishing feature enabled). I have found a no-code Sandboxed solution (NCSS) which can enble this functionality in SharePoint 2013 (Link to the article).
But I don't wan't to deploy any wsp into solution gallery as my organization won't approve it. Looking for an alternative way through client side code JSOM/Rest.

A: I have taken a look into the Mavention Duplicate Page (no-code Sandboxed WSP) link.
Found out that there is only a js file inside. Tried putting the content of the js file into a script editor webpart in my Pages document library and it's working.
Actually there is no need to deploy the wsp into solution gallery.

eval(function(p, a, c, k, e, d) {
debugger;
e = function(c) {
    return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36))
};
if (!''.replace(/^/, String)) {
    while (c--) {
        d[e(c)] = k[c] || e(c)
    }
    k = [function(e) {
        return d[e]
    }];
    e = function() {
        return '\\w+'
    };
    c = 1
};
while (c--) {
    if (k[c]) {
        p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c])
    }
}
return p
}('(2(){I(L(h)===\'D\'||h===16){n}h.e(2(){0 v=2(){0 5={};5.U=\'w\';5.V=Q;5.E={};5.E.P=2(1){n A(1)};I(L(G)!==\'D\'){G.19.12(5)}};0 A=2(1){0 c=13(1);11(1,2(){0 6=p 10(c+\'-r\');q(1,6);6.Y()});0 7=[];7.e(\'<s Z=\'+14(c+\'-15\')+\' 1a="t-u-r t-u-X">\');7.e(17(1,1.8,1.1b));7.e(\'</s>\');n w.W(c,7.T(\'\'))};0 q=2(1,6){R(1,6);0 S=1.8;6.18(p 1w({1E:\'o\',1F:2(1G,1D){0 l=3.4.i.1C(\'1y f...\',1z);0 9=1.8.x.1A(\'.y\',p 1B().1H(\'1I\')+\'.y\');0 j=3.1Q.1c();0 z=j.1O();0 d=z.1P(1.8.x);d.1N();d.1J(9);d.1K();j.1L(F.O(H,2(B,m){3.4.i.C(l);0 b=3.4.g.J(\'o f:\',\'1M 1x 1j 1k: <a 1l="\'+9+\'">\'+9+"</a>",k);3.4.g.K(b,\'1i\');0 M={\'1h\':1,\'1d\':k};1e(M,3.4.1f.1g)}),F.O(H,2(B,m){3.4.i.C(l);0 b=3.4.g.J(\'o f:\',\'1m 1n 1t 1u 1v 1s 1r 1o f: <N>\'+m.1p()+\'</N>\',k);3.4.g.K(b,\'1q\')}))}}))};v()})})();', 62, 115, 'var|renderCtx|function|SP|UI|templateOverride|calloutActionMenu|ecbMarkup|CurrentItem|path||sid|calloutID|file|push|page|Status|_spBodyOnLoadFunctions|Notify|context|true|nid|eventArgs|return|Duplicate|new|calloutOnPostRenderCustomTemplate|actions|span|js|callout|registerDuplicatePageAction|Callout|FileRef|aspx|web|calloutRenderCustomFooterTemplate|sender|removeNotification|undefined|Templates|Function|SPClientTemplates|this|if|addStatus|setStatusPriColor|typeof|evtAjax|em|createDelegate|Footer|850|CalloutOnPostRenderTemplate|listItem|join|BaseViewID|ListTemplateType|GenerateDefaultFooter|ecbActionDownArrow|render|id|CalloutActionMenu|AddPostRenderCallback|RegisterTemplateOverrides|GetCalloutElementIDFromRenderCtx|StAttrQuote|ecbMenu|null|RenderECBinline|addAction|TemplateManager|class|CurrentFieldSchema|get_current|csrAjaxRefresh|AJAXRefreshView|DialogResult|OK|currentCtx|green|duplicated|as|href|The|following|the|get_message|red|duplicating|while|error|has|occured|CalloutAction|successfully|Copying|false|replace|Date|addNotification|action|text|onClickCallback|event|format|yyyyMMddHHmmss|copyTo|undoCheckOut|executeQueryAsync|Page|checkOut|get_web|getFileByServerRelativeUrl|ClientContext'.split('|'), 0, {}))


text:
Q: SSIS: Executing package with custom component I have created a package that aims to achieve a high level of flexibility, allowing mappings from a flat file to a custom component to be determined at runtime. I have done so by doing the following:

*

*Created a package which fetches column mappings from a database table. This table contains the "flat file source columns" and the "database table columns". This data is stored in a package variable.

*I created a custom pipeline component (destination adapter) that processes the rows from the flat file and then populates a data table with the data from the flat file into the "database table columns". This data table is stored in a variable. (This custom component was not added to the package through the designer)

*In order to achieve "dynamic mapping", I created a script task which ran after my initial SQL query which fetched the column mappings. The script task does the following:

*

*Creates a package

*Adds a Data Flow task

*Adds a flat file source (and connections) to the Data Flow Task

*Adds my custom component

*Maps the flat file source to my custom component

*Passes in my "Parent package variables" and executes the package

*Retrieves the "Data table variable" from the newly created package

I then run another script task which runs insert statements for each record in the data table variable.
The issue that I am having is that my package will not execute unless I add a flat file destination to the package that I created programatically.
I discovered this by saving the package that I created programatically and then added the flat file destination through the designer. I then opened a script task, loaded this package and executed it and it ran.
Below is the code for the creating the child package programatically:
 Try
  'CREATE PACKAGE
  package = New Microsoft.SqlServer.Dts.Runtime.Package()

  '-----------------------
  'CREATE DATA FLOW TASK
  '-----------------------
  Dim PipelineTask As Executable = package.Executables.Add("STOCK:PipelineTask")
  Dim DataFlowTask_Runtime As Dts.Runtime.TaskHost = CType(PipelineTask, Dts.Runtime.TaskHost)
  DataFlowTask_Runtime.Name = "MyCustom Data Flow Task"

  Dim DataFlowTask_DesignTime As MainPipe = CType(DataFlowTask_Runtime.InnerObject, MainPipe)

  '------------------
  'SETUP CONNECTIONS
  '------------------
  'CREATE FLAT FILE CONNECTION
  Dim FFConnectionManager As ConnectionManager = package.Connections.Add("FLATFILE")
  FFConnectionManager.ConnectionString = FileName
  FFConnectionManager.Name = "Flat File Source Connection"

  'SETUP FLAT FILE COLUMNS AND DELIMETERS
  GetColumnsFromFlatFile(FFConnectionManager, DelimeterType.CarriageReturnLineFeed, DelimeterType.LineFeed, DelimeterType.Tab, 0)

  '-----------------------
  'CREATE SOURCE COMPONENT
  '-----------------------
  ' Set up the souce component of the Dataflow task
  Dim FFSourceComponent As IDTSComponentMetaData100 = DataFlowTask_DesignTime.ComponentMetaDataCollection.New
  FFSourceComponent.Name = "Flat File Source"

  ' The managed source is an instantiation of the source.
  FFSourceComponent.ComponentClassID = "{D23FD76B-F51D-420F-BBCB-19CBF6AC1AB4}"
  Dim FFSourceComponent_DesignTime As Microsoft.SqlServer.Dts.Pipeline.Wrapper.CManagedComponentWrapper = FFSourceComponent.Instantiate
  FFSourceComponent_DesignTime.ProvideComponentProperties()

  ' Link the connection to the source component.
  If FFSourceComponent.RuntimeConnectionCollection.Count > 0 Then
    FFSourceComponent.RuntimeConnectionCollection(0).ConnectionManager = DtsConvert.GetExtendedInterface(FFConnectionManager)
    FFSourceComponent.RuntimeConnectionCollection(0).ConnectionManagerID = FFConnectionManager.ID
  End If
  FFSourceComponent_DesignTime.AcquireConnections(Nothing)
  FFSourceComponent_DesignTime.ReinitializeMetaData()

  '------------------------------------------
  'Create Output Mappings from the flat file.
  '------------------------------------------
  Dim OutputColumnCollection As IDTSOutputColumnCollection100
  OutputColumnCollection = FFSourceComponent.OutputCollection(0).OutputColumnCollection

  Dim exOutColumn As IDTSExternalMetadataColumn100
  For Each OutputColumn As IDTSOutputColumn100 In OutputColumnCollection
    exOutColumn = FFSourceComponent.OutputCollection(0).ExternalMetadataColumnCollection(OutputColumn.Name)
    FFSourceComponent_DesignTime.MapOutputColumn(FFSourceComponent.OutputCollection(0).ID, OutputColumn.ID, exOutColumn.ID, True)
    'Add the output column name and ID to an array so that we can identify them at a later stage
    outputColumnLineageIDs.Add(OutputColumn.Name, OutputColumn.ID)
  Next
  FFSourceComponent_DesignTime.ReleaseConnections()

  '----------------------------
  'CREATE MYCUSTOM SCRIPT COMPONENT
  '----------------------------

  Dim MyCustomScriptComponent As IDTSComponentMetaData100 = DataFlowTask_DesignTime.ComponentMetaDataCollection.New
  MyCustomScriptComponent.ComponentClassID = "MyCustomBuffer.CustomComponents.MyCustomScriptComponent, MyCustomBuffer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=516f7fc6acf0e6e0"
  MyCustomScriptComponent.Name = "MyCustom Script"

  Dim MyCustomScriptComponent_DesignTime As CManagedComponentWrapper = MyCustomScriptComponent.Instantiate
  MyCustomScriptComponent_DesignTime.ProvideComponentProperties()

  ' Create the path from source to destination.
  Dim path As IDTSPath100 = DataFlowTask_DesignTime.PathCollection.New
  path.AttachPathAndPropagateNotifications(FFSourceComponent.OutputCollection(0), MyCustomScriptComponent.InputCollection(0))

  ' Get the destination's default input and virtual input.
  Dim InputMyCustom As IDTSInput100 = MyCustomScriptComponent.InputCollection(0)
  Dim vInputMyCustom As IDTSVirtualInput100 = InputMyCustom.GetVirtualInput

  MyCustomScriptComponent_DesignTime.ReinitializeMetaData()

  ' Iterate through the virtual input column collection.
  For Each vColumn As IDTSVirtualInputColumn100 In vInputMyCustom.VirtualInputColumnCollection
    ' Call the SetUsageType method of the destination
    '  to add each available virtual input column as an input column.
    Dim InputCol As IDTSInputColumn100 = MyCustomScriptComponent_DesignTime.SetUsageType(InputMyCustom.ID, vInputMyCustom, vColumn.LineageID, DTSUsageType.UT_READONLY)
  Next

  '----------------------------
  'CREATE FLAT FILE DESTINATION
  '----------------------------

  Dim DestFFConnManager As ConnectionManager = package.Connections.Add("FLATFILE")
  DestFFConnManager.ConnectionString = "C:\Test\MyCustomBufferTest.txt"
  DestFFConnManager.Name = "Flat File Destination Connection"

  Dim DestFFConnManager_DesignTime As IDTSConnectionManagerFlatFile100 = DestFFConnManager.InnerObject
  DestFFConnManager_DesignTime.ColumnNamesInFirstDataRow = True
  DestFFConnManager_DesignTime.CodePage = 1252
  DestFFConnManager_DesignTime.HeaderRowDelimiter = vbTab
  DestFFConnManager_DesignTime.Format = "Delimited"
  DestFFConnManager_DesignTime.HeaderRowsToSkip = 0
  'FlatFileConnection.TextQualifier = ""
  DestFFConnManager_DesignTime.RowDelimiter = vbTab

  'CREATE FLAT FILE DESTINATION
  Dim FFDestination As IDTSComponentMetaData100 = DataFlowTask_DesignTime.ComponentMetaDataCollection.New
  FFDestination.ComponentClassID = "{8DA75FED-1B7C-407D-B2AD-2B24209CCCA4}"
  FFDestination.Name = "Flat File Destination"

  Dim FFDestination_DesignTime As CManagedComponentWrapper = FFDestination.Instantiate
  FFDestination_DesignTime.ProvideComponentProperties()

  ' Link the connection to the source component.
  If FFDestination.RuntimeConnectionCollection.Count > 0 Then
    FFDestination.RuntimeConnectionCollection(0).ConnectionManager = DtsConvert.GetExtendedInterface(DestFFConnManager)
    FFDestination.RuntimeConnectionCollection(0).ConnectionManagerID = DestFFConnManager.ID
  End If
  Dim Destpath As IDTSPath100 = DataFlowTask_DesignTime.PathCollection.[New]
  Destpath.AttachPathAndPropagateNotifications(MyCustomScriptComponent.OutputCollection(0), FFDestination.InputCollection(0))

  Dim DestInput As IDTSInput100 = FFDestination.InputCollection(0)
  Dim VDestinput As IDTSVirtualInput100 = DestInput.GetVirtualInput()
  Dim VDestInputColCollection As IDTSVirtualInputColumnCollection100 = VDestinput.VirtualInputColumnCollection

  Dim indexMax As Integer = VDestInputColCollection.Count - 1
  For index As Integer = 0 To indexMax
    ' Get input column to replicate in flat file
    Dim virtualInputColumn As IDTSVirtualInputColumn100 = VDestInputColCollection(index)

    ' Add column to Flat File connection manager
    Dim flatFileColumn As IDTSConnectionManagerFlatFileColumn100 = TryCast(DestFFConnManager_DesignTime.Columns.Add(), IDTSConnectionManagerFlatFileColumn100)
    flatFileColumn.ColumnType = "Delimited"
    flatFileColumn.ColumnWidth = virtualInputColumn.Length
    flatFileColumn.DataPrecision = virtualInputColumn.Precision
    flatFileColumn.DataScale = virtualInputColumn.Scale
    flatFileColumn.DataType = virtualInputColumn.DataType
    Dim columnName As IDTSName100 = TryCast(flatFileColumn, IDTSName100)
    columnName.Name = virtualInputColumn.Name

    If index < indexMax Then
      flatFileColumn.ColumnDelimiter = vbTab
    Else
      flatFileColumn.ColumnDelimiter = vbCrLf
    End If
  Next

  FFDestination_DesignTime.AcquireConnections(Nothing)
  FFDestination_DesignTime.ReinitializeMetaData()

  For Each virtualInputColumn As IDTSVirtualInputColumn100 In VDestInputColCollection
    ' Select column, and retain new input column
    Dim inputColumn As IDTSInputColumn100 = FFDestination_DesignTime.SetUsageType(DestInput.ID, VDestinput, virtualInputColumn.LineageID, DTSUsageType.UT_READONLY)
    ' Find external column by name
    Dim externalColumn As IDTSExternalMetadataColumn100 = DestInput.ExternalMetadataColumnCollection(inputColumn.Name)
    ' Map input column to external column
    FFDestination_DesignTime.MapInputColumn(DestInput.ID, inputColumn.ID, externalColumn.ID)
  Next

Catch ex As Exception
  MsgBox(ex.Message)
End Try

Adding the destination flat file component has allowed my package to execute, however it does not make sense as my custom component type is a destination adapter. The additional destination flat file component is inefficient and I would like to know what the need for this is.

A: You're probably getting the error while validation of your custom component, what you should do is:
Set the delay validation property in your custom component to true.


text:
Q: How to use RainTPL? I'm trying to use the 'include' tag from RainTPL but it's not working, I can't figure out why.
My server setup is a UniServer installation with apache and php. I have tried php code to test the setup and it worked.
    <?php
    include "inc/rain.tpl.class.php"; //include Rain TPL
    raintpl::$tpl_dir = "layout/"; // template directory
    raintpl::$cache_dir = "tmp/"; // cache directory
?>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Ezbuy - Compras Inteligentes - Aguardem</title>

        <link rel="stylesheet" href="comingsoon.css" type="text/css">
        <link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">

        {include="layout/header"}

Facilidade, Preço & Segurança

Cadastre-se e descubra uma forma fácil de comprar, sem necessidade de longas pesquisas pela internet.
                    Você pode escolher os produtos oferecidos com o menor preço.
                    Vendedores qualificados e método de pagamento seguro.

Apenas o que interessa

Find local favorites, new menu items, and global recommendations. Check the Forkly DishScore™ to see what's good at a glance; or search every dish and detail to plan ahead.

Pague quanto quiser

Escolha o valor que deseja pagar pelo produto e aguarde uma oferta.

A: Just use {include="header"} as you have already told Rain to use layout folder as template directory... what you are currently doing is trying to include layout/layout/header.html
By the way.. you should not include HTML and PHP in the same file... you should use an index.php file to initialize the Rain instance and then call the draw('template') method and put all the html in the file layout/template.html


text:
Q: Text is not sharp and shadowy in my new LCD Quite similar to this question, I'm in trouble of the same problem now. I'm trying to set up dual monitor on my SONY CS36H laptop, and I bought Acer S231HLbd last Saturday, but have been struggling with solving to get the text be sharp in these days, searched a lot, tried a lot, including all the methods in the best answer of that question, I even did more, like reinstalled NVIDIA driver, reinstalled Windows 7, tried to set gamma to some darker to let the text shadow gone. Turn off and on the clearType a few times. Changed the location of VGA cable, split the power cable and VGA cable as far as possible. Issue still there. also the screen is too white, and not healthy for eye ..
Arial font could be kind of sharp, but bold font are too fuzzy, and more other fonts look fuzzy.
I was hoping to buy DVI transistor, but posts show that it helps little for 1920x1080.
What I didn't have time and chance to do is to take the big stuff to office and try whether it is because of my laptop's video card issue, or to find some other LCD to replace and see whether that would be sharp.
Now, I'm totally exhausted .. what's left now is changing another LCD?

A: In the case of 1920x1080, DVI ought to help against VGA, particularly if your VGA cable is not of a very good quality or is very long.
What made you think otherwise ?

A: Try turning the Screen refresh rate up. Also, if your monitor has an Auto Adjust button (most new monitors have it), try pushing that after you up the refresh rate.

A: It's possible your video card isn't pushing enough power through the video cable. Seems that the spec for this versus implementation conventions are fairly disjoint. It may help to try another video cable (and be quite sure both ends are firmly attached for any video cable you try). Kind of sounds more like a setting problem though.
It rarely hurts to make sure all your system updates have been installed - particularly for your video card, in this case.

A: @Breakthrough - First of all, as The White Phoenix wrote all kinds of signals are powered, so it means - they use energy to translate signal through the cable. Second, my "LOL" means that if video card supports up to 1080p (an windows recognizes it), then video card must have enough power to provide such "power" to send signal through any kind of video/media cable as VGA/DVI/Display Port/SCART/S-VIDEO or HDMI. So guys if you have only "WORDS" and "NO PROOF", please don't trash this topic :/
I think author's video chip has enough power source to translate 1080p on screen and problem is only in monitor's driver, which just will fix picture Scale Proportions (Auto Adjust) and Auto Calibrate screen.
P.S. that was long time ago, when such resolution was "big/large".


text:
Q: Copying data from one database to another database on same server I am trying to copy data from one database to another. I can do it with creating a query in one database, save the data to a spreadsheet and import into the other database but I want to find a simpler (less steps) process to do this.  Here the problem. The user name and password on the databases are not the same. Any thoughts on how to remedy this?

A: You have several options

*

*SQL Server import and export wizard, as mentioned above

*bcp.exe out, then bcp.exe in or bulk insert

*select * into


text:
Q: Error during implementation of quickSort algorithm in c++:- "error: cannot convert 'int*' to 'int**'....." The full error is as follows:- "|error: cannot convert 'int*' to 'int**' for argument '1' to 'void quickSort(int**, int, int)'|"
MY whole code is below:
#include <iostream>

using namespace std;

int Partition (int *A[], int p, int r) {
    int x = *A[r];
    int i = p-1;
    for (int j=0; j<=r; j++){
        if(*A[j]<=x){
            i++;
            int save=*A[j];
            *A[j] = *A[i];
            *A[i] = save;
        }
    }
    int save2=*A[i+1];
    *A[i+1]=*A[r];
    *A[r]=save2;
    return (i+1);
}

void quickSort(int *A[], int p, int r) {
    if (p<r){
    int q = Partition(A, p, r);
    quickSort(A, p, (q-1));
    quickSort(A, (q+1), r);
    }
}

int main() {
    int RR[] = {2,8,7,1,3,5,6,4};
    int y=sizeof(RR)/sizeof(int)-1;
    cout << y << endl;
    int *QQ = RR;
    cout << *QQ << endl;
    quickSort(QQ, 0, y);

    return 0;
}

This is an implementation that I tried myself from a pseudo code. I'm new to programming so it would be a great help if you could illustrate a little of why this error occurred.
Thanks in advance

A: The first thing I notice about the code is a whole lot of unneccessary pointer dereferencing. The contents of A will be changed without the need for additional pointers because Arrays decay to pointers (What is array decaying?) so A is treated as a pointer to the first array element and you are effectively passing the array by reference already.
Worse, int * A[] isn't a pointer to an array of int, it is an array of pointers to int. A very different thing. *A[0] does not return 2, it tries to use 2 as an address and return whatever happens to be in memory at address 2. This will almost certainly not be anything you want, or are allowed, to see so the program will do something unfortunate. Crash if you are lucky.
Instead, try
int Partition (int A[], int p, int r) {
    int x = A[r];
    int i = p-1;
    for (int j=0; j<=r; j++){
        if(A[j]<=x){
            i++;
            int save=A[j];
            A[j] = A[i];
            A[i] = save;
        }
    }
    int save2=A[i+1];
    A[i+1]=A[r];
    A[r]=save2;
    return (i+1);
}

void quickSort(int A[], int p, int r) {
    cout << p << ',' << r << endl; // Bonus: This will make the next bug really easy to see
    if (p<r){
    int q = Partition(A, p, r);
    quickSort(A, p, (q-1));
    quickSort(A, (q+1), r);
    }
}

Note the extra cout statement at the top of quickSort This will help you see the logic error in Partition. The program will crash due to a... wait for it! A Stack Overflow, but the cout will show you why.


text:
Q: How do I separate the execution of tests via cargo test? I'm working on a Rust project that has many units test (almost 200).
About 20 of those tests are really heavy and they create problems when executed with the others in my pipeline (take more than an hour).
If I execute them separately they are fast enough.
I'm actually using a workaround:
I've create a project feature on my Cargo.toml:
skipped_tests = []

Then I launch my test with:
$ cargo test

then the others:
$ cargo test module::my_test --features skipped_tests

Is there a proper way or a best practice to separate the tests execution in Cargo?

A: You can add the #[ignore] attribute to expensive tests, which causes them to be skipped by default.
#[ignore]
#[test]
fn test_something() {
    assert_eq!(1 + 1, 2);
}

You can run only the ignored tests using
cargo test -- --ignored

or all tests using
cargo test -- --include-ignored

A: One way would be to put this part of your project into a separate translation unit/crate, e.g. with Cargo.toml
[package]
name = "heavy_weight"

and then run tests with cargo test --exclude heavy_weight. You can add several exclusions.
Then run the heavy-weight ones with something along the lines of cargo test --manifest-path=heavy_weight/Cargo.toml
I recommend you run those tests in --release mode if there are no blockers, maybe it will be enough for you to not bother with any other changes.


text:
Q: GET multiple values in a search request I am using the AtTask API to do some custom reporting and I would like to get back more than one of a particular parameter. For example, in the documentation it states:

GET /attask/api/project/search?status=CUR

Is there a way to also get back APP, PLN, etc? i.e. I'd like to do one call and get back all projects with a particular set of statuses. I've tried:
status={CUR,APP,PLN}
status=CUR,APP,PLN
status=CUR&status=APP&status=PLN

So far none of those have returned the dataset. Thank you!

A: Your last attempt is the closest. You just need to add status_Mod=in, so your statement would be:
GET /attask/api/project/search?status=CUR&status=APP&status=PLN&status_Mod=in


text:
Q: Find a formula for calculate $\prod_{n=0}^N(a^n + b)$ I have an expression, in which I am looking for a formula to calculate
$$ \prod_{n=0}^N (a^n +b)$$
as a summation. Is there a general name for this type of formula? Or a relevant approach to find partial products such as this one?

A: Using the Gaussian binomial coefficients, also known as the q-analogs of the binomial coefficient, gives a representation of: $$ \prod_{n=0}^{N} (a^n + b) = b^{N+1} \: \left(-\frac{1}{b}; \: a \right)_{N+1} = b^{N+1} \: \sum_{j=0}^{N+1} {{N+1} \brack {j}}_a \: \left( \frac{1}{b}\right)^j a^{\binom{j}{2}} $$ Though I think that sum would be much more computationally expensive than just running the product through.


text:
Q: Tcl: K trick / unsharing objects also for embracing a list? What I'm trying to do is to put an additional level of braces around a list:
set l [list $l]

For operations of the type
set someVar [someFunc $someVar]

it is recommended (https://stackoverflow.com/a/67318915/3852630, https://stackoverflow.com/a/64117854/3852630, https://wiki.tcl-lang.org/page/K) to use
set someVar [someFunc $someVar[set someVar {}]]

instead which is known to drastically improve performance.
Two questions:

*

*Would this also apply to list, so should I use this for my specific problem?:

set l [list $l[set l {}]]

*

*Is there another efficient way to add an additional level of braces?

Thanks for your help!

Edit: corrected error pointed out by Chris Heithoff

A: Yes, that should work.   list is just another possible thing to substitute into someFunc in the recommendation for K.
Your specific example for list isn't quite right though.
set l [list $l[set $l {}]]

..you want to assign an empty string to the variable name l, not the value of $l to actually benefit.
Do this instead:
set l [list $l[set l {}]]

A: This is an explanation of why you don't need the K trick.
Tcl's values are in general reference counted compound values that have a guaranteed serialization to a string; this is normally concealed information but it's how things really work. In fact, some of our strings also have complicated internal representations some of the time, making Tcl's strings a lot faster than those in C, C++, or Java most of the time.
To go with this is a model where you have to copy a value to modify it. But we don't actually do that; it's rather slow if you have to copy things all the time! Instead, we only take a copy when we're writing to a shared value; the value is shallow deduplicated, the updates are applied to the new copy, and then that's used where it should be (e.g., written back to the variable). This is done in a recursive fashion as required, so that the right thing happens when you do a modification deep inside a nested list or dictionary.
When are values shared? Well, there are a few places that can hold references (e.g., lists and dicts) but the key ones here are:

*

*Variables. (Duh! This is a really obvious one!)

*The Tcl execution stack. This is where Tcl holds the results of substitutions, variable reads, and commands until it can dispatch to the command it is about to call next. In theory an alternate execution mechanism could be used, but you'd still have to hold the references for the same amount of time to get the execution model right.

So, what happens in the classic case for K? Well, you start by doing set x [linsert $x 0 a] which (ignoring bytecoding) will do:

*

*Push set.

*Push x.

*Push linsert

*Push the value read from x. (Keep an eye on this: it now has two references, one from the variable and one from the stack)

*Push 0

*Push a

*Invoke (of linsert) consuming 4 values from the stack (steps 3–6) and pushing the result. The value references to the arguments are only dropped after the command implementation returns, ensuring that arguments don't disappear from under the command's feet.

*Invoke (of set) consuming 3 values from the stack (steps 1, 2 and 7).

The implementation of linsert can do an in-place edit of the list if the value is unshared, but as noted in step 4 the value is naturally shared, so it must be deduplicated, making this necessarily an expensive operation.
The classic K trick is this:
proc K {x y} {return $x};  # This is the K combinator

set x [linsert [K $x [set x DUMMY]] 0 a]

That effectively does a take-from-variable (leaving an arbitrary value behind). You're using an optimised version of that (which depends on bytecode trickery and a semantic optimisation in the guts of the string concatenation implementation).
But why don't we need it for set x [list $x]? Well, in that case we're not updating the value, we're just encapsulating it in a list wrapper value and then updating the variable. Values are not variables. You can get the exact value that was previously in there with lindex $x 0; confirm this for yourself with tcl::unsupported::representation, whose output includes where values are actually stored in memory (as well as both reference count and type info). It's a neat debugging tool, though sometimes quite surprising!

[EDIT]: To illustrate what I meant, here's a little interactive session. Pay particular attention to the object pointer; that's the memory address of the Tcl_Obj structure and is effectively the true identity of the value. (This is normally strictly ignored in Tcl; values are not supposed to have identity as such, as that's a concept that is reserved for named entities like variables. With being named comes the idea that things can be modified.)
% set x "a b c"
a b c
% tcl::unsupported::representation $x
value is a pure string with a refcount of 4, object pointer at 0x7ff2eba275b0, string representation "a b c"
% set x [list $x]
{a b c}
% tcl::unsupported::representation $x
value is a list with a refcount of 2, object pointer at 0x7ff2eba26ec0, internal representation 0x7ff2eb02f290:0x0, string representation "{a b c}"
% tcl::unsupported::representation [lindex $x 0]
value is a pure string with a refcount of 4, object pointer at 0x7ff2eba275b0, string representation "a b c"
% set x [linsert $x 0 d]
d {a b c}
% tcl::unsupported::representation $x
value is a list with a refcount of 2, object pointer at 0x7ff2eba2b930, internal representation 0x7ff2eb02d090:0x0, string representation "d {a b c}"

As you can see, the original value is still inside the list; it's not been altered in any way.


text:
Q: WP_Query Attachment adds additional attachment count and need to link attachment to post url I just wonder why WP_Query adding one more additional attachment with the defined number or posts. Also need to link attachment (thumbnail) to the post url. Here is my code
<?php
$query = new WP_Query( array( 'post_type' => 'news', 'showposts' => 5, 'orderby' => 'rand' ) );
if( $query->have_posts() ){
    while($query->have_posts()){
        $query->the_post();
        $image_query = new WP_Query( array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 'showposts' => -1, 'post_parent' => get_the_ID() ) );
        while( $image_query->have_posts() ) {
            $image_query->the_post();

            echo '
';
            echo wp_get_attachment_image( get_the_ID() );
            echo '
';
        }
    }
}
?>


text:
Q: android:windowSoftInputMode... is there a javascript/meta tag/"web page" config equivalent? I've got a web site "application" which is not an app, but an actual web page you'd use through Chrome or some other browser.  In iOS invoking the keyboard (via an input element for example) doesn't change the viewport ratio or resize anything, but on Android it does. This is causing insane layout problems for my app "page", as we have to distinguish between portrait and landscape view orientations.
I found many answers about android:windowSoftInputMode activity configs w/rt keyboard display and interaction with media queries, and how to specify your desired value (in my case, "adjustNothing"), but I haven't found anything on how to invoke this configuration when you're looking at a web page via chrome or any other browser.
So does anyone know of a way to do this via JavaScript or some other in-page code? Thanks.


text:
Q: How to get dropdown value Magento2.1 I want to get a dropdown attribute value on the category page, i set the show in listing to yes and added this attribute to product. then set below code to my list.phtml:

productAttribute($_product, $_product->getMaterial(), 'material') ?>

but get the id of the attribute value. mean that now i see 72 instead of Bronze
How can i get the value test?

A: Try the below code to get the attribute value :
$attr = $_product->getResource()->getAttribute('your_attribute_code')->getFrontend()->getValue($_product);

and try to print the $attr variable.

A: Try following code, I did something similar but that was on the product page.
<?php  $_attributeValue = $_helper->productAttribute($_product, $_product->getMaterial(), 'material');
if ($_attributeValue):
$attribute = $_product->getResource()->getAttribute($_code);
if ($attribute->usesSource()) {
    $optionText = $attribute->getSource()->getOptionText($_attributeValue);
    echo $optionText;
}
?>


text:
Q: How to clear error message buffer in SQLPlus? There's an issue when installing several objects via SQL*Plus.
Let's install two objects: package A and view B, and A has compilation errors
SET FEEDBACK OFF

prompt install PACKAGE_A spec
create or replace package package_a is
  procedure p;
end;
/
show errors

prompt install PACKAGE_A body
create or replace package body package_a is
  procedure p is begin hello; end;
end;
/
show errors

prompt install VIEW_B
create or replace view view_b as
  select * from dual;

show errors

Thus we get in the output:
install PACKAGE_A spec
No errors.

install PACKAGE_A body

Warning: Package Body created with compilation errors.

Errors for PACKAGE BODY PACKAGE_A:

LINE/COL ERROR
-------- -----------------------------------------------------------------
2/24     PL/SQL: Statement ignored
2/24     PLS-00201: identifier 'HELLO' must be declared

install VIEW_B
Errors for PACKAGE BODY PACKAGE_A:

LINE/COL ERROR
-------- -----------------------------------------------------------------
2/24     PL/SQL: Statement ignored
2/24     PLS-00201: identifier 'HELLO' must be declared

I had faced this problem not only in a "view after package" case, but currently I can not reproduce it in a short example for a "package after package" case (which bothers me mostly). So it seems to not appear for all types of compilation errors.

Documentation says When you specify SHOW ERRORS with no arguments, SQL*Plus shows compilation errors for the most recently created or altered stored procedure.
It is also clear that there is an option of specifying a particular object
SHOW ERR[ORS] [{FUNCTION | PROCEDURE | PACKAGE | PACKAGE BODY ...} [schema.]name]

But it does not look usable, because the requirement of giving an object type overcomplicates the situation (it is not obvious why the command cannot be satisfied with an object name alone).
Could you help me find a way to clear the buffer of SHOW ERRORS command, so it could be set in a pristine state before every object compilation?

A: If there is a way, I don't know it.
SHOW ERRORS is a SQL*Plus command. As fara as I can tell, it fetches data from USER_ERRORS (or, possibly, ALL_ERRORS or DBA_ERRORS). Its description is
SQL> desc user_errors;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------
 NAME                                      NOT NULL VARCHAR2(30)
 TYPE                                               VARCHAR2(12)
 SEQUENCE                                  NOT NULL NUMBER
 LINE                                      NOT NULL NUMBER
 POSITION                                  NOT NULL NUMBER
 TEXT                                      NOT NULL VARCHAR2(4000)
 ATTRIBUTE                                          VARCHAR2(9)
 MESSAGE_NUMBER                                     NUMBER

If I do something like this:
SQL> create or replace procedure ptest is
  2    l_Res number;
  3  begin
  4    l_res := 1 * A;
  5  end;
  6  /

Warning: Procedure created with compilation errors.

SQL> show err
Errors for PROCEDURE PTEST:

LINE/COL ERROR
-------- --------------------------------------------------------
4/3      PL/SQL: Statement ignored
4/16     PLS-00201: identifier 'A' must be declared

then SHOW ERR returns the last errors I got. Does it mean that USER_ERRORS doesn't contain something else? No:
SQL> select name, line, substr(text, 1, 50) text from user_Errors;

NAME               LINE TEXT
------------ ---------- --------------------------------------------------
PTEST                 4 PL/SQL: Statement ignored
PTEST                 4 PLS-00201: identifier 'A' must be declared
ADD_COURSE            0 PL/SQL: Compilation unit analysis terminated
ADD_COURSE            2 PLS-00201: identifier 'COURSE.TILTE' must be decla

SQL>

So, can I simply delete its contents? Ideally, I'd do that between every two CREATE PROCEDURE (or whatever) statements in that .SQL script:
SQL> delete user_errors;
delete user_errors
       *
ERROR at line 1:
ORA-01031: insufficient privileges

Nope, I can't do that.
Therefore, I think you'll have to use that not-very-usable option and specify whose errors you want to see.


text:
Q: Multivariable Calculate $\int\int_D(x^2 + y^2 )dx dy$ Calculate Double integral $$\iint_D (x^2 + y^2 ) dxdy$$
where:
$$D=\{(x,y)\in\mathbb{R}^2 : x\le x^2+y^2\le2x, -x\le y \le x \}$$
What i did?
I tried to use polar coordinates and i got this ==> $\sqrt x\le r \le \sqrt(2x)$

Can you please help me with the limit of integration if i change this
  to polar coordinates. Thank you

A: You haven't fully used polar coordinates. Recall the transformation is given by $(x,y) \mapsto (r\cos \theta, r \sin \theta)$. From $D$ we then get the bounds: $r\cos \theta \leq r^2 \leq 2 r\cos \theta$, $-r \cos \theta \leq r\sin \theta \leq r \cos \theta$. The first one of course reduces to $\cos \theta \leq r \leq 2\cos \theta$ while if you divide the second one by $r\cos\theta$ you can get $\arctan(-1) \leq \theta \leq \arctan(1)$. From there you get an integral that is manageable to evaluate.


text:
Q: How to generate mapping of ActorID to Peer in TicTacFish (Distributed Actors sample project) In Apple's TicTacFish sample project, Step 3 provides an example of a LocalNetworkActorSystem based on Bonjour. At various points in the implementation, reference is made to building up a mapping from actor IDs to Connections/Peers, such that we can identify the correct connections to send calls and replies on (the sample project just broadcasts to all connections.) I've tried various approaches but can't get past the simple hurdle that:

*

*the methods required by DistributedActorSystem (e.g., SampleLocalNetworkActorSystem.remoteCall(on:target:invocation:throwing:returning:) do not allow for additional arguments, preventing me from passing along data about the originating connection that could be used to uniquely identify the peer

*the peer initialization happens separately from the relevant ActorID methods (e.g., SampleLocalNetworkActorSystem.resolve(id:as:), SampleLocalNetworkActorSystem.assignID(_:), SampleLocalNetworkActorSystem.actorReady(_:)) which prevents me from knowing which connection this actor initialization corresponds to.

Has anyone figured out a way to get this to work?


text:
Q: What are discrete animations? The MDN animation documentation refers to animation type being discrete. What does this mean?

A: Discrete animations proceed from one keyframe to the next without any interpolation.
Think of it the way you normally would think of an animation - one image to the next.  Interpolation is inbetweening - filling in space between the main images (in the case of computer graphics these are found from formulas).
In traditional hand-drawn animation, the main artist would produce the keyframes, and an assistant would draw the inbetweens.
So discrete animation is like hand-drawn animation done without the inbetweens of an assistant.


text:
Q: Example of subgroup of $\mathbb Q$ which is not finitely generated
I was looking for a proper subgroup of $\mathbb Q$ which is not finitely generated under the addition operation.

We know every finitely generated subgroup of $\mathbb Q$ is cyclic. For a proper subgroup I am just thinking about the subgroup $H$ generated by $\{\frac{1}{p} : p \text{ prime }\}$ may work. It seems $1/4$ is not in $H.$ Is this a  correct example? Thanks

A: Try $\mathbb Z[\frac12]$, that is, the set of binary fractions.
More generally, $\mathbb Z[\frac1p]$, that is, the set of fractions whose denominators are powers of the prime $p$.


text:
Q: Which is better ifram or  to play video (both youtube as well non youtube) in terms of browser compatibility? I tried with both

*

*iframe - no solution to stop autoplay or control video for non-youtube videos

*video - Does not support youtube video

Using iframe
 <iframe id="vt" width="420" autoplay="false" height="345" src="http://cache4.asset-cache.net/xd/468140002.mp4?v=1&c=IWSAsset&k=2&d=72990B68305E4FDFEE95B69A879131BCD6D7111452E48A17C03F8342D660D5A451EBC1DEC2A827C9&b=RTdG" frameborder="0" allowfullscreen></iframe>

jQuery(document).ready(function () {

   // var url = $('#vt').attr('src');
 // $('#vt').attr('src', '');
 //   $('#vt').attr('src', url);
    var vid = document.getElementById("vt");
    vid.pause()
//vid.onpause = function() {
    //alert("The video has been paused");
};
});

with video tag
<video width="320"  height="240" src="https://www.youtube.com/watch?v=dwH34mR6ZG8" controls="controls"> </video>

A: First of all, iframes were never meant for displaying embedded media. That's something the object tag was intended to handle instead. From the MDN docs:

The HTML Inline Frame Element (<iframe>) represents a nested browsing
  context, effectively embedding another HTML page into the current
  page.
The HTML Embedded Object Element (<object>) represents an external
  resource, which can be treated as an image, a nested browsing context,
  or a resource to be handled by a plugin.

Both of which predate the video element, which is what you should always be using to embed video content in a webpage.
Secondly, YouTube videos aren't meant to be linked directly from a <video> element... the embed code they provide you with is an iframe that opens up to an HTML5 video player anyway (or a Flash fallback for antique devices).
Verdict: If the video you're trying to display isn't or can't be hosted on YouTube, use the video tag on a webpage to embed it, making sure to convert the video in as many supported formats as possible. There's plenty of write-ups online on HTML5 video, so I won't detail the process here.


text:
Q: How do I deploy files to Apache Tomcat in a similar fashion to Apache Webserver, ftp I need to deploy some files to a Tomcat App Server, is it possible to access the root directory of an application, and upload files to a folder?
I have only used Apache WebServer thus far, and I can add files using something like filezilla to upload my website. In this case I just need to upload some files for download.
How can I setup a downloads folder, in tomcat?

A: If you don't specify which kind of files you have it is difficult. Do you have both static and dynamic content? App deploying is not quite the same as in Apache. I assume you have the right folder structure, your xml descriptors and so on. For this you have to theck the servlets specification version you are using, Tomcat version... With this, you have to upload files to webapps folder. You can upload a war file or an exploded folder with all contents (which structure do you have), althought the latest is not recommended. Tomcat may start to deploy before all files are uploaded.
Could you specify a little more?

A: If the only thing you need to deploy is a WAR, there's a package in most linux repos called tomcat-admin that provides a web interface to upload a WAR file directly.


text:
Q: Two XML elements with different types repeated unbounded times in XSD? Suppose I use a sequence of a and b elems. a has a type aType and b has a type bType.
<xs:sequence>
    <xs:element ref="a" maxOccurs="unbounded"/>
    <xs:element ref="b" maxOccurs="unbounded"/>
</xs:sequence>

...

<xs:element name="a" type="aType" abstract="true"/>
<xs:element name="b" type="bType" abstract="true"/>

If I write an XML doc with sequence which has both type elems of aType and bType, I get an error. Is it possible to allow in sequence to use any number of elements of two types?  What I want to allow is something like this:
 <seq></seq>

A: First, eliminate abstract="true" if you want to instantiate a and b in your document.
Then, place the maxOccurs="unbounded" on xs:choice:
<xs:choice maxOccurs="unbounded">
    <xs:element ref="a"/>
    <xs:element ref="b"/>
</xs:choice>

to allow a and b will be allowed to appear repeatedly such as you show in your comment:

A: The content model you show should match any sequence of one or more elements substitutable for an a element, followed by one or more elements substitutable for b.
You say, however, that you want to match a sequence of a and b elements, intermingled.  At least two things in your current declaration will need to change, then:

*

*If a and b elements should be allowed to appear in valid document,s then they are not abstract; you should stop saying that they are.

*If a sequence like  in the input may validly be followed by more a and b elements, then the sequence defined by the xsd:sequence element needs to be allowed to repeat; changing xsd:sequence/@maxOccurs to an integer greater than one, or to unbounded, will be necessary.

*If the intermingled set of a and b elements can start with a b, or end with an a, then you need to allow the individual elements in the content model to match zero elements in the instance, thus:
<xs:sequence maxOccurs="unbounded">
  <xs:element ref="a" minOccurs="0" maxOccurs="unbounded"/>
  <xs:element ref="b" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>

This is equivalent to the content model already suggested by kjhughes; for the language they both recognize, most readers will find a repeating choice clearer than a repeating sequence all of whose members are optional.


text:
Q: how to process standart confirm window In this code login off is faster then a browser close.
$(window).on('beforeunload',function(e){
    var msg = "Close window?";
    if (e) {
        e.returnValue = msg;
        $('.exit').click();
        return msg;
    }
});

How do I add processing to select an action in the window?
for example:
if(true){
    $('.exit').click();
}

I have found a cross-browser example:
    var myEvent = window.attachEvent || window.addEventListener;
    var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
    var confirmationMessage = 'Are you sure to leave the page?';  // a space
    (e || window.event).returnValue = confirmationMessage;
    return confirmationMessage;
});

But my question is still open: how to processing chossing close or not in confirm window?


text:
Q: How can I find the longest words in the string and return those (excluding duplicates) along with maximum length? I know how I can find the longest word in a string. For example this code here.
But here the problem is that the word "bbbbbb" is found because he is the
FIRST LONGEST WORD IN THE string,after that with 6 chars we have also the word "jumped". My question is how can I find in this case and the word "jumped",so all of them not only the first one.
UPDATE: I want unique list, so only one of each words

function longestWord(sentence) {
  sentence = sentence.split(' ');

  let theWord = sentence[0];
  var longest = 0;
  for (let i = 0; i < sentence.length; i++) {
    if (sentence[i] != "") {
      if (sentence[i].length > theWord.length) {
        longest = sentence[i].length;
        theWord = sentence[i];
      }
    }
  }
  return {
    length: longest,
    actuallWord: theWord
  }
}
console.log(longestWord("The quick brown as bbbbbb fox jumped over the bbbbbb lazy dog"));

A:

function longestWord(sentence) {
  // First we divide the sentence into words
  var words = sentence.split(' ');

  // We then get the length by getting the maximun value of the length of each word
  var length = Math.max(...words.map(a=>a.length));
  return {
    length: length,
    // Finally we filter our words array returning only those of with the same length we previously calculated
    words: words.filter(i => i.length == length)
  }
}
console.log(longestWord("The quick brown as bbbbbb fox jumped over the lazy dog"));

A: You may do that with Array.prototype.reduce() by a single pass through the array (without extra looping for calculating maximum length).
The idea is to reset resulting array with a single word, once its length exceeds those that were inserted before or append if current word happens to have same length, or simply pass by otherwise:

const src = 'The quick brown as bbbbbb fox jumped over the jumped lazy dog',

      result = src.split(' ')
                  .reduce((res, word, idx) => {
                    if(!idx || word.length > res.length)
                        res = {length: word.length, words:new Set([word])}
                    else if(word.length == res.length)
                        res.words.add(word)
                    return res
                  }, {})

console.log({result: result.length, words: [...result.words]})
.as-console-wrapper {min-height:100%}

A: You could take a single loop approach and check the legth fot each word with the accumulators length of the first item.

function longestWords(words) {
    return words
        .split(/\s+/)
        .reduce((accu, word) => {
            if (!accu[0] || accu[0].length < word.length) return [word];
            if (accu[0].length === word.length) accu.push(word);
            return accu;
        }, []);
}

console.log(longestWords("The quick brown as bbbbbb fox jumped over the lazy dog"));

A: You can do it by reducing the sentence array.
The advantage of this approach is that it loops over the array only once:

function longestWords(sentence) {
  return sentence.split(' ').reduce((output, word) => {
    if (word.length > output.length) {
      output.words = [word]
      output.length = word.length
    } else if (word.length === output.length) {
      output.words.push(word)
    }
    return output
  }, { length: 0, words: [] })
}
console.log(longestWords("The quick brown as bbbbbb fox jumped over the lazy dog"));

Or, if you want to filter out duplicate words, you could return a Set instead:

function longestWords(sentence) {
  return sentence.split(' ').reduce((output, word) => {
    if (word.length > output.length) {
      output.words.clear()
      output.length = word.length
    }
    if (word.length >= output.length) {
      output.words.add(word)
    }
    return output
  }, { length: 0, words: new Set })
}
const words = longestWords("The quick brown as bbbbbb fox jumped over the jumped lazy dog")
console.log(words.length);
console.log(Array.from(words.words)) //Just to make StackSnippets console show the Set's entries

A: What you can do is check if the word's length is greater or equal to the length of the first item of the array (All the items in the array should have the same length).
If so, then check if it is greater. If that is true, then set the array to that word, because you found a word that was bigger than the words in the array. Otherwise, add it to the array of the words that have the greatest length.

function longestWord(sentence) {
  sentence = sentence.split(' ');
  let theWord = sentence[0];
  var longest = 0;
  for (let i = 0; i < sentence.length; i++) {
    if (sentence[i] != "") {
      if (sentence[i].length >= theWord[0].length) {
        if (sentence[i].length > theWord[0].length) {
          longest = sentence[i].length;
          theWord = [sentence[i]];
        } else {
          theWord.push(sentence[i])
        }
      }
    }
  }
  return {
    length: longest,
    actuallWord: theWord
  }
}
console.log(longestWord("The quick brown as bbbbbb fox jumped over the lazy dog"));

A: It can also be done in single reduce.
Initiated with the object.

function longestWord(words) {
  return words
    .split(/\s+/)
    .reduce((acc, word) => {
   if(word.length > acc.length) {
    acc.length = word.length;
    acc.words = [word];
   }
   else if (word.length === acc.length) {
    acc.words.push(word);
   }
   return acc;
  }, {length:0, words:[]});
}

console.log(longestWord("The quick brown as bbbbbb fox jumped over the lazy dog"));

A: This approach doesn't have a better time complexity than the best answers here, but it does have better coefficients. (It only loops over the array of words once, no function calls except for Array.prototype.push).

let allLongestItems = items => {
  let longest = [];
  let length = 0;
  for (let item of items) {
    let len = item.length;
    if (len === length) longest.push(item)
    else if (len > length) { longest = [ item ]; length = len; }
  }
  return { items: longest, length };
};

let str = 'The quick brown as bbbbbb fox jumped over the lazy dog';
console.log(allLongestItems(str.split(' ')));


text:
Q: Is Camera Calibration needed to get measurements from an image? I am working on an android application that measures distances (euclidean distances) from a digital image. I know that in order to get real world measures like cm or meters I have to use an object with a known dimensions. Is Camera Calibration needed to get measurements from an image if I am using an object as a reference?
Thanks.

A: Antonio Criminisi's PhD thesis contains all the basics on this issue.
See this answer to a related question.

A: Short: No
Long:
Camera Calibration (parameters) are in terms of optimization an additional term (sometimes a polynom) which can improve the resulting accuracy.
Think about it as an regression: If you have enough data to fit an higher order polynomial with a better insample/outsample error then you should should use the additional parameter(s). If you don't have enough data then you overfit and the insample/outsample error will be worse.
Especially in photogrammetry camera calibration parameters need to have a certain angle and camera position or combinations of them (relative to the object which you measure). Otherwise you wont be able to calculate the parameter with an significant value.


text:
Q: Using hidden Sitemap nodes to control access In my Asp.NET C# application, I have a sitemap bound to a menu for site navigation. To control user access, I am using the NHibernate Custom Role Provider by Manuel Abadia, and setting the Roles attribute on each SiteMap node.
<siteMapNode title="Add/Modify Roles" description="Add/Modify User Roles"
url="~/MemberPages/Admin_Roles.aspx" roles="Administrator" />

Everything has been working fine so far, but now I wish to have several webpages that do not appear on the sitemap-bound menu, but still use the sitemap nodes to control user access. For example, I have a page exclusively for admins that displays all the Roles in the database (ViewPage). On that page, I have a 'Add New' button which redirects the user to another page to add a new Role (AddPage). ViewPage should exist on the menu, and AddPage shouldn't, but both should share the same access settings (only accessible by admins).
How should I go about achieving this? I am aware that I can declare the access settings in my web.config file, but I would rather avoid this as there will be many pages like this one. Also, system admins will be allowed to customize the access rules, like changing it from admin-only to admins & moderators, so it would be more convenient if the system could alter the access rules for all pages in one sitemap.

A: Thanks to MikeSmithDev's comment, I've managed to sort out a nice solution. If anyone else comes across the same problem, here's what I did:
In my SiteMap, I added a custom attribute HideFromMenu:
<siteMapNode title="Add Page" description="Page to Add stuff"
roles="Administrator" url="~/AddPage.aspx" HideFromMenu="true" />

In my Menu control, I added the OnMenuItemDataBound attribute:
<asp:Menu ID="Menu1" runat="server" DataSourceID="siteMapSource"
OnMenuItemDataBound="Menu1_MenuItemDataBound" >

And in the master's code-behind:
protected void Menu1_MenuItemDataBound(object sender, MenuEventArgs e)
{
    SiteMapNode node = (SiteMapNode)e.Item.DataItem;
    if (node["HideFromMenu"] == "true")
    {
        if (e.Item.Parent != null) //if this item has a parent..
            e.Item.Parent.ChildItems.Remove(e.Item); //use parent to remove child..
        else
            Menu1.Items.Remove(e.Item); //else.. remove from menu itself.
    }
}

Finally, to ensure the user doesn't access pages off-boundary, I added some validation in my master page..
var authorizedRoles = SiteMap.CurrentNode.Roles; //obtain the list of authorized roles for the current page

if (authorizedRoles == null || authorizedRoles.Count == 0) // no roles defined for this node
    isAuthorized = false;
else
{
    if (authorizedRoles.Contains("*")) // this page can be accessed by everyone
        isAuthorized = true;

    if (!isAuthorized)
    {
        foreach (string authorizedRoleName in authorizedRoles)
        {
            if (Roles.IsUserInRole(authorizedRoleName) == true)
            {
                isAuthorized = true;
                break;
            }
        }
    }
}

if (!isAuthorized)
    Response.End(); // unauthorised user; kill the page.

I hope this helps whoever faces the same problem. Please let me know if there are better ways to achieve the same result.


text:
Q: Transform Sql to QueryBuilder I try to transform a sql query to querybuilder.
SELECT c.id, SUM(a.view_count), dt
FROM project_content c
JOIN project_content_analytic a ON a.content_id = c.id
RIGHT JOIN (SELECT c.id, DATE_FORMAT(a.created_at, '%d-%m-%Y') dt, MAX(a.created_at) max_date
            FROM project_content c
            JOIN project_content_analytic a ON a.content_id = c.id
            GROUP BY dt, c.id) x
ON x.max_date = a.created_at and x.id = c.id
GROUP BY dt
ORDER BY `x`.`dt` ASC

I tried:
        $qb->select('c.id')
            ->addSelect('COALESCE(SUM(a.viewCount),0) as viewCount')
            ->addSelect('DATE_FORMAT(a.createdAt, \'%d-%m-%Y\') as date')
            ->innerJoin('c.analytics', 'a')
            ->groupBy('c.id')
            ->addGroupBy('date')
            ->orderBy('a.createdAt', 'DESC');

The subquery:
        $sub->select('cc.id')
            ->addSelect('MAX(aa.created_at) as maxDate')
            ->addSelect('DATE_FORMAT(aa.createdAt, \'%d-%m-%Y\') as ddate')
        $sub->innerJoin('cc.analytics', 'aa')
            ->addGroupBy('ddate')
            ->orderBy('aa.createdAt', 'DESC');

But i don't know how to join the queries.
Thank you for your help.


text:
Q: js: Regex to find a string in Knockout conditional comments I have to find a string in the Knockout conditional comment using Regex. The scenario is , There will be two kind of KnockoutConditionalStatement, this will vary based upon the user details paid/not-paid.
Statement-I - Not-paid

00

Statement-II - Paid

01

Based upon the user details, Statement-I or Statement-II will be saved in the status
var status = knockoutConditionalStatement;

Task is,

*

*have to check whether the user is Paid Customer or Not-paid Customer

*have to check whether the status having word "NotPaid" or "Paid" knockoutConditionalStatement

*if word "Not-paid" found in knockoutConditionalStatement means have to set the License as false

*if word "Paid" found knockoutConditionalStatement means have to set the License as true

I have tried like Method -I,
var status = knockoutConditionalStatement;
var license = false;
if (string.search("title=\"Paid\""))
{
    license = true;
}

else
{
    license = false;
}
// this code run without any error. but license mode did not analysed.

I have also tried like this method -II, (may be stupid)
if(String == '00')
{
    license = true;
}

else
{
    license = false;
}
// this code always getting into else{} block

Please suggest me how can I parse the knockout Conditional Statement and predict the license details.
Thanks in Advance
EDIT- 1: Working code:
var status = knockoutConditionalStatement;
var license = false;
    if (string.search("title=\"Paid\"") != -1 ) // if found
    {
        license = true;
    }

    else // not found
    {
        license = false;
    }


text:
Q: How to use built-in data instead of uploaded data I have an app like below. I want to either read-in data from file upload or use the built-in data. I thought I could put an action button and if somebody hit it the input data will mount on and it goes to the next levels. My problem is later in my real app, some widgets such as selectInput have to be updated and I want to be empty until user decided whether to use uploaded data or the built-in one.
library(shiny)

x <- mtcars

ui <- fluidPage(
  fileInput(inputId = "uploadcsv", "", accept = '.csv'),
  actionButton(inputId = "a", label = "action button"),
      selectInput("select",label = h3("Select box"),choices = "",selected = 1)
)

server <- function(input, output, session) {

  data <- reactive({
    infile <- input$uploadcsv

    if (is.null(infile))
      return(NULL)

    read.csv(infile$datapath, header = TRUE, sep = ",")
  })

  DataToUse <- NULL

  observe(!is.null(input$uploadedcsv),
               DataToUse <- data()
  )

  observeEvent(input$a,
               DataToUse <- x
  )

  observe({
    req(DataToUse)
    if (max(DataToUse$cyl) %% 4 == 0){
      numberofinterval <- max(DataToUse$cyl) %/% 4
    } else {
      numberofinterval <- (max(DataToUse$cyl) %/% 4)+1
    }

    NumPeriod <- seq(0, numberofinterval)

    updateSelectInput(session, inputId = "select",
                             choices = NumPeriod,
                             selected = NumPeriod)
  })

}
shinyApp(ui = ui, server = server)

A: Something like this should do:
library(shiny)

x <- mtcars

ui <- fluidPage(
  fileInput(inputId = "uploadcsv", "", accept = '.csv'),
  actionButton(inputId = "a", label = "action button"),
  selectInput("select",label = h3("Select box"),choices = "",selected = 1)
)

server <- function(input, output, session) {

  data <- reactive({
    infile <- input$uploadcsv

    if (is.null(infile))
      return(NULL)

    read.csv(infile$datapath, header = TRUE, sep = ",")
  })

  v <- reactiveValues()
  v$DataToUse <- NULL

  observeEvent(input$uploadcsv,{
    if(!is.null(input$uploadcsv)){
      v$DataToUse <- data()
    }
  })

  observeEvent(input$a,v$DataToUse <- x)

  observeEvent(v$DataToUse,{
    req(v$DataToUse)
    if (max(v$DataToUse$cyl) %% 4 == 0){
      numberofinterval <- max(v$DataToUse$cyl) %/% 4
    } else {
      numberofinterval <- (max(v$DataToUse$cyl) %/% 4)+1
    }

    NumPeriod <- seq(0, numberofinterval)

    updateSelectInput(session, inputId = "select",
                      choices = NumPeriod,
                      selected = NumPeriod)
  })

}
shinyApp(ui = ui, server = server)


text:
Q: Fully dynamic Stored SQL Procedures? Is it possible to have fully dynamic SQL Stored procedures? I've read up on dynamic SQL for the past few hours but couldn't find the "fully dynamic" solution that I am looking for.
I want to make a procedure that allows for imports of all files of that type, just by simply passing the file location, table name, the rows data and value types. It shouldn't care how many columns there has to be, what datatypes are used etc.
Reason for this is that we are importing a lot of different types of .csv files, and having to make a new stored procedure and table for it sounds way more time consuming than just having to make the table and use a common procedure with some passed values.
Not a master of SQL, so I sketched out what I need in C# instead:
Table createAndFillTable(string tableName, string[] columnNames, string[] columnTypes, string[] rows)
{
    var t = CreateNewTable(tableName);
    for(int i = 0; i < columnNames; i++)
    {
        t.addColumn(columnNames[i], columnTypes[i]);
    }

    foreach(var r in rows)
    {
        //Needs parsing to correct data types
        t.AddRow(r);
    }

    return t;
}

The example is with creating new tables, but the optimal solution would be to just import to an existing table by passing 2 parameters, tableName and fileLocation and let the sql handle the variable types etc. No idea if that's a better solution though.
Thanks up front!

A: Take a look at bulk insert command line tool, it's designed for this scenario.
Also, consider dynamic sql instead of dynamic stored procedure.
You can use your C# to construct dynamic SQL statements that insert batches into the database.  A long time a go, stored procedures were compiled more efficiently, but for a long time that same type of compilation is applied to regular SQL Statements.
The bulk insert command line tool already takes care of the batching stuff which can be helpful.


text:
Q: How to CSS pairs of DIV text left/right of center I'm having problems centering some divs, in which some should appear left of center, others right of center, and some on newlines. eg.

Mr

Firstname

Surname

Address

Town,

Postcode

Should appear as (text lengths vary from block to block):
                                      Mr Firstname Surname
                                             Address
                                         Town, Postcode

I've tried various uses of floats, inline-boxes, and other clever stuff, but I can't work it out for the life of me.

A: From what I understand this is what you want..
.container{
    text-align:center;
}
.container>div{
    display:inline-block;
    vertical-align:top;
}
.rightofcenter+.leftofcenter{
    display:block;
}

http://jsfiddle.net/uzbs4Lax/

A: Like this?

.center {
  text-align: center;
}

    Mr Firstname Surname

    Address

    Town, Postcode


text:
Q: Calculate a growth ratio week over week in SQL Statement I have a SQL Server table contains [date], [category], [year], [week], [Month], [Volume Received].
Here's the query I wrote for getting weekly sum[Volume] per category for last 4 years.
    SELECT Year([Date]) AS [D_Year]
       , [Week] AS [Week of Year]
       , SUM([Volume Received])AS [Received]
       , [Category]
  FROM [t1]
  WHERE YEAR(Date) in ('2016', '2017', '2018','2019')

  GROUP BY Year([Date]), [Week], [Category]

It give me this table:
 > year   week      received     category
 > 2016     1         51123         A
 > 2016     2         41123         A
 > 2016     3         21123         B
 > 2016     1         5113          D
 >  ...
 > 2017     18         1113         A
 >  ...
 > 2019     1         11134         C

I'm looking for one SQL Statement that will give me average growth ratio by week per category.
I've done it manually in EXCEL but thats not updating when I refresh my connection to SQL Server.
Final output I want is something like this:
> week      ratio      category
> 1         -0.05         A
> 1          0.15         B
> 1          0.02         C
> 1         -0.25         D
> 2          0.25         A
> 2         -0.15         B
> 2          0.02         C
> 2         -0.25         D

A: You can wrap your existing query and use window function LAG() to get the previous value of [Received]:
SELECT
    [D_Year],
    [Week of Year],
    (
        [Received]
        - LAG([Received]) OVER(PARTITION BY [Category] ORDER BY [D_Year], [Week of Year])
    ) / [Received] [Ratio]
FROM (
    SELECT
        Year([Date]) AS [D_Year],
        [Week] AS [Week of Year]
        SUM([Volume Received]) AS [Received],
        [Category]
    FROM [t1]
    WHERE YEAR(Date) IN (2016, 2017, 2018, 2019)
    GROUP BY
        Year([Date]),
        [Week],
        [Category]
) t


text:
Q: Benefits of setting PHP memory_limit to lower value for specific PHP script? I need to execute just few lines of PHP code on every single page of my website. This PHP code does not require more than 4MB memory. That is why i want to allocate just 4MB memory to all pages by using following code :
ini_set('memory_limit','4M');

Does it give any benfits in any of the following areas :
1. Website speed
2. Bandwidth optimization
3. Optimizing server memory usage

A: It won't give you any speed boost, nor bandwidth optimization, nor server memory usage.
What memory limit says is that when a script tries to use more memory, a error occurs. This is the only effect. PHP won't magically optimize memory if you reach the memory limit. If an object takes 16 bytes of memory, it will always take 16 bytes, no matter what is the actual memory limit and if it is reached or about to be reached.

*

*Website speed depends on many factors such as the size of HTML, CSS, JavaScript and images, the number of requests per page required to load all the content, the time it takes to the code-behind to process the input and generate the output, etc. Memory limit has no effect on this.

*Bandwidth usage depends on the size of HTML, CSS, JavaScript and images, the number of requests per page required to load all the content. Setting 2 MB or 200 MB as a limit won't change anything.

*Memory usage for a given script won't change neither, since it depends on the number of objects and their respective size. If and only if the different scripts are randomly taking too much memory and the only response you have is to kill them, then it will have a positive impact on memory usage: instead of filling the memory, those bogus scripts will simply be stopped by a PHP error.
I highly doubt such case exists. When a script takes too much memory, what should a developer do is to inspect it with a profiler and to fix the parts which are allocating too much memory. Killing the instances which fill up memory is the weirdest way to "solve" the problem.
So why would anyone use the memory limit?
The memory limit can be useful in debug, to be sure that your application doesn't start to take too much memory.
This doesn't replace a profiler, but can be a good solution where you don't want so use more complex tools, but still want to be alerted when, one day, your app grows enough to fill 2, 50 or 200 MB of memory.
Note: PHP documentation is very clear on that:

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server.

Source: Description of core php.ini directives, emphasis mine.


text:
Q: Dynamics 365 for Operations Online trial APIs or Web services We have setup trial Dynamics for Finance and Operations. This is actually created from here.
https://aka.ms/D365OperationTrials - We have created Finance and Operations for Enterprise.
So our URL for trial is https://d365try-31.trial.operations.dynamics.com/namespaces/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx?mode=trial
Our requirement is to fetch data(order, accounts, companies and all data available there) in our custom application.
Is there any Web Service or Apis available to achieve this ?What kind of authentication we need to do?
We also want to customize ribbon to add some button and want to add custom code in this trial version. Is this possible ? if yes, how.
Thanks for reply.

A: a. To answer your first question, yes you can use Odata feed end points exposed by D365 Unified Operations and consume in your custom application. However, the pre-requisite for this kind of integration is you will need to register your application in AAD (Azure Active Directory) where you generate the client id and secret key which can then be used in your custom application for authentication purpose. For any kind of web service integration, be it REST, SOAP or ODATA, the registration process in AAD is mandatory.
b. In the trial version link which you have put in your question, you won't get a VM access. For that you will need to either be on the Microsoft Connect site, you will need invitation to join the feedback program.
We (www.dynamicsavenue.com) host Trial D365 VMs for developers and pre-sales consultants. If you are interested, drop us a line on [dilip]dot[nair]at[dynamicsavenue]dot[com]

A: Refer link for Dynamics AX Integration samples and demos.
Dynamics-AX-Integration


text:
Q: Sending Multipart Requests in mule I have an Database connector from the selected data i use to create a file and I want to do HTTP post with file (created from the selected data in csv) along with other data (text) as attached in the screenshot. According to the mule documentation, the payload must be an outbound attachment which I am doing by using Set Attachment property. With this approach, I am setting the Content-Type for one of my attachment as application/CVS (as my file is of CVS type) and as text/plain for the other parameter. Any thoughts on achieving this? I have attached the screenshot of how the request looks like in Postman.

Below is the config XML..!!
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:file="http://www.mulesoft.org/schema/mule/file"
    xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd">
<spring:beans>
        <spring:bean id="CSFMDataSource" name="CSFMDataSource" class="oracle.jdbc.pool.OracleDataSource">
            <spring:property name="user" value="XXCCS_OSB_O"/>
            <spring:property name="password" value="OrG2_BtN"/>
            <spring:property name="dataSourceName" value="ds"/>
            <spring:property name="URL" value="jdbc:oracle:thin:@(DESCRIPTION=(CONNECT_TIMEOUT=5)(TRANSPORT_CONNECT_TIMEOUT=3)(RETRY_COUNT=1)(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=scan-nprd-2023)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=DV3CSF_SRVC_OTH.cisco.com)(SERVER=DEDICATED)))"/>
        </spring:bean>
    </spring:beans>
    <db:oracle-config name="Oracle_Configuration" dataSource-ref="CSFMDataSource" doc:name="Oracle Configuration"/>
    <http:request-config name="HTTP_Request_Configuration" host="tools-stage.cisco.com" port="80" doc:name="HTTP Request Configuration"/>

  <flow name="testFlow">
        <poll doc:name="Poll">
            <fixed-frequency-scheduler frequency="1" timeUnit="MINUTES"/>
            <logger message="Log-1" level="INFO" doc:name="Logger"/>
        </poll>
        <db:select config-ref="Oracle_Configuration" doc:name="Database">
            <db:parameterized-query><![CDATA[SELECT sol.SW_UPG_CONTRACT_NUMBER,
       sol.service_level,
       sol.BILL_TO_SITE_USE_ID,
       sol.SERVICE_BEGIN_DATE,
       sol.SERVICE_END_DATE,
       0 Net_Price,
       sol.PRODUCT_ORDER_NUMBER,
       sol.SERIAL_NUMBER,
       sol.SW_UPG_FULFILLMENT_PID,
       sol.INSTALL_SITE_USE_ID,
       sii.INSTANCE_ID,
       DECODE (sii.INSTANCE_ID, 'Yes', 'No') softline,
       '1232' cs_cse_number,
       lg.error_message
  FROM apps.XXCSS_SFM_ORDER_LINES sol,
       apps.XXCSS_SFM_ERROR_LOG lg,
       apps.XXCSS_SFM_INSTANCE_INTERFACE sii
        WHERE     1 = 1
       AND sol.order_type = 'INNVO_LINE'
       AND sol.entitlement_status IN ('CSFM_ERROR', 'QA_FAILED')
       --AND lg.so_header_id = sol.header_id
       --AND lg.so_line_id = sol.line_id
       AND lg.ERROR_TYPE = 'ERROR'
       AND sol.header_id = sii.so_header_id(+)
       AND sol.line_id = sii.so_line_id(+)
       AND lg.sfdc_case_req = 'Y'
       AND lg.sfdc_case_no IS NULL]]></db:parameterized-query>
        </db:select>
    <dw:transform-message doc:name="Transform Message" metadata:id="38e67a04-7f03-4261-a450-72b69ae0fff1">
            <dw:set-payload><![CDATA[%dw 1.0
%output application/csv
---
payload map ((payload01 , indexOfPayload01) -> {
    BILL_TO_SITE_USE_ID: payload01.BILL_TO_SITE_USE_ID as :number,
    CS_CSE_NUMBER: payload01.CS_CSE_NUMBER,
    ERROR_MESSAGE: payload01.ERROR_MESSAGE,
    INSTALL_SITE_USE_ID: payload01.INSTALL_SITE_USE_ID as :number,
    INSTANCE_ID: payload01.INSTANCE_ID,
    NET_PRICE: payload01.NET_PRICE as :number,
    PRODUCT_ORDER_NUMBER: payload01.PRODUCT_ORDER_NUMBER,
    SERIAL_NUMBER: payload01.SERIAL_NUMBER,
    SERVICE_BEGIN_DATE: payload01.SERVICE_BEGIN_DATE,
    SERVICE_END_DATE: payload01.SERVICE_END_DATE,
    SERVICE_LEVEL: payload01.SERVICE_LEVEL,
    SOFTLINE: payload01.SOFTLINE,
    SW_UPG_CONTRACT_NUMBER: payload01.SW_UPG_CONTRACT_NUMBER,
    SW_UPG_FULFILLMENT_PID: payload01.SW_UPG_FULFILLMENT_PID
})]]></dw:set-payload>
        </dw:transform-message>
        <byte-array-to-object-transformer doc:name="Byte Array to Object"/>
        <set-attachment attachmentName="filedata" value="#[payload]" contentType="application/csv" doc:name="Attachment"/>
        <set-attachment attachmentName="casedata" value="{ "Origin":"Web", "CaseNumber":"33315931584", "SearchCCOID":"vimerugu"}" contentType="text/plain" doc:name="Attachment"/>
        <set-payload value="#[null]" doc:name="Set Payload"/>

        <http:request config-ref="HTTP_Request_Configuration" path="/cvcm/was70/pwc036/caseApi/updateCaseAttach/33315931584" method="POST" doc:name="HTTP" parseResponse="false">
            <http:request-builder>
                <http:header headerName="Authorization" value="Basic Q1BFQ2FzZUFQSS5nZW46Y2FzZTFnZW4="/>

            </http:request-builder>
        </http:request>
        <logger message="#[flowVars.varCaseUpdate]" level="INFO" doc:name="Logger"/>

       <catch-exception-strategy doc:name="Catch Exception Strategy">
            <db:insert config-ref="Oracle_Configuration" doc:name="Log_DB">
                <db:parameterized-query><![CDATA[insert into XXCSS_SFM_OSB_EXECUTION_LOG (PROCESS_STATUS) values ('SFDCCaseCreationService-Exception')]]></db:parameterized-query>
            </db:insert>
            <db:insert config-ref="Oracle_Configuration" doc:name="SFDCCaseCreation- Exception">
                <db:parameterized-query><![CDATA[insert into XXCSS_SFM_CESB_LOG_ERROR ( LOG_ERROR_ID,SERVICE_NAME,SERVICE_TYPE,SERVICE_ACTIVITY,SERVICE_PAYLOAD,LOG_ERROR_STATUS,
LOG_ERROR_MESSAGE,ERROR_CODE,ERROR_MESSAGE,ERROR_DETAILS,LOG_ERROR_SEVERITY,SUGGESTED_ACTION,NOTIFY_MAIL,NOTIFY_COUNT,ATTRIBUTE_1,
ATTRIBUTE_2,ATTRIBUTE_3,ATTRIBUTE_4,ATTRIBUTE_5,ATTRIBUTE_6,ATTRIBUTE_7,ATTRIBUTE_8,ATTRIBUTE_9,ATTRIBUTE_10,CREATED_BY,CREATION_DATE,LAST_UPDATED_BY,LAST_UPDATE_DATE,BATCH_ID)
values ('1000','SFDCCaseCreationService','SFDCCaseCreationServiceType','SFDCCaseCreationServiceActivity','SFDCCaseCreationServicePayload','ERROR','','Error_Code','Error_Message',
#[exception.getSummaryMessage()],'Critical','','NA',3,'','','','','','','','','','','SFDCCaseCreationService',sysdate,'SFDCCaseCreationService',sysdate,'1000')]]></db:parameterized-query>
            </db:insert>
        </catch-exception-strategy>
    </flow>
</mule>

A: Please check if below link helps you.It tells how to read multiple files and process them.You can send them to required endpoint instead of FTP
How send a file in an HTTP request and upload it to file server via FTP in Mule


text:
Q: Transformations on a discrete function. Make it wider and flatter. Say I have a discrete function encoded in two arrays of the same size. Array $X$ and array $Y$, where each $Y[i]$ corresponds to each $X[i]$.
There are two types of modifications I need to be able to perform to my $Y[i]$ values.
1) I need to modify them as to make the function wider/narrower.
2) I need to make it flatter/sharper.
Can anyone point me towards the right direction, how can I transform a function in these ways.

A: It works similar to continuous time functions:
1) It depends on how is your function encoded. if its something like $X = sin(t)$, its enough to multiply the $t$ for a constant. $X = sin(t*A)$ the narrower or wider of the function is controlled with the constant $A$.
2) To make it flatter or sharper, the function has to be element wise multiplied for a constant, means that each element of the array has to be multiplied for the exact same constant, lets say $A$. If $A>1$ then it becomes sharper, if $A<1$ becomes flatter, and if $A = 1$ it remains the same.


text:
Q: Listening to sails socket in react I'm trying to listen to changes from Sails socket in the front-end using react.
Server listen to changes in a MongoDB Collection and blasts the changes:
// Setting up connection to MongoDB
const RTPEntryDB = sails.getDatastore("RTPEntrydb").manager;
// Switching to the appropriate collection in MongoDB
const profilesCollection = RTPEntryDB.collection("workloads");

// MongoDB Change Stream - Detect changes in DB's collection
const changeStream = profilesCollection.watch();
changeStream.on("change", function(change) {
    console.log("new change", change);
    sails.sockets.blast('newWorkloads', change);
})

This is working perfectly fine.
But on the front-end, I couldn't listen
import React, { useRef, useReducer, useEffect } from 'react';
import PropTypes from 'prop-types';

import socketIOClient from 'socket.io-client';
import sailsIOClient from 'sails.io.js';

const FetchWorkloads = (props) => {

    // Instantiate the socket client (`io`)
    const io = sailsIOClient(socketIOClient);
    io.sails.url = 'http://localhost:1337/';

    io.socket.on('connect', function onConnect(){
        console.log('This socket is now connected to the Sails server!');
    });

    io.socket.on('newWorkloads', (msg) => {
        console.log('workloads changed', msg);
    });

    return (
        <>
            {/* My Component */}
        </>

    );
}

FetchWorkloads.propTypes = {
    api: PropTypes.object.isRequired
};

export default FetchWorkloads;

I'm getting the error GET http://localhost:1337/__getcookie net::ERR_ABORTED 404 (Not Found). How do I resolve this?
Thanks

A: I resolved this by defining a custom __getcookie in routes.js as follows:
'GET /__getcookie': (req, res) => {
        return res.send('_sailsIoJSConnect();');
 },

There was also another issue with the compatibility between sails.io.js and socket.io-client. I was using the latest version of socket.io-client (v4.4) but sails was only compatible with v2.x.


text:
Q: exibir um único valor da classe Django Gostaria de saber como faço pra mostrar no meu template html, um único personagem de meu model "Personagem".
esse é meu models.py, inseri 10 personagens nessa classe via admin do django:
arquivo models.py
from django.db import models

# Create your models here.
class Personagem(models.Model):
    Nome = models.CharField(max_length=255)
    Idade = models.IntegerField(blank=True, null=True)
    Espécie = models.CharField(max_length=255)
    Gênero = models.CharField(max_length=255)
    Ocupação = models.CharField(max_length=255)
    Descrição = models.TextField(max_length=999)

    def __str__(self):
        return self.Nome

existe um personagem que seu campo nome é "Finn", queria exibir esse valor no meu html, esse é meu template:
arquivo char_info.html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Adventure Time</title>
    {% include 'parciais/head.html' %}
</head>
<body>
    <h1>{{ personagens.Nome }} </h1>

</body>
</html>

queria que nesse {{ personagens.Nome }} aparecesse o nome do personagem, porém não sei como fazer, não está retornando nada desse meu código.
minha views.py
from django.shortcuts import render, get_object_or_404
from .models import Personagem

def index(request):
    personagens = Personagem.objects.all()
    return render(request, 'home/index.html', {
        'personagens': personagens
    })

def Finn(request):
    personagens = Personagem.objects.get(Nome=personagens.Nome)
    return render(request, 'home/char_info.html', {
        'personagens': personagens
    })

arquivo urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('Finn', views.Finn, name='Finn'),
]

infelizmente não achei nenhum exemplo assim na net, só achei usando o loop {% for %}, e exibindo todos os valores, como faço pra pegar um único valor de um único campo da classe.?

A: Nessa linha:
personagens = Personagem.objects.get(Nome=personagens.Nome)

Passe como parametro o nome do personagem dessa forma:
personagens = Personagem.objects.get(Nome='Finn')

Caso você queira que a busca do personagem seja dinâmico, você deve especificar no parâmetro na url. Na urlpatterns substitua path('Finn') por path(<str:nome>) e na sua função Finn você adiciona o nome como parâmetro.
def Finn(request, nome):
    personagens = Personagem.objects.get(Nome=nome)
    return render(request, 'home/char_info.html', {
        'personagens': personagens
    })


text:
Q: TCL: detect string map substitution I have a question about the use of string map in TCL.
Is there a way to detect when this function has changed the previous value of the mapped string?
For example, in this case:
set location "default_user: admin"
set new_user "user"
set new_location [string map [list "admin" $new_user] $location]

In this case, I want to know if new_location has a different value than location (without comparing both variables, maybe there is a more elegant way).
My real case is more complicated than this one, I have a variable with the content of a html file, and I want to substitute a specific value for another one or read from another variable if there was no subtitution.
Thanks for your help, I hope everything is clear in the example above.

A: string map function does not imply a return number of replacements. In order to get the number of substitutions may be used regsub -all function that returns the value. You can also use a string first to value before string map, to learn whether there is a variable line of the desired value.


text:
Q: Unable to knit R markdown The following error is shown when I try to knit my r markdown baring in mind all code runs successfully otherwise.
Error in as.ts(x) : object 'Trainingdatar2000_m' not found
Calls: <Anonymous> ... withVisible -> eval -> eval -> acf -> na.action -> as.ts
In addition: Warning messages:
1: In has_crop_tools() :
Tool(s) not installed or not in PATH: pdfcrop, ghostcript
-> As a result, figure cropping will be disabled.
2: In has_crop_tools() :
Tool(s) not installed or not in PATH: pdfcrop, ghostcript
-> As a result, figure cropping will be disabled.
Execution halted```

A: R Markdown evaluates in its own clean session. Your notebook needs to generate all datasets needed, and will not share objects in the parent session.