text:
Q: Setting a Trend Chart to "Last 30 Days" in Qlikview 11 I am trying to create a column graph that regardless of whichever date filters are selected, it will always show only the past 30 days worth of data. I have the date values in Excel format as the field [Raw Excel Date]. No idea how to do this, as I am relatively new to Qlikview development. Any help is greatly appreciated.
Some additional info- The expression I am using right now that is displaying the trend across all dates is simply COUNT([ThingID]).

A: Lets assume that the data look like this:
(not sure in what format is the date that you have. I assume that the format is YYYY-MM-DD)
Raw Excel Date, ThingID
2014-01-01    , 10
2014-01-02    , 20
2014-01-03    , 30
2014-01-04    , 40
2014-01-05    , 50

Then you need to create one variable (vMaxDate in my case):
= date(max({1} [Raw Excel Date] ), 'YYYY-MM-DD')

The above variable will always return the max possible data in your data set no matter the selections (not only the data selection but any selection)
Then in your chart you can use expressions like this:
count({< [Raw Excel Date]=,  [Raw Excel Date] = {"<=$(=( date(vMaxDate)))>=$(=( date(vMaxDate - 30)))"}>} [ThingID])

The set analysis in the expression will ignore all selections in [Raw Excel Date] field and then will "select" (internally) only the values in [Raw Excel Date] which are less than (and equal) to the value in vMaxDate and bigger than (and equal) vMaxDate-30 values.
Stefan


text:
Q: Rowspan on Bootstrap 4 Beta 0 Grid System Hi I'm working on a eCommerce template witch uses Bootstrap 4 Beta. I made it work on mobile, but on desktop I could not figure how to make the Buy Box stay under title. On my aproach it apears under the Gallery section.
Desired Desktop

Desired Mobile

                   Gallery

                   Title

                   Buy Box

                   Description

                   Related

A: You could use the util classes to float the cols on xl widths, which would cause the "Best Buy" box to move under the title, assuming the height of the gallery is taller.
https://www.codeply.com/go/3E3Y9A5zZa

                   Gallery

                   Title

                   Buy Box

                   Description

                   Related

redpajama_set_name: RedPajamaStackExchange


text:
Q: In SrchRng, If Cell Contains Data, Paste Formula To The Right I'm working on a VBA function in Access to output a spreadsheet. Unfortunately, I'm not finding any resources online that can help with what I would like to do.
My information is output in columns ("A2:AF" & Lrow). "Lrow" defines the last row of the information. "Lrow +1" is where I have a formula totaling everything in each column.
I'd like to search ("C2:AF" & Lrow) for cells that <> "" and paste a formula (Offset 0,1) to divide that cell by the total in "Lrow +1". For example, in my picture, there is data (225.060) in C4. I am trying to paste a formula in D4 to divide C4 by C11 (or Lrow +1 since Lrow changes each time I output a spreadsheet)
Here is the code I have so far, but I'm stuck on the formula part:
Dim SrchRng As Range, Cel As Range
Dim wks As Excel.Worksheet
Set SrchRng = wks.Cells("C2:AF" & Lrow)
For Each Cel In SrchRng
     If Cel.Value <> "" Then
          Cel.Offset(0,1).Value = "=Cel.Value/(???)"

Tim Williams suggested I add my entire code because I'm getting an error with the first line of his answer. I get Error5: Invalid procedure call or argument.
Private Sub Command19_Click()
'Export to Excel
Dim rs1 As DAO.Recordset, rs2 As DAO.Recordset, rs3 As DAO.Recordset, rs4
As DAO.Recordset
Dim qdf As DAO.QueryDef
Dim prm As DAO.Parameter
Dim cnt As Integer
Dim SrchRng As Range, Cel As Range
Dim Lrow As Long, Lrow1 As Long

Dim appExcel As Excel.Application
Dim wbk As Excel.Workbook
Dim wks As Excel.Worksheet
Dim rng, rng1 As Excel.Range

Set db = CurrentDb
Set appExcel = Excel.Application
Set wbk = appExcel.Workbooks.Add
Set wks = wbk.Worksheets(1)
Set rng = wks.Range("A2")

appExcel.Visible = False

cnt = 1

Set qdf = CurrentDb.QueryDefs("qry_Comparison_Bulk")
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next

Set rs1 = qdf.OpenRecordset()

For Each fld In rs1.Fields
    wks.Cells(1, cnt).Value = fld.Name
    cnt = cnt + 1
Next fld
Call rng.CopyFromRecordset(rs1, 4000, 26)

qdf.Close
rs1.Close
Set rs1 = Nothing
Set qdf = Nothing

For Colx = 4 To 26 Step 2
Columns(Colx).Insert Shift:=xlToRight
Next

Set SrchRng = wks.Cells("C2:AF" & Lrow)
For Each Cel In SrchRng
If Cel.Value <> "" Then
    Cel.Offset(0, 1).Formula = "=" & Cel.Address & "/" & wks.Cells(Lrow +1, Cell.Column).Address
End If
Next

'Identifies the last row and row beneath it

Lrow = wks.Cells(Rows.Count, "A").End(xlUp).Row
Lrow1 = wks.Cells(Rows.Count, "A").End(xlUp).Row + 1

'Everything below is formatting

With wks.Range("A" & Lrow1, "AF" & Lrow1)
.Font.Bold = True
.Font.ColorIndex = 2
.Interior.ColorIndex = 16
.HorizontalAlignment = xlRight
End With

With wks.Range("C2:AE" & Lrow)
.NumberFormat = "0.000"
End With

wks.Cells(Lrow1, "C").Formula = "=SUM(C2:C" & Lrow & ")"
wks.Cells(Lrow1, "E").Formula = "=SUM(E2:E" & Lrow & ")"
wks.Cells(Lrow1, "G").Formula = "=SUM(G2:G" & Lrow & ")"
wks.Cells(Lrow1, "I").Formula = "=SUM(I2:I" & Lrow & ")"
wks.Cells(Lrow1, "K").Formula = "=SUM(K2:K" & Lrow & ")"
wks.Cells(Lrow1, "M").Formula = "=SUM(M2:M" & Lrow & ")"
wks.Cells(Lrow1, "O").Formula = "=SUM(O2:O" & Lrow & ")"
wks.Cells(Lrow1, "Q").Formula = "=SUM(Q2:Q" & Lrow & ")"
wks.Cells(Lrow1, "S").Formula = "=SUM(S2:S" & Lrow & ")"
wks.Cells(Lrow1, "U").Formula = "=SUM(U2:U" & Lrow & ")"
wks.Cells(Lrow1, "W").Formula = "=SUM(W2:W" & Lrow & ")"
wks.Cells(Lrow1, "Y").Formula = "=SUM(Y2:Y" & Lrow & ")"
wks.Cells(Lrow1, "AA").Formula = "=SUM(AA2:AA" & Lrow & ")"
wks.Cells(Lrow1, "AC").Formula = "=SUM(AC2:AC" & Lrow & ")"
wks.Cells(Lrow1, "AE").Formula = "=SUM(AE2:AE" & Lrow & ")"
wks.Cells(Lrow1, "B").Formula = "TOTAL (MG)"

With wks.Range("A1:AF1")
.Font.Bold = True
.Font.ColorIndex = 2
.Interior.ColorIndex = 16
.NumberFormat = "@"
.HorizontalAlignment = xlCenter
.EntireColumn.AutoFit
End With

appExcel.Visible = True

End Sub

enter code here

A: You need to set the Formula property, and the formula needs to be parseable
Something like this:
Dim SrchRng As Range, Cel As Range
Dim wks As Excel.Worksheet
Set SrchRng = wks.Range("C2:AF" & Lrow).Cells 'edit: "Cells()" >> "Range()"
For Each Cel In SrchRng
     If Cel.Value <> "" Then
          Cel.Offset(0,1).Formula = _
              "=" & Cel.Address & "/" & wks.Cells(Lrow +1, Cel.Column).address


text:
Q: Is there a way to save a WIQL query on the TFS Server? Hopefully the title says it all. I've retrieved the results of adhoc queries using the WorkItemStore.Query() method and created Query objects via the new syntax.  However after examining the object model for Query objects, QueryFolders, QueryItems and the WorkItemStore I can't find a way to create and save a WIQL query to the store/TFS Server.
Any suggestions?

A: You can use QueryHierarchy.Save Method to save the query. For example:
QueryDefinition query = new QueryDefinition("My Query", "Select * from WorkItems Where [System.AssignedTo] = @me", parentFolder);
myproject.QueryHierarchy.Save();

Check blog for more information: http://blogs.msdn.com/b/team_foundation/archive/2010/06/16/work-item-tracking-queries-object-model-in-2010.aspx


text:
Q: OnClickListener and OnTouchListener I have an 2 adapters extending BaseAdapater. The first Adapter (let's call it imageAdapter) loads an image base on an ID, the second adapter (pageAdapter) builds grids of images from the first adapter. I set the second adapter to a gallery. The idea is that I can sort have pages in an album where there are multiple pictures on each album.
Now I want to the imageViews to fire off clicks, so I set an onClickListener for each of the imageViews from the imageAdapter. The problem is that after I set the onClickListener, I cannot scroll the gallery by touch/fling/scrolling on the images anymore. I think it's an issue of parent/children event pass through thing.. but I am not sure how to fix it exactly. Please help.

A: This is a  wild guess based on an experience with ListView (where one clickListener worked but the parent onClickListener did not), but setting the onClickListener on the imageViews might have made it so they have taken away the focus, and now your other touch events are not registering.
try setting myImageView.setFocusable(false)
I am assuming that everything worked as expected before you added the onClickListener to the ImageViews.

A: I solved this problem by subclassing Gallery and overriding onDown() and onSingleTapUp(). I have to also implement a pointToChildId() method to translate motion events to item ids. =) it was a lot more work than I initially planned for, but it works now and I am quite happy with the solution.


text:
Q: How read multiple inputs from one line in java? So i have this code :
for(int i=0;i<number;i++) {
System.out.println("WHAT HOUSEHOLD DO YOU WANT TO CONNECT IN APARTMENT NO."+(i+1));
        System.out.println("1 ) OVEN");
        System.out.println("2 ) TV");
        System.out.println("3 ) VACCUUM CLEANER");
        System.out.println("4 ) REFRIGERATOR");
        int option = cin.nextInt();
        switch(option) {
        case 1: {
            for(initiereAparate e : aparate)
            fw.write((i+1)+" "+e.ob1.denumire+" "+e.ob1.material+" "+e.ob1.culoare+" "+e.ob1.origine+" "+e.ob1.consumEnergie+"\r\n"); break;
        }
        case 2: {
            for(initiereAparate e : aparate)
            fw.write((i+1)+" "+e.ob2.denumire+" "+e.ob2.material+" "+e.ob2.culoare+" "+e.ob2.origine+" "+e.ob2.consumEnergie+"\r\n"); break;
        }
        case 3: {
            for(initiereAparate e : aparate)
            fw.write((i+1)+" "+e.ob3.denumire+" "+e.ob3.material+" "+e.ob3.culoare+" "+e.ob3.origine+" "+e.ob3.consumEnergie+"\r\n"); break;
        }
        case 4: {
            for(initiereAparate e : aparate)
            fw.write((i+1)+" "+e.ob4.denumire+" "+e.ob4.material+" "+e.ob4.culoare+" "+e.ob4.origine+" "+e.ob4.consumEnergie+"\r\n"); break;
        }
        }
}

I would like to know how to read multiple inputs.For example i will type in one line 1 2 4 , and this numbers will execute 3 cases at once.In my code that i already have i can type only 1 number and it will execute only one case statement

A: You would need to change your input function to expect a string rather than an int. And then simply split your string into number and loop trought the number to execute your switch case.
P.S please note that this code is untested, don't just copy and paste it expecting everything to work perfectly. Try to understand what I did and apply it to your own context.
for (int i = 0; i < number; i++) {
        System.out.println("WHAT HOUSEHOLD DO YOU WANT TO CONNECT IN APARTMENT NO." + (i + 1));
        System.out.println("1 ) OVEN");
        System.out.println("2 ) TV");
        System.out.println("3 ) VACCUUM CLEANER");
        System.out.println("4 ) REFRIGERATOR");
        // we change this to nextLine() because we want a string.
        String option = cin.nextLine();
        // we split our string at white space, this give us an array of string;
        String[] options = option.split("\\s+");
        // we parse every options in the array
        for (int j = 0; j < options.length; j++) {
            // we need to cast the option back to an integer since, it's what we are
            // comparing.
            int currentOption = Integer.parseInt(options[j]);
            switch (currentOption) {
            case 1: {
                for (initiereAparate e : aparate)
                    fw.write((i + 1) + " " + e.ob1.denumire + " " + e.ob1.material + " " + e.ob1.culoare + " "
                            + e.ob1.origine + " " + e.ob1.consumEnergie + "\r\n");
                break;
            }
            case 2: {
                for (initiereAparate e : aparate)
                    fw.write((i + 1) + " " + e.ob2.denumire + " " + e.ob2.material + " " + e.ob2.culoare + " "
                            + e.ob2.origine + " " + e.ob2.consumEnergie + "\r\n");
                break;
            }
            case 3: {
                for (initiereAparate e : aparate)
                    fw.write((i + 1) + " " + e.ob3.denumire + " " + e.ob3.material + " " + e.ob3.culoare + " "
                            + e.ob3.origine + " " + e.ob3.consumEnergie + "\r\n");
                break;
            }
            case 4: {
                for (initiereAparate e : aparate)
                    fw.write((i + 1) + " " + e.ob4.denumire + " " + e.ob4.material + " " + e.ob4.culoare + " "
                            + e.ob4.origine + " " + e.ob4.consumEnergie + "\r\n");
                break;
            }
        }
    }
}

As Arvind Kumar Avinash
 pointed out in the comment, it is important to add the keyword break to you switch cases, this ensure that you only treat one case per iteration.

A: Yes, you can do that. You can use following idea:
String option = cin.nextLine();
String[] data=option.split(" ") // split by space character
for(int i=0;i<data.length;i++){
int option = Integer.parseInt(data[i]);
switch(option)...}


text:
Q: 2 same netowork printers in Kubuntu I wanted to install my Pixma TS6052 as a network printer. I have installed Canon drivers for my Pixma TS6052. Now when I see in my Kubuntu 20.04 2 Canon Pixma TS6000 series network printers there. They were added automatically by Kubuntu. It is nice from Ubuntu to discover my network printers, but I do not want them to be installed automatically. When I try to remove them they stay and don't go.
How can I remove them or at least leave ony one?

A: I recommend letting Kubuntu add the printer. Then when its done you add another one with your name and all the details you want. Test it from an application and from the print test page.  Then delete the printer you don't want. You can add the same printer with different details as many times as you want. If another one keeps coming back then you may have a network loop.  Another printer is sharing your printer back to you.


text:
Q: How to make mouse moves in Excel independent of screen resolution? I would like to create an Excel elearning tutorial (blended learning) for some coworkers.
I would like to use vba/vbs to move the mouse over the screen and show them where the different commands are located.
I know that this can be done, but when you change the screen resolution it no longer works.
Is there any way to make it independent of the screen resolution?
I.e.:
Move mouse slowly to "Bold"-Button and click on it, regardless of what tab is currently selected and the screen resolution?
Thanks for any suggestions.

A: *

*This would be best achieved with a screen video capture tool

*If you insist, create a pointer-shaped shape on the worksheet and use some version of the attached code to move it around
Sub MoveShape(shp As Shape, dbTop As Double, dbLeft As Double)
Dim dbVerticalIncrement As Double, dbHorizontalIncrement As Double
Dim lLoop As Long
Const lSteps As Long = 1000

dbVerticalIncrement = (dbTop - shp.Top) / lSteps
dbHorizontalIncrement = (dbLeft - shp.Left) / lSteps

For lLoop = 1 To lSteps
    shp.Top = shp.Top + dbVerticalIncrement
    shp.Left = shp.Left + dbHorizontalIncrement
    Application.Wait (Now() + 0.0000001)
Next lLoop

End Sub


text:
Q: How to deal with 3 times quotation marks in a onclick proberty of an element I have a little problem: In my project I tried to make a like button and defined a button attached to a function via onclick proberty. But now it looks like this:
<div class="post-container">
    <button class="{% if post.liked %}color-blue{% else %}color-white{% endif %}" id="post_{{ post.id|stringformat:'s' }}" onclick="postLike('{{ post.id|stringformat:'s' }}')"> {{ number_of_likes }} Like{{ number_of_likes|pluralize }}</button>
</div>

Visual Studio Code red-marks this and I am not really sure how to handle these this, since I am getting an error on onclick in the Console when I press the button...

A: To deal with 3 times quotation marks you need to switch between single and double quotes. Try doing this:
onclick='postLike("{{ post.id|stringformat:'s' }}")'

A: Inline handlers like you're currently using are universally considered to be terrible practice, and one of the reasons for that is because they have very ugly quote escaping problems when passing string parameters. (They also require global pollution and have a demented scope chain.)
Put the post ID into a data attribute instead, and attach listeners to each element in standalone JavaScript elsewhere. For example, if you're starting with
<button class="myButton" onclick="postLike('{{ post.id|stringformat:'s' }}')">

change to
<button class="myButton" data-post-id="{{ post.id|stringformat:'s' }}">

and retrieve the post ID from the button when clicked. After the HTML contains all the buttons, run the following JS:
for (const button of document.querySelectorAll('.myButton')) {
  button.addEventListener('click', (e) => {
    postLike(e.target.dataset.postId);
  });
}

You will have to tweak the selector string .myButton depending on the HTML markup around your buttons.
Another option, using event delegation on a container of all the buttons:
container.addEventListener('click', (e) => {
  if (e.target.dataset.postId) {
    postLike(e.target.dataset.postId);
  }
});


text:
Q: leaflet usage in Preact JS How can we embeded leaflet Map into Preact component. I am creating a Map widget using webpack. In the below I show you the code I implemented.
import registerCustomElement from 'preact-custom-element';
import { h , Component } from 'preact';
import {map as createMap, tileLayer} from '../../node_modules/leaflet/dist/leaflet-src.esm.js';

class mapView extends Component {

    componentDidMount() {
        let map2 = L.map('mapid').setView([51.505, -0.09], 13);
        map.addLayer(L.tileLayer(urlTemplate, {minZoom: 4}));
        const mapEl = this.shadowRoot.querySelector('#mapid');
        let map = createMap(mapEl).setView([51.505, -0.09], 13);
    }

    render (){
        return (

        )
    }
  }

registerCustomElement(mapView, "map-view");

Can we use React Leaflet in Preact? Is it possible to use? or is there any library or package to create Map in Preact?

A: This is easy. I found a Stack Overflow question related to Leaflet usage in LitElement.
My answer is similar as this, but need to do some changes, because I am creating a web component (widget).
import registerCustomElement from 'preact-custom-element';
import { Component } from 'preact';
import {map as createMap, tileLayer , icon, marker} from '../../node_modules/leaflet/dist/leaflet-src.esm.js';
import markerIcon from '../../node_modules/leaflet/dist/images/marker-icon.png';
import '../../node_modules/leaflet/dist/leaflet.css';
import "../Assets/CSS/file.css";
import 'bootstrap/dist/css/bootstrap.css';

class mapView extends Component {

    componentDidMount()  {

         var locations = [
             ["LOCATION_1", 11.8166, 122.0942],
             ["LOCATION_2", 11.9804, 121.9189],
             ["LOCATION_3", 10.7202, 122.5621],
             ["LOCATION_4", 11.3889, 122.6277],
             ["LOCATION_5", 10.5929, 122.6325]
           ];

        map = createMap('mapid').setView([51.505, -0.09], 13);

        let urlll = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?';
        map.addLayer(tileLayer(
            urlll,
            {attribution: 'Map data © OpenStreetMap contributors, Imagery © Mapbox',
            maxZoom: 18,
            tileSize: 512,
            zoomOffset: -1,
        })
        );

        let marketIcon = icon({
            iconUrl: markerIcon,
            iconRetinaUrl: markerIcon,
            iconAnchor: [5, 25],
            popupAnchor: [10, -44],
            iconSize: [25, 35],
        });

         for (var i = 0; i < locations.length; i++) {
             marker([locations[i][1], locations[i][2]], {
                 icon: marketIcon,
                 draggable: true,
             }).addTo(map);
         }
    }

    render (){
        return (

        )
    }
}

registerCustomElement(mapView, "map-view");

You need to update your webpack.config with the file loader. https://v4.webpack.js.org/loaders/file-loader/
Here is my script file code

<map-view name="map"></map-view>


text:
Q: Flash always above? Fix with css? So i recently added a video from youtube on my website and my footer is positioned as fixed, and the flash move goes above it, is it any way to fix that? Tricks and mix with css maybe?
Any help would be greatly thanked..
Preview: http://swipper.org
-swipper

A: In your YouTube iframe, add &wmode=Opaque to the URL, see here
Note that transparent wmode usually isn't necessary (vs "opaque") for positioning, unless you truly want to make part of the Flash transparent since it's more resource intensive.

A: Set the background of your Flash file to transparent by setting the wmode parameter to transparent in the embed code. See here for more info.

A: If you can use your URL like "http://www.youtube.com/embed/OleH02U_qRw?wmode=opaque", means you have to add "?wmode=opaque" at the end of URL then it will work fine for all major browsers.


text:
Q: PhoneGap Cordova 3.1.0 inAppBrowser EventListener not working I'm starting to use Cordova 3.1.0 now. I use command line to generate a project and then modify the existing code.
I copy and paste the following code from official website to test.
<!DOCTYPE html>
<html>
  <head>
    <title>InAppBrowser.addEventListener Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for device API libraries to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // device APIs are available
    //
    function onDeviceReady() {
         var ref = window.open('http://apache.org', '_blank', 'location=yes');
         ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
         ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
         ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
         ref.addEventListener('exit', function(event) { alert(event.type); });
    }

    </script>
  </head>
  <body>
  </body>
</html>

This doesn't work. There are no alert. Then I added a button to try to fire the events.
<!DOCTYPE html>
<html>
  <head>
    <title>InAppBrowser.addEventListener Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8" src="jquery.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for device API libraries to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // device APIs are available
    //
    function onDeviceReady() {
        $("#btn").click(function(){
            var ref = window.open('http://apache.org', '_blank', 'location=yes');
            ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
            ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
            ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
            ref.addEventListener('exit', function(event) { alert(event.type); });
        });
    }

    </script>
  </head>
  <body>
    <button id="btn">trigger</button>
  </body>
</html>

This time, it works with second time. It means, it doesn't work when I click the button first time. But it works at the second time when I click the button. After that, I use console log inside the callback function to debug. The logs were not appeared at the first time (appeared at the second time and third, forth....).
I don't really know why this happened. I followed all steps from official website. Creating project, installing plugin, building and so on.
Could someone give me a hand?

A: I ran into the same problem. On further investigation, I found that the events weren't firing in the emulator / browser, but fired fine on the Nexus 7 device that I do my testing on. Hope that helps!

A: It looks like it's a problem with the last phonegap/cordova version 3.1.0.
https://groups.google.com/forum/#!topic/phonegap/e5_5unC2fYs
Try an older version.


text:
Q: How to Fix CloudFormation error "Provided Load Balancers may not be valid. Please ensure they exist and try again when I try to create Autoscale group with Application load balancer with the following cloudformation yml file
    LoadBalancer:
      Type: AWS::ElasticLoadBalancingV2::LoadBalancer
      Properties:
        Type: application
        Subnets:
          Ref: VPCZoneIdentifier

    AutoScalingGroup:
      Type: AWS::AutoScaling::AutoScalingGroup
      DependsOn: LoadBalancer
      Properties:
        AvailabilityZones:
          Ref: "AvailabilityZones"
        Cooldown: 120
        DesiredCapacity:
          Ref: DesiredCapacityASG
        LaunchConfigurationName:
          Ref: LaunchConfiguration
        MaxSize:
          Ref: MaxSizeASG
        MinSize:
          Ref: MinSizeASG
        LoadBalancerNames:
          - Ref: "LoadBalancer"
        TargetGroupARNs:
          - !Ref TargetGroup

I got an error saying "Provided Load Balancers may not be valid. Please ensure they exist and try again. (Service: AmazonAutoScaling; Status Code: 400; Error Code: ValidationError; Request ID:)"

A: this error is happening because you used LoadBalancerNames for Application loadbalancer as it is noted here
to fix it : remove the  LoadBalancerNames and keep TargetGroupARNs in the properties
LoadBalancerNames:
    - Ref: "LoadBalancer"
so the yml file will be like :
    AutoScalingGroup:
      Type: AWS::AutoScaling::AutoScalingGroup
      DependsOn: LoadBalancer
      Properties:
        AvailabilityZones:
          Ref: "AvailabilityZones"
        Cooldown: 120
        DesiredCapacity:
          Ref: DesiredCapacityASG
        LaunchConfigurationName:
          Ref: LaunchConfiguration
        MaxSize:
          Ref: MaxSizeASG
        MinSize:
          Ref: MinSizeASG
        TargetGroupARNs:
          - !Ref TargetGroup

A: If you are using ansible ec2_asg module and reached here, replace load_balancers: with target_group_arns and pass the ARN of the Target Group.


text:
Q: Angular $routeProvider - Adding Route Resolve Programmatically I'd like to add Angular resolve dynamically after it was defined by the app. Imagine, my app is defined with routes like this:
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"   })
    .when("/services", {templateUrl: "partials/services.html", controller: "PageCtrl"   })
}]);

Then later I want to add/edit/override specific route(s) to resolve a promise:
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    .when("/services", {templateUrl: "partials/services.html", controller: "PageCtrl",  ,resolve:{getData: function(myService){return myService.getOffer();}}    })
}]);

How do I do this? The key here is adding after it was defined/configured. So this code will run at some point in the future.

A: It is
app.run(function ($route) {
  var route = $route.routes['/...'];
  route.resolve = route.resolve || {};
  route.resolve.someResolver = ...;
});


text:
Q: In what proportions do length and time adjust to preserve the speed of light? Suppose my friend is moving relative to me in the direction of motion of a light pulse with a speed $\frac{c}{2}$. We both have identical meter scales and clocks.Then, the universe can preserve the speed of light with respect to him by making one of these adjustments:

*

*His scale becomes half of my scale and his clock continues ticking with the same rate.

*His clock ticks slows down to half the speed of my clock, and his scale remains unchanged.

*His clock slows down to $\frac{3}{4}$ of its original speed, and his scale contracts to $\frac{2}{3}$ of its original length.
etc....
So, length and time can adjust in multiple proportions in order to preserve the speed of light. How is it decided that which parameter is adjusted to what extent?

A: From your point of view, your friend appears to be a) aging more slowly then when they are at rest with respect to you, and b) "flattened" in the direction of their movement. More specifically, these quantities are "off" by a factor of $\gamma = 1/\sqrt{1-v^2/c^2}$, where $v$ is your friend's velocity. These are always the adjustments made to "preserve" the speed of light. In your example, $\gamma = 2/\sqrt3 \approx1.15$. So, the period of your friend's clock is $1.15$ times as long as yours, and their scale is $1.15$ times shorter than yours. Indeed, this is the only possible way that $c$ can be the same in all refernce frames.
EDIT- Here, I'll derive the formulas for time dilation and length contraction mentioned above.
Imagine that your friend is in a train cart of height $L$ moving at velocity $v$. Say the cart has mirrors on the ceiling and floor, and that he has a clock which functions by ticking every time a light beam (which is repeatedly traveling from the floor to the ceiling and back) hits the floor. From his view, the period of ticks is $\Delta t = 2L/c$. However, from my point of view, say the cart travels a distance $x$ in between each tick. Then the light travels a distance $\sqrt{x^2+4L^2}$ between each tick, and so the period of ticks is (noting that $x = v\Delta t'$)
$$\Delta t' = \frac{\sqrt{x^2+4L^2}}{c} = \frac{\sqrt{v^2\Delta t'^2+4L^2}}{c}$$
Solving for $\Delta t'$ gives us
$$\Delta t' = \frac{2L}{\sqrt{c^2-v^2}} = \frac{2L/c}{\sqrt{1-v^2/c^2}} = \gamma \Delta t$$
which gives us the formula I described above. As for length contraction, suppose a particle decays in time $t$, where this time is measured from its own reference frame. Further, suppose it's traveling at a velocity $v$ towards an observer. As we saw above, to the observer, the particle will take $\gamma t$ to decay. Thus, it travels $L' = v\gamma t$ in its lifetime, from the point of view of the observer. However, in the particle's reference frame, it travels a distance $L = vt$. Thus, we have $L' = \gamma L$ (this is to say, the environment looks "shorter" to the particle in the direction of its motion).


text:
Q: Как запретить программное изменение таба в PropertyGrid? Я добавил вкладку (PropertyTab) в свой PropertyGrid и теперь должен сделать, чтобы при смене выделенного объекта эт вкладка не переключалась на "свойства".
Выбрал объект -> переключил таб в PG -> изменил объект -> таб вернулся на свойства.

A: Достаточно на клик по табу поместить в его в переменную, а потом при смене объекта вызвать из ToolStripButton PerformClick.


text:
Q: Class receiving the value reset I'm doing insert via post, but my class is getting the zero values of the inputs.
The values of the inputs are passed via variable and corrections are displayed, but at the time of the post are coming down.
The most interesting thing is if you type inside the input, then the values come correctly.
 <form method="post">

            SALDO

                <input asp-for="Caixas.ValorFinalDinheiro" name="Caixas.ValorFinalDinheiro"  id="Caixas.ValorFinalDinheiro" class="form-control finalFundo"  disabled="disabled" />

                <input asp-for="Caixas.ValorFinalCheque" class="form-control finalFundo"  disabled="disabled"/>

                <input asp-for="Caixas.ValorFinalBoleto" class="form-control finalFundo"  disabled="disabled" />

                <input asp-for="Caixas.ValorFinalCartao" class="form-control finalFundo"  disabled="disabled" />

                <input asp-for="Caixas.ValorFinalDeposito" class="form-control finalFundo" disabled="disabled"  />

                <input asp-for="Caixas.ValorFinal" class="form-control" style="background-color:#9FF781"   />

                <input type="submit" value="Confirmar o Fechamento do Caixa" class="btn btn-primary btn-sm"  />
                Retorna ao Caixa

    </form>

  [BindProperty]
        public Caixas Caixas { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {

            var C = _context.Caixas.Find(Caixas.Id);
            C.fechado = true;
            C.DataFinal = DateTime.Now;
            C.HoraFinal = DateTime.Now;
            C.FuncionarioFechamentoId = _userManager.GetUserId(HttpContext.User);
            C.ValorFinalDinheiro = Caixas.ValorFinalDinheiro;
            C.ValorFinalCheque = Caixas.ValorFinalCheque;
            C.ValorFinalBoleto = Caixas.ValorFinalBoleto;
            C.ValorFinalCartao = Caixas.ValorFinalCartao;
            C.ValorFinalDeposito = Caixas.ValorFinalDeposito;
            C.ValorFinal = Caixas.ValorFinal;

            C.ValorSaida = Caixas.ValorSaida;

            await _context.SaveChangesAsync();
            return RedirectToPage("./Index");
        }

A: Remove Caixas property and add it as parameter in your OnPostAsync method:
// [BindProperty]
// public Caixas Caixas { get; set; }

[HttpPost]
public async Task<IActionResult> OnPostAsync([FromBody]Caixas c)
{
    // ...
}


text:
Q: @media query works fine in browser resize but not on mobile This media query works fine when resizing in a browser but it doesn't work on mobile devices

@media handheld,screen and(max-width:870px)

A: Tiny little slip up in your code.  You need a space between "and" and "(".
Not sure why this happens, but it seems to bother mobile platforms while desktop platforms work fine without the space.
Hope it works out for you.


text:
Q: Docker registry and index Good day!
I have looked a ton of info about docker registry and still have some questions about it... Please, help me to understand some things about index and registry.

*

*I have installed docker-registry for private repositories. And I worked with standalone mode true. As I understand, docker registry can't authenticate users - it asks index for permissions and auth. So, I disabled standalone mode, so docker-registry needs to authenticate me by index.docker.io, but it don't work - registry allows me to push and pull any images I want. So the question is - why docker-registry doesn't try to authenticate me by i
index.docker.io?

*If docker-registry authenticates me through index.docker.io, so where authorization parameters are stored? I mean, if I want to grant user vozerov to push only to private.repo.domain:5000/vozerov repository.

*Docker searches through index. So if I want to search my images in my private repository I need to tell index.docker.io that there is new private repository. Is it real or I tell something wrong?

*I found docker-index project at github - https://github.com/ekristen/docker-index. It is alternative for index.docker.io. So, if I install it, login to it, would docker search command search through my private index or through index.docker.io?
UPD:
I worked a lot with docker-registry this night, so I have a bit confused:

*

*If standalone mode is true, then disable_token_auth is not used in
any variant. So we can:
1.1 Use this repo without auth (pull and push rights to anyone).
1.2 Use basic auth with nginx and docker login my.registry.com, so every user that have basic auth info can push and pull. So, we don't have authorization at this mode.

*If standalone mode is false, then docker-registry need to communicate with index.docker.io, but it doesn't. Two variants:
2.1. If disable_auth_token is true - I get 405 error (method not allowed), but it means that I allow anyone to push or to pull images, or not?
2.2. If disable_auth_token is false - I get 405 error...
And for 2.1 and 2.2 docker login my.registry.com not working - it shows me 404 error... Maybe it is my misconfiguration?

A:
1.I have installed docker-registry for private repositories. And I worked with standalone mode true. As I understand, docker registry can't authenticate users - it asks index for permissions and auth. So, I disabled standalone mode, so docker-registry needs to authenticate me by index.docker.io, but it don't work - registry allows me to push and pull any images I want. So the question is - why docker-registry doesn't try to authenticate me by i index.docker.io?

The private docker registry you setup has no authentication because you did not set it up. You have to use nginx as a reverse proxy to setup the authentication, and since docker client does not support basic authentication without SSL, you have to setup SSL on the reverse proxy as well.
When you push or pull, you are using the docker client. It can connect to any registry, private registry you setup, as well as docker hub. Here are several points to consider:

*

*When you fire off a docker search from your docker client, it will by default search the docker hub, and let you pull any image from there as long as it's public.

*Login is needed to push the image in Docker Hub.

*Now if you want to search your private docker registry you have to tell the docker client to search that registry in the following format:
  docker search private.repo.domain:5000/vozerov

*Now, depending on which registry you actually want to search, your private registry will require it's own authentication if you setup it up with reverse proxy, docker hub will require you to login as well if you want to use it to push images.

*The reason you can push/pull/search is because you are probably telling docker client to do those actions in your private registry only by specifying the domain_name:port/image_name, even if you don't specify and use Docker Hub by default, you will not run into authentication issues unless you try to push the image.

2.If docker-registry authenticates me through index.docker.io, so where authorization parameters are stored? I mean, if I want to grant user vozerov to push only to private.repo.domain:5000/vozerov repository.

*

*Authorization parameters are stored on your docker client machine in the following file (it's a hidden file, so use ls -la). File is called: ".dockercfg"

*Inside that file you find the login credential details of registries you tried logging into with successfully:
{
        "your_domain.com": {
                "auth": "dXNlcjE6cGFzc3dvcmQxMjM="
                "email": ""
}

*The "auth" is your base 64 encoded (username:password) credentials

*Docker private registry provides login (with help of reverse proxy) only. If you want a full blown user based authentication/authorization or access control system, you could look at solutions like Artifactory or core OS enterprise registry

3.Docker searches through index. So if I want to search my images in my private repository I need to tell index.docker.io that there is new private repository. Is it real or I tell something wrong?

*

*Docker Client search through the index.io if you don't specify you want it to search you private registry. That is default behavior of docker. Your private docker registry is totally separate from the official docker index, simply nothing to do with it. If you want to search your private registry in your Docker client, here are some commands you could use, native or curl:

*Using curl (apt-get install jq):
curl -s -X GET http://private.repo.domain:5000/v1/search | jq '.results[].name'

*Using docker search:
docker search private.repo.domain:5000/<search_keyword>

4.I found docker-index project at github - https://github.com/ekristen/docker-index. It is alternative for index.docker.io. So, if I install it, login to it, would docker search command search through my private index or through index.docker.io?

*

*Looks like that project is coming to a stop as Docker is rolling out with a new registry. Never really tried it, so I would not know which registry it searches. I would assume it is something you integrate with a private registry since Docker Hub already has it's own index, so if I were to make a guess, it would search your private registry.

A: Docker registry manages docker-images. Docker index manages authentication.
Docker registry is open source, while Docker index is not open source.
If you deploy docker-registry, you have to implement authentication over it.
Docker index can provide you private docker-registry, check this.

A: If you want authentication (and encryption) to your private registry then you will need to put nginx or apache in front of docker as a proxy and use http authentication and SSL termination there.
As far as I can tell, there isn't a way to have the docker search command search your private registry. That command only searches Docker Hub.


text:
Q: Network topology for both direct and routed traffic between two nodes Despite it's small size, this is the most difficult network design problem I've faced.  There are three nodes in this network:

*
*PC running Windows XP with an internal WiFi adapter.
*Base station with both WiFi and a Wireless Modem (WiModem)
*Mobile device with both WiFi and WiModem

The modem is a low-bandwidth but high-reliability connection.  We'd like to use WiFi for high-bandwidth stuff like file transfers when the mobile is nearby, and the modem for control information.  Here's the tricky part: we'd like the wifi traffic to go directly from the mobile to the PC, as rebroadcasting packets on the same WiFi channel takes up double the bandwidth.
We can do that with a manual configuration by giving the both the PC and the base station two IP addresses for their WiFi interfaces: one on a subnet shared with the mobile, and one on their own subnet.  The routes on the PC are set up so that any traffic going to the mobile via WiModem goes through the secondary IP address so that return traffic from the mobile also goes through the WiModem.  Here's what that looks like:

*

*PC

*

*WiFi 1: 192.168.2.10/24

*WiFi 2: 192.168.3.10/24

*Default route: 192.168.2.1

*Base Station

*

*WiFi 1: 192.168.2.1/24

*WiFi 2: 192.168.3.1/24

*WiModem: 192.168.4.1/24

*Mobile

*

*WiFi: 192.168.3.20/24

*WiModem: 192.168.4.20/24

We'd like to move to having the base station automatically configure the mobile and PC, as the manual setup is problematic when you start having multiple mobiles and PCs.  This means that the PC can only have 1 IP address and needs to be treated as being pretty simple.  Is it possible to have a setup driven by DHCP on the base station that is efficient with bandwidth?

A: If I understand correctly, the end result of this configuration would result in two network routes between the mobile and the desktop - with the possibility of routing loops if you aren't careful. I don't think DHCP would help here either. You could try RIP or other routing protocols, but I don't think that would simplify things too much.
What's more, WiFi is "point-to-point" - so I think you would have to get a second WiFi card for the desktop and configure it for a different channel and name. Then your mobile could choose which one you wanted - the router or the desktop.
If you move to multiple desktops and mobiles, then this gets exponentially worse - and more expensive.
I would choose the simpler possibility over the extra traffic: add WiFi routers and let the traffic flow. If the problem is just a transfer of files, I might use Bluetooth instead between the mobile and the desktop (assuming a one-to-one association).

A: So you want to communicate using wifi on your LAN devices, then use the wimodem for anything else?
PC > Wifi > Base Station > Wimodem > Intrnet Right?
That's easy.  Just use the base station as a router and make a default route on the base station out to your ISP's gateway.  If local devices need to talk to each other, they'll use wifi, if they need to go out to the Internet, they'll use the wimodem.
Then configure your DHCP server to hand out IPs in the range you want with the base station as the default gateway.
I'm assuming that wimodem is connecting to the internet.  You'll need to setup NAT as well probably.


text:
Q: Performance of two 1:N grouping methods Let's say we have two tables in a 1:N relationship. Now let's say on the java side you wish to structure the result data as such:
class ParentDto {
    public Long id;
    public String someColumn;
    public List<ChildDto> children = new ArrayList<>();
}

class ChildDto {
    public Long id;
    public Long parentId;
    public String someColumn;
}

IN THEORY, is it faster to perform a single sql query like:
SELECT *
FROM PARENT_DTO
    JOIN CHILD_DTO ON PARENT_DTO.ID = CHILD_DTO.PARENT_ID

and then perform a grouping operation like so on the java side
// assume that query is some api to run a query like jdbc that returns theortical type List<Row>
List<ParentDto> results = query(/* query above*/).stream()
    // assume that first value in row is ParentDto::id
    .collect(groupingBy(row -> (Long) row.get(0)))
    // after collect stream type is Map<Long, List<Row>>, whatever row type is from whatever api
    .values()
    .stream()
    // listOfGroupRows is just List<Row>
    .map(listOfGroupedRows -> {
        // assume that ParentDto constructor knows how to fetch values from first row
        ParentDto rowValue = new ParentDto(listOfGroupedRows.get(0))
        // assume that ChildDto constructor knows how to fetch values from each row
        rowValue.children = listOfGroupedRows.stream()
            .map(row -> new ChildDto(row))
            .collect(toList())
    })

OR is it faster to just run two seperate queries:
SELECT *
FROM PARENT_DTO

SELECT *
FROM CHILD_DTO

and then perform a grouping operation like so on the java side:
Map<Long, List<ChildDto>> children = query(/* second query */).stream()
    .map(r -> new ChildDto(r))
    .collect(groupingBy(ChildDto::parentId));

List<ParentDto> results = query(/* first query */).stream()
    .map(r -> {
        ParentDto dto = new ParentDto(r);
        dto.children = children.get(dto.id);
        return dto;
    })
    .collect(toList());

The first method only requires one query to the database, but has a higher volume since the number of rows returns is n * m where n is the number of rows in the parent table and m is the number of rows in the child table. It also incurs a cost on the java side of 2(n * m) (one to group, one to convert each row).
The second method incurs two queries to the database, but has lower volume because the total rows returned is n + m and each row is smaller then each row of the original join query. The java performance is better because it is n + m as well (m to group children and n to process and initialize parents).
By this logic, I would always choose option two, but I don't have a lot of practical experience with actual sql servers. Are there any situations that a more seasoned individual would/should choose option 1? Is the cost of another submission to a database ever so much that it would outweigh the complexity difference of these operations?

A: If you were using an ORM framework like Hibernate, this would be taken care of automatically behind the scenes.  And, it would be using the first version, where the join happens on the database, rather than the second version.  The reason why the first version is preferable is that databases are designed to do things like joins very efficiently.  Java would probably be less efficient at doing the same join operation.  The only reason I even see why the second version might be more efficient is the latency of data going back to and from the database.  The second version might involve transferring less data.  But, I think the penalty for doing database operations in your Java code would outweigh this.

A: I did not mean for this to be a Q&A style post, but after sleeping on it, I realized I made a faulty assumption. The different types of joins have different complexities. The complexity that I mentioned (n*m) is the memory and computation complexity of a CROSS join, where the result of the two sets is a power set of the original sets. My original join query was not a CROSS join, but an INNER join. This is, at worst, a max(n, m) in both memory complexity and computation complexity, but can be much less depending on how many rows in both tables do not associate to the other table in any way, (a parent_dto with no children is not in the result set). That is also only for a naive grouping solution, as there are many methods sql servers employ to radically improve joins like indexing operations.
So in summary, in practice for inner and left joins, method 1 has a lower complexity (max(m, n) vs. m + n) and It will resolve much faster on the sql side in practice because of indexing and other pre-calc and caching methods. The only difference would be a slight increase in network overhead (redundant normalized data).


text:
Q: How to understand the following bash script? #! /bin/sh
arg=("${@/a/b}")
arg=("${arg[@]/c/d}")
echo $arg
echo ${arg[@]}

As I run the above script with different arguments, I get the following results:
$ ./a.sh a
b
b

$ ./a.sh  a w
b
b w

The script replace the 'a' in argument with 'b'.
However, I'm confused about the use of '/', and I don't understand the expression of arg[@].

A: In parameter expansion, ${foo/a/b} replaces the first occurrence of a in the value of foo with b. For the parameter @, it replaces the first of occurrence of a in each positional argument with b, and the expansion is, as usual, a series of words corresponding to the original arguments.
$ set a ab ac
$ printf '%s\n' "$@"
aa
ab
ac
$ printf '%s\n' "${@/a/b}"
ba
bb
bc

arg=("${@/a/b}") is an array whose elements are the modified positional arguments. The / operator applied to an array expansion behaves the same way it does with $@; in this case, the first occurrence of c in each element of ${arg[@]} is replaced with a d.
$ printf '%s\n' "${arg[@]/c/d}"
ba
bb
bd

Finally, $arg by itself is equivalent to ${arg[0]}.

A: ${arg[@]/c/d}

That expands all the elements of the array arg[] and replaces all occurences of c with d.
In a bash shell try this:
a=(this is some stuff)
echo ${a[0]}
echo ${a[1]}
echo ${a[@]}
echo "${a[@]/i/X/}"

And see what happens
SUBSTRING REPLACEMENT:
${string/substring/replacement}      - replace first match of substring

${string//substring/replacement}     - replace all matches of substring

${string/#substring/replacement}     - replace substring at front of string

${string/%substring/replacement}     - replace substring at tail of string


text:
Q: Octave: how can I colorize an isosurface? I'm trying to make an isosurface be colorized by pretty much anything. The details don't matter, but at the moment it's a single-color green blob. I've tried using isocolors, and the best I could get was that the whole thing turned a shade of teal instead.

A: Huh. And I found something.
Before I had used this command (all variables are 21x21x21 matrices)
isosurface(X,H,R,DX_DT, 0)

What worked was
isosurface(X,H,R,DX_DT, 0, ones(21,21,21).*0:20)

Basically, calling
isosurface(x,y,z,val, iso, col)

I had avoided trying that because I couldn't figure out how I was supposed to format col. Were it supposed to be 3 dims, for RGB? Turns out you just need different values there, and Octave will scale them to span the whole color space, whether they go from 0-1 or 1-100.


text:
Q: Возврат вектора из функции Как правильно возвращать вектор из функции - возвращать сам вектор, указатель на него или итератор? "Правильность" интересует с точки зрения оптимального использования ресурсов и хорошего стиля программирования.
A: *

*Возврат итератора требует фактического хранения вектора после  завершения работы. Т.е. либо вектор должен быть статичным (объявлен с ключевым словом static), либо как член класса, а возвращать его будет метод, либо получен на вход функции ещё откуда-либо.
С одним лишь итератором многого не сделать: неизвестно, например, сколько ещё элементов после текущего итератора можно прочитать (для этого придётся возвращать пару итераторов, итератор и длину остатка или что-то подобное), нельзя вставить новый элемент или удалить существующий. С другой стороны, итератор концептуально представляет собою позицию в контейнере (плюс вариант отсутствия когда итератор указывает на end).
Итого: если вам нужна именно семантика указателя на позицию в контейнере, итератор вам подойдёт. В остальных случаях ничего хорошего не выйдет.

*Возврат указателя можно разделить на 2 случая: с передачей владения и без (т.е. определить, кто занимается удалением вектора).

*

*Если владение не передаётся, остаются всё те же требования к времени жизни рассматриваемого вектора, как и в предыдущем пункте. В таком случае можно также вернуть ссылку на вектор — подходы будут эквивалентны.
class Node {
  std::vector<Node> children_;
  // ...

public:
  // ...
  const std::vector<Node>& getChildren() const {
    return children_;
    // ОК: возвращаемый вектор имеет такое же время жизни, как
    // и объект, с которым мы работаем
  }
}

*Если нужно передать владение вектором вызывающему контексту, следует изначально создавать его на куче (с помощью оператора new). С точки зрения идиоматичного C++ следует использовать умные указатели shared_ptr, unique_ptr или их аналоги из библиотек вроде boost или Qt.
std::shared_ptr<std::vector<int>> getNumbers(int n) {
  auto res = make_shared<std::vector<int>>(n);
  // ...
  return res;
}

Следует заметить, что в C++11 такой подход довольно бессмыслен, поскольку там существует семантика перемещения (об этом позже). С другой стороны, shared_ptr доступен и в C++03 с TR1. Правда, он может быть не совсем эквивалентен своему собрату из 11 стандарта.

*Возврат по значению может вылиться в дорогостоящее копирование, однако:

*

*В C++11 (который на текущий момент с нами уже 4 года, между прочим) существует семантика перемещения, которая позволит вернуть вектор по значению без копирования.

*Даже для более старых стандартов многие компиляторы реализуют оптимизации Return Value Optimization и Named Return Value Optimization (подробнее о этих товарищах можно почитать у Алёны C++). Несмотря на то, что большинство компиляторов поддерживают эти оптимизации, могут существовать экзотические / старые компиляторы, не проводящие их.
Следует отметить, что эта оптимизация не всегда срабатывает. Один из таких случаев — когда возвращаемый результат зависит от пути исполнения, например
std::string toString(bool flag) {
  std::string a("True");
  std::string b("False");
  return flag ? a : b;
}

A: Давайте-ка я суммирую дискуссию в комментариях здесь.
Классическим методом является передача пустого вектора по ссылке в функцию, с тем чтобы функция его заполнила.
Затем, если вы уверены, что время жизни вектора, который вы передаёте, достаточно велико (например, вектор является полем класса), то вы можете возвращать ссылку на него. Внимание! При этом вы вводите потенциально опасную зависимость: если сам объект умрёт, ссылка на вектор тоже перестанет быт валидной! Сам объект не может знать, как его используют, и не является ли он, например, временным.
Затем, вы вполне можете вернуть вектор по значению, особенно если вы конструируете его на стеке в самой функции (и значит, не можете вернуть ссылку на него). Это кажется излишним копированием, но на самом деле оптимизатор часто может убрать ненужное копирование используя RVO/NRVO. (Вот ссылкf про это: NRVO in Visual C++ 2005). Тем не менее, иногда эта техника может всё же ведёт к копированию (например, потому, что оптимизатор не волшебник) и показывает плохие результаты.
И ещё: я бы не советовал возвращать итератор. Итераторы в C++ — ещё более хрупкая вещь, чем ссылки: любой чих в сторону вектора может его инвалидировать.

A: Например, так:
void MagicMethod(std::vector<SomeData> &destVector) {
    std::vector<SomeData> tmpVector;

    //что-то делаете с tmpVector ...

    destVector.swap(tmpVector); //вернули вектор
}


text:
Q: Why did Goetz not use volatile boolean for Listing 7.20 again? Here is the code from listing 7.20 in Brian Goetz's Java Concurrency in Practice:
public class CheckForMail {
    public boolean checkMail(Set<String> hosts, long timeout, TimeUnit unit)
            throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        final AtomicBoolean hasNewMail = new AtomicBoolean(false);

        try {
            for (final String host : hosts)
                exec.execute(new Runnable() {
                    public void run() {
                        if (checkMail(host)) hasNewMail.set(true);
                    }
                });
        } finally {
            exec.shutdown();
            exec.awaitTermination(timeout, unit);
        }
        return hasNewMail.get();
    }

    private boolean checkMail(String host) { // Check for mail return
        false;
    }
}

Referring this code, Goetz says that "The reason an AtomicBoolean is used instead of a volatile boolean is that in order to access the hasMail flag from the inner Runnable, it would have to be final, which would preclude modifying it" (p. 158).
Why does it have to be final? Couldn't you just make it a non-final boolean volatile?

A:
However why does it have to be final? Couldn't you just make it a non final boolean volatile?

hasNewMail needs to be accessed from the inner Runnable, as Goetz says.  That's an instance of an inner class.  In the most recent versions of Java, the variable being "effectively final" is a requirement for an inner class to access a local variable of a lexically enclosing method.  I think Goetz was writing at a time when the requirement was stronger: that the variable indeed be final.  The difference between "effectively final" and final doesn't really matter for this purpose, however, as either way, the variable cannot be modified.
Note, too, that the AtomicBoolean in Goetz's code is final.  It itself cannot be modified, but the value stored within can be, and this is how the program works.

A: Local variables can't be volatile. If you try to make that change, you'll see it's a compilation error.
Incidentally, as of Java 8, you no longer need to mark the variable as final; as long as it's effectively final (that is, you don't set it after the first time), Java will accept it as if you'd marked it final.


text:
Q: How to automatically call for a next iterator inside a loop I recently started scripting and am having difficulties with nested loops. I'm not getting the first iterator object from the first loop as an input to the second to run properly.
The problem itself is quite simple. I would like to change the second item ('20') on row 1 in my data to a number from the range and create a file.
So if the first number from the range is 14 then the first line of the file is (L,14,0,0,0,0) and gets a name data1.txt.
Data:
L,1,5.827,20,-4.705,0
L,20,0,0,0,0
L,12,15,0,-6,0
Original Script:
import re
from itertools import islice
import numpy as np

x = np.arange(14,30.5,0.5)
size = x.size

with open('data.txt', 'r') as line:
    for line in islice(line, 1, 2):
        re.sub(r'\s', '', line).split(',')
    nline = line[:2] + line[3:]

x = iter(x)
y = next(x)

for i in x:
    nline = nline[:2] + str(y)+ nline[3:]

with open('data.txt', 'r') as file:
    data = file.readlines()
    data[1] = nline

for i in range(1,size):
    with open('data%i.txt' %i, 'w') as file:
        file.writelines(data)

EDITED:
Ive made some progress with my script and Im almost there.
After the first loop I have the output that I need (33 cases). All I would like to do now is to write them to a 33 unique files, named data1 to data33. What seems to happen however is that the second loop iterates through the first loop another 33 times and creates 1089 cases. So what ends up in the files is only the last line of the first loop.
Any suggestions how to allow the second loop for file creation but disable it for data?
Updated Script:
import re
from itertools import islice
import numpy as np

x = np.arange(14,30.5,0.5)
size = x.size

with open('data.txt', 'r') as line:
   for line in islice(line, 1, 2):
       re.sub(r'\s', '', line).split(',')

for i in x:
    y=str(i)
    nline = line[:2] + y + line[4:]

    with open('data.txt', 'r') as file:
        data = file.readlines()
        data[1] = nline

        for i in range(1,size+1):
            with open('data%i.txt' %i, 'w') as file:
                file.writelines(data)
                print data

A: It seems you are trying to concatenate a string to a list. nline = nline[:2] + str(y)+ nline[3:]. This will yield in a type error.
Also nline[:2] gets the first 2 parts of the list, so you want to split nline[:1] to nline[2:]
Try something along the lines of:
import re
from itertools import islice
import numpy as np

x = np.arange(14,30.5,0.5)
size = x.size

with open('data.txt', 'r') as line:
    for line in islice(line, 1, 2):
     re.sub(r'\s', '', line).split(',')
    nline = line[:1] + line[2:] #not sure what this does, but this might be wrong, change accordingly

x = iter(x)
y = next(x)
temp = []
temp.append(y)

for i in x:
 nline = nline[:1] + temp + nline[2:]

with open('data.txt', 'r') as file:
    data = file.readlines()
    data[1] = nline

for i in range(1,size):
    with open('data%i.txt' %i, 'w') as file:
        file.writelines(data)


text:
Q: How to use Redis to track mobile-user-history for short term and long term Our mobile app track user history (History event is predefined with action and date)
Each mobile reporting the user history and later on can retrieve it.
I though of using the latest history(let's say 100 records) on Redis for fast retrieval and after 100 records to move the old data to some datasource.

*

*Do you think Redis is good for the short-term history retrieval?

*Which datasource would you use to keep the oldest history to be ready for retrieval?

Other ideas from your experience? Thank you.

A: Yes, the Redis is great choise for the short-term history behaviour. The LIST is well looking data structure for that:

*

*Fast insert ordered data (LPUSH for O(1))

*Fast select (LRANGE for O(S+N))

*Low memory consumption (the lowest in Redis actualy - just 21 bytes overhead per list item)

Also you may use some kind of cron job which get and insert old data to SQL like database. Use LUA scrpting to obtaine tail of logs:
local ret = {}
while tonumber(redis.call('llen', KEYS[1])) > tonumber(ARGV[1]) do
   table.insert(ret, redis.call('rpop', KEYS[1]))
end
return ret

Where KEY is your LIST key and first argument is tail size to process. This LUA script atomically cut off (and return) from all of your log entries more than ARGV1. The next step is simple foreach by list and insert to SQL database.
While user want to get all his history (in pseudo code, there require variables is total records queried by user):
ret = redis.call('LRANGE', 'myKey', 0, require)
require = require - length(ret)
if (require > 0) {
    ret += db.query('SELECT ... LIMIT ' + require)
}


text:
Q: Strange answer from StringReplace I have a list of strings and I would check if there is an empty string element, that's "", because I need to replace it with a "0". I try the following
StringReplace[{"90", "", "20"}, "" -> "0"]

and I get the following (unexpected) answer:
(* {"09000", "0", "02000"} *)

I think it is quite strange, not sure if it's a wrong or designed behavior. Any sensible explanation?
It could be related to this other strange result:
StringPosition[{"90", "", "20"}, ""]

{{{1, 0}, {2, 1}, {3, 2}}, {{1, 0}}, {{1, 0}, {2, 1}, {3, 2}}}

I don't need a solution, because the alternative to my original issue is easy, but I'm posting here just to have other opinions.

A: As others have indicated this result is not surprising at all. What you actually need is not StringReplace but ReplaceAll (/.):
{"90", "", "20"} /. "" -> "0"

{"90", "0", "20"}

A: The illustrated behavior seems reasonable to me, even if it may not seem "natural."

*

*For position or replacement a given pattern should match when it appears between any two sequences of characters, or it is at the beginning and end of a string.  A zero-length string effectively is between every pair of characters.  Why should it not match?  To keep it from matching would seem to call for an exception.  What other behavior would it have?

*If a null string did not behave as shown how would you achieve this behavior?  I believe you would need another token such as WordBoundary.  It is shorter and equally logical for "" to be used instead.

A: That is a rather slippery replacement, "Find nothing and replace it with something" Try telling the replacement that there nothing between the beginning and end
StringReplace[{"90", "", "20"}, {StartOfString ~~ "" ~~ EndOfString -> "0"}]

A: StringReplace just searched from left to right and replaced all the zero-length string for once. Here is a way to visualize the process:
i = 0; StringReplace[{"90", "", "20"},
 "" :> ToString[Style["0", {Orange, 15 + 5 i++}], StandardForm]]

The inserted zero is dyed into orange and becomes bigger every time the replacing rule is applied so you can see where and how the replacement happens.


text:
Q: addParticipant to one-on-one conversations(escalation) and startOnlineMeeting return service failure I have been having some trouble with the UCWA API when attempting to create outgoing invitations to multi-party conversations.
I have created user endpoints and am able to carry out one-on-one chats. I have also managed to join multi-party conversations on receiving incoming invitations. However,
1) When I try creating ad hoc online meetings through startOnlineMeeting or try using joinOnlineMeeting to create new meeting
2) When I use addParticipant to existing one-on-one conversation, to escalate conversation to multiparty meeting and send out a participant invite
I find that though the requests succeed with a 201, the first event I get on the channel is a onlineMeetingInvitation/participantInvitation failure with reason,
"reason": {
            "code": "ServiceFailure",
            "message": "Your request couldn't be completed."
          }
Any idea where i am going wrong? These operations seem to go smoothly when attempted through desktop client.
All help will be appreciated!


text:
Q: How to filter a Spark dataframe based on datestamp of the file Can someone let me know how filter on datestamp on file
I have the following files in their respective folders in Azure Data Lake:
adl://carlslake.azuredatalakestore.net/folderOne/filenr1_1166_2018-12-20%2006-05-52.csv

adl://carlslake.azuredatalakestore.net/folderTwo/filenr2_1168_2018-12-22%2006-07-31.csv

I have written the following script that will read all .csv files in both folders, but I only want to read .csv files in their respective folders based on current date.
test1 = spark.read.csv("adl://carlslake.azuredatalakestore.net/folderOne/",inferSchema=True,header=True)
test2 = spark.read.csv("adl://carlslake.azuredatalakestore.net/folderTwo/",inferSchema=True,header=True)

Can someone let me know how to tweak the above the read files on the folders based on current date e.g. the two .csv files are 2018-12-20 and 2018-12-22
I thought it might have been written something like
test1 = spark.read.csv("adl://carlslake.azuredatalakestore.net/folderOne/", select(current_date)inferSchema=True,header=True)

But that didn't work

A: Try something like
from datetime import datetime

today = datetime.today().date()
test1 = spark.read.csv(f"adl://carlslake.azuredatalakestore.net/
                       folderOne/*_{today}*.csv")

A: Just go with
test1 = spark.read.csv("adl://carlslake.azuredatalakestore.net/testfolder/RAW/*{today}.csv"

The other pattern *_{today}*.csv was not matching your file example above filenr1_1166_2018-12-20%2006-05-52.csv


text:
Q: AJAX jquery Form Post not working I am trying to post a form using ajax.
Right now, the code I have is
$("#sub").click(function() {
    var tag = $("#tagbar").val();
    var opinion = $("#op").val();
    alert($("#expressform").serialize());
    $.post("dbfunctions.php", $("#expressform").serialize());
});

This works, but it takes a long time to post and add to the database (thats what dbfunctions does) compared to how long it took before, when I was using a form action and refreshing the page. Why is this?
Also, if I remove the alert, the script stops working completely. I can't figure out anyway in which this makes sense.
Thanks

A: Make sure you cancel the default action of the button by returning false from the click handler:
$("#sub").click(function() {
    $.post("dbfunctions.php", $("#expressform").serialize());
    return false;
});

Also instead of subscribing for submit button clicks, it's better to subscribe to the submit event of the corresponding form directly:
$("#expressform").submit(function() {
    $.post(this.action, $(this).serialize());
    return false;
});

This way you are no longer hardcoding any urls in your javascript files. You are simply unobtrusively AJAXifying your form.

A: You can use below function for submit the data
through Ajax form Submit

$('#form1').ajaxForm({
      success:function(response){
          $('#save_data').html(response);

});

$('#btnSubmit').click(function() {

          $('#form1').submit();

  });


text:
Q: ECB: can't access / On updating to Kubuntu 12.04, and Emacs 24.1.50 - I can't access / folder in ecb's tree browser. When I try to get there, or just activate the ecb Emacs opens *tramp/scpc C* buffer and it says:
 ssh: Could not resolve hostname C: Name or service not known

it was working fine before the update to Kubuntu 12.04 and Emacs 24.1.50
All my ecb-related configs:
;; ECB and CEDET:
;; (global-ede-mode 1)
(require 'semantic/sb)
(require 'semantic/analyze)
(provide 'semantic-analyze)
(provide 'semantic-ctxt)
(provide 'semanticdb)
(provide 'semanticdb-find)
(provide 'semanticdb-mode)
(provide 'semantic-load)
(semantic-mode 1)
(setq semantic-load-turn-useful-things-on t)

(setq stack-trace-on-error t)

(require 'cedet)

(require 'ecb)
;; (ecb-activate)
;; (ecb-byte-compile)
(require 'ecb-autoloads) ;; if aren't going to turn ECB on at start up
(setq ecb-auto-activate 1)

(ecb-winman-winring-enable-support) ;; This MUST be done BEFORE the first call to any winring-command, so also before calling winring-initialize!

(setq ecb-winman-winring-name "ECB")

(global-set-key (kbd "C-x e") '(lambda ()
                                 (interactive)
                                 (ecb-activate)
                                 ))
(global-set-key (kbd "C-x E") 'ecb-deactivate)

(setq tags-revert-without-query t)

(setq ecb-cache-directory-contents nil)
(setq ecb-highlight-tag-with-point t)

(setq semantic-idle-work-parse-neighboring-files-flag nil)
(setq semantic-idle-work-update-headers-flag nil)

(setq global-semanticdb-minor-mode nil)
;; (setq semantic-imenu-index-directory nil) ;; do I have such a var at all?
(require 'semantic-load)

;; (global-semantic-auto-parse-mode -1)
(global-semantic-show-unmatched-syntax-mode -1)
(setq truncate-partial-width-windows nil)

(setq global-semantic-idle-summary-mode t)
(setq global-semantic-idle-completions-mode t)
(setq global-semantic-decoration-mode t)
(setq global-semantic-highlight-func-mode t)

(add-hook 'ecb-symboldef-buffer-sync (lambda ()
                                       (setq truncate-lines nil)
                                       ))

;; etags!
(setq tags-file-name (expand-file-name "~/its/dbes/etgs/TAGS"))

(setq ecb-highlight-tag-with-point (quote highlight-scroll))
(setq ecb-layout-name "left-symboldef")
(setq ecb-layout-window-sizes (quote (("left-symboldef" (0.2571428571428571 . 0.26666666666666666) (0.2571428571428571 . 0.2) (0.2571428571428571 . 0.23333333333333334) (0.2571428571428571 . 0.26666666666666666)) ("left8" (0.23809523809523808 . 0.2857142857142857) (0.23809523809523808 . 0.21428571428571427) (0.23809523809523808 . 0.2857142857142857) (0.23809523809523808 . 0.17857142857142858)))))
(setq ecb-options-version "2.40")
(setq ecb-source-path (quote (("/home/boris/its/plts" "plts"))))
(setq ecb-tip-of-the-day nil)
(setq ecb-tree-incremental-search (quote substring))

as You see - no C: in there.
Edit 2:
I've found to have a ~/.emacs.d/tramp file, and it has:
;; -*- emacs-lisp -*- <12/05/03 19:12:12 /home/boris/.emacs.d/tramp>
;; Tramp connection history.  Don't change this file.
;; You can delete it, forcing Tramp to reapply the checks.

((["scpc" nil "C" nil]
  nil))

I've deleted that file, then have opened the emacs, have activated ECB, tried to get to / in the directory tree, it made the same error. Then, after I've close emacs - it made the same tramp file. Seems like it is writter somewhere in a tramp - in the latest emacs sources.

A: I am using Kubuntu 12.04 and ran into this same problem; don't know if it is specific to Kubuntu or 12.04 generally.
Somehow the "C:\nppdf32Log\debuglog.txt" file (http://askubuntu.com/questions/144408/what-is-the-file-c-nppdf32log-debuglog-txt) was being picked up by the internal ecb-filename-cache - I couldn't figure out exactly how ecb-filename-cache was being populated but I was able to see this by running ecb-remote-patch-cache-dump - this was the source of the tramp error for me.  To get around it, I removed all semantic cache directories, all traces of the debuglog.txt file and any tramp files that I could find.  Viola, ECB works again.

A: Weird, maybe it's reusing an old C:\ something in your old trammp file?  also reading this scpc link maybe your newly updated kubuntu doesn't support it?  Try the command the link says to see if it works.  Sounds more like a tramp issue than an ECB.

A: I ran into the same problem, and found that customizing the source path (as noted in ECB First Steps) fixed the problem for me.


text:
Q: Highlight a node connected with maximum links I have build a force directed graph for the sample data which I have
My code for this is here

My Question is at the time the graph loads I need to calculate the node which is connected with maximum nodes(i.e Music node which is connected with maximum number of nodes) and at the time of load It should be highlighted and display information.
How can I achieve this ?


text:
Q: Failed to start the following executable, Failed to start the following executable, \bin\javac.exe -g -classpath C:\Users\user\Documents -d C:\Users\user\Documents C:\Users\user\Documents\Kwame.java For help, please refer to http://www.jcreator.com/installation.htm.
For some reason it keeps doing this no matter what code I write and I have no idea why.
import java.io.*;
import java.util.*;

public class KyeretwieTestProgram1113 {
    public KyeretwieTestProgram1113() {
        Scanner kbInput = new Scanner(System.in)
        System.out.println(Enter the high temperature on day 1:);
        double d = kbInput.nextDouble();
        System.out.println(Enter the high temperature on day 2:);
        double da = kbInput.nextDouble();
        System.out.println(Enter the high temperature on day 3:);
        double a = kbInput.nextDouble();
        System.out.println(Enter the high temperature on day 4:);
        double day = kbInput.nextDouble();
        System.out.println(Enter the high temperature on day 5:);
        double y = kbInput.nextDouble();
    }
}

How can I solve this issue?

A: The error shown is not related to the code but rather the Java compiler or javac. Make sure you have the JDK installed and can run a simple 'Hello world' program before slapping code here.


text:
Q: Zeroes of ODE in normal form I need to find the number of zeroes of an ODE:
$$y"+q(x)y=0$$
when $q(x)>0$ but monotonic decreasing. For instance:
$$y"+ \frac{y}{x^2} =0$$
where $x\in [1, \infty)$.
How can I use the Strum-Comparision Theorem to estimate the number of zeroes of it's solution?
(P.S. Here the number of zeroes won't be infinitely many contrary to the general case of $q(x)\gt 0$ and monotonic increasing.)

A: The example you can solve exactly, as that is Euler-Cauchy,
$$
x^2y''(x)+y(x)=0\implies y(x)=Ax^{\frac12}\cos\left(\frac{\sqrt3}2\ln(x)+B\right)
$$
giving infinitely many zeros.
In the more general case, you can get a first impression by using the WKB approximation
$$
y\approx Aq(x)^{-\frac14}\cos\left(B+\int_1^x \sqrt{q(s)}\,ds\right)
$$
to get a general idea if the number of zeros will be finite or infinite.
The WKB approximation can also be worked backwards to get expressions that are compatible with an exact approximation of the comparison theorem, see https://math.stackexchange.com/a/2075892 for an example. Note that this works originally for $q$ becoming very large, opposite to the current case.


text:
Q: PHPUnit code coverage in NetBeans fails with Yaml dependency I am trying to get the code coverage in NetBeans working, but I am stuck on error that the PHPUnit gives me:
"/usr/bin/php" "/usr/bin/phpunit" "--colors" "--log-junit" "/tmp/nb-phpunit-log.xml" "--bootstrap" "/home/btekielski/Dokumenty/Projects/PlanQ/src/tests/bootstrap.php" "--coverage-clover" "/tmp/nb-phpunit-coverage.xml" "/usr/local/netbeans-7.4/php/phpunit/NetBeansSuite.php" "--run=/home/btekielski/Dokumenty/Projects/PlanQ/src/tests"
PHPUnit 3.7.28 by Sebastian Bergmann.

PHP Fatal error:  Uncaught exception 'PHPUnit_Framework_Error_Warning' with message 'include_once(Symfony/Component/Yaml/Yaml.class.php): failed to open stream: No such file or directory' in /home/user/Projects/src/tests/bootstrap.php:65
Stack trace:

I have a custom auto loader function in bootstrap which looks like following:
function loadClass($class) {
    if (empty($class) || $class == 'parent') {
        return;
    }
    $throw = false;

    if (strpos($class, 'PHPExcel') !== false) {
        return;
    }

    $file = str_replace('\\', DIRECTORY_SEPARATOR, $class) . CLASS_FILE_EXTENSION;
    include_once($file);

    if (!class_exists($class, false) && !interface_exists($class, false)) {
        if ($throw) {
            trigger_error(
                    "Class file '" . $file . "' do not provide class '" .
                    $class . "'", E_USER_ERROR
            );
        }

        return;
    }
}

I'd appreciate any hints...

A: The include_once() you called has a relative path to Symphony, indicating it is below the current directory. Is this the case, or are you in the wrong directory for this relative path to work?


text:
Q: Sort contents alphabetically So I am appending the following after an AJAX call, and this AJAX call may happen several time, returning several data items. And I am trying to use Tinysort [http://plugins.jquery.com/project/TinySort] to sort the list everytime, so the new items added are integrated nicely and sorted alphabetically.
It unfortunately doesn't seem to be working. Any ideas? I mean, the data itself is being correctly appended, but unfortunately the sorting isn't occurring.
var artists = [];

$.each(data.artists, function(k, v) {
 artists.push('

' + v.name + '
' + v.events + ' upcoming gig');

 if (v.events != 1) {
  artists.push('s');
 }

 artists.push('

Last

');
});

$('div.artists p').remove();
$('div.artists div.next').remove();
$('div.artists').append(artists.join('')).append('
Next
');
$('div.artists section').tsort('section[id]', {orderby: 'id'});

Thanks!

A: I suggest to sort data on the server side. Not sure what is your data source but in most cases it should be much easier to move sorting logic to the server.
With sorting in Javascript you may face problems in different browsers when your data will contain non-ascii characters (some browsers can sort such data and some not). This leads to different behavior between browsers which is not expected as I think.


text:
Q: Scheduling Oracle sql files using Unix based SAS enviornment I have bunch of SQL queries that run against an Oracle database. Is there a way to schedule these .sql files using UNIX Based SAS, so they can execute one after another at certain time of day?

A: If they are .sql files, why do you want to schedule them using SAS? Are they SAS programs? If not, I would do one of three things, depending on my constraints:
1) Convert the .sql files to stored procedures and call them from DBMS_SCHEDULER within Oracle, since Oracle has a fantastic job scheduling subsystem (actually multiple variants) that protects against duplicate jobs among other issues, and you get transactional control, auditing and logging. http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_sched.htm
2) If converting them to stored procs is too much, then call the .sql scripts directly from DBMS_SCHEDULER with DBMS_SCHEDULER.CREATE_PROGRAM() and then schedule that program with DBMS_SCHEDULER.CREATE_JOB.
3) Use cron or atrun to schedule batch / shell script wrappers that call sqlplus to run .sql files.
If the question is specifically how to do this with SAS, then DBMS_SCHEDULER can still execute external SAS programs using option (2) above.


text:
Q: Populating column based on existing columns in MySQL 5.6 and ORACLE 11 and ORACLE 12 I have a table where one column is of varchar type which contains value as '1.2.1', '1', '0.2' etc.
In general there will be max 3 numbers separated by decimal (.)
I need to create 3 new columns of Integer type to save these 3 numbers.
Sample data looks like this.

Also, the data can contain some string value as well but its fixed that it will be one string appended at last, separated by hyphen (-). For Example 1.2.1-xyz. If the data is like this, the string value should go to fourth column.
This case data will look like below:

This is the query which I have written to achieve this requirement.
Please find below the SQLFiddle
http://sqlfiddle.com/#!9/5aaeb4/1
Is there any better way of doing this? I am new to DB side so please suggest some optimized approach of achieving this.

A: In MySQL, we can use Substring_Index() function as well as User-defined variables. Variables help us in avoiding redoing certain string operations again and again.
Schema (MySQL v5.7)
CREATE TABLE IF NOT EXISTS `table1` (
  `mainCol` varchar(45) NOT NULL
) DEFAULT CHARSET=utf8;
INSERT INTO `table1` (`mainCol`) VALUES
  ('1.2.1'),
  ('0.2'),
  ('1'),
  ('1.2.1-xyz'),
  ('1.2');

Query
SELECT
  mainCol,

  @first := SUBSTRING_INDEX(mainCol, '.', 1) AS col1,

  TRIM(LEADING '.' FROM
       REPLACE(@second := SUBSTRING_INDEX(mainCol, '.', 2),
               @first,
               '')
      ) AS col2,

  @fourth := CASE WHEN INSTR(mainCol, '-')
                  THEN SUBSTRING_INDEX(mainCol, '-', -1)
                  ELSE ''
             END AS col4,

  REPLACE(TRIM(LEADING '.' FROM
               REPLACE(SUBSTRING_INDEX(mainCol, '.', 3),
                       @second,
                       '')
               ),
          CONCAT('-', @fourth),
          '') AS col3
FROM table1
CROSS JOIN (SELECT @first := '',
                   @second := '',
                   @third := '',
                   @fourth := '') AS user_vars;

Result
| mainCol   | col1 | col2 | col4 | col3 |
| --------- | ---- | ---- | ---- | ---- |
| 1.2.1     | 1    | 2    |      | 1    |
| 0.2       | 0    | 2    |      |      |
| 1         | 1    |      |      |      |
| 1.2.1-xyz | 1    | 2    | xyz  | 1    |
| 1.2       | 1    | 2    |      |      |

View on DB Fiddle


text:
Q: Opción seleccionada por defecto Estoy llenando un select con angular 2 de la base de datos, entonces lo que necesito es que al momento que cargue la página principal aparezca como seleccionado el "Seleccione un elemento" que contiene el valor 0,
¿Como puedo mandar por default el value para que al momento que carge la página venga seleccionado?

            {{'Empresa'}}

              <select [(ngModel)]="model.IdEmpresa"   name="IdEmpresa" class="form-control">
              <option value="0" disabled>Seleccione un elemento</option>
              <option *ngFor="let empresa of empresaArray"   [value]="empresa.id" >{{empresa.nombre}}</option>
              </select>

A: Buenos dias, yo he hecho algo parecido pero en versiones anteriores a Angular 2, en la 1,6 para ser exacto, y lo hice de esta manera, no he estudiado versiones posteriores pero pues de pronto te pueda servir si es que entendi bien la pregunta.

               Tipo Documento:

                 <select name="" ng-model="tipoDocumento" class="form-control" id="selectDocumento" >
                   <option value="">Seleccionar</option>
                   <option ng-repeat="documento in tableTipoDocumento" value="{{documento.id_tipoDocumento}}">{{documento.desc_tipo_documento}}</option>
                 </select>

              {{tipoDocumento}}

A lo que daría como resultado:

Ahora quedaria el Select despues de seleccionar alguna opcion:

Obteniendo el ID del elemento con el atributo Value
value="{{documento.id_tipoDocumento}}"

Espero haber sido de ayuda!


text:
Q: Functions from empty set in Coq I am new to Coq. I noticed it was possible to define the empty set in Coq using
Inductive Empty_set : Set :=.

Is it also possible to define the function from the empty set to another general set/type ?
If so how ?

A: Yes. Just use pattern matching:
Definition of_Empty_set T (x : Empty_set) : T :=
  match x with end.


text:
Q: Adding routes inside a component in react router dom version 6 I am trying to migrate from react router 5 to react router 6. I coded a simple frontend where only if the login button is clicked you can go to the profile page. and inside profile page there are two links to view profile and edit profile.
//App.js
import './App.css';

import Header from './components/Header';
import HomePage from './pages/HomePage';
import AboutPage from './pages/AboutPage';
import Profile from './pages/Profile';
import NotFoundPage from './pages/NotFoundPage';
import Post from './pages/Post';
import GroupProfile from './pages/GroupProfile';

import {BrowserRouter as Router, Routes, Route, Navigate} from 'react-router-dom';
import {useState} from 'react';

function App(){
    const [login, setLogin] = useState(false);
    const [glogin, setGlogin] = useState(false);
    return(

            <Router>

                <button onClick={() => setLogin(!login)}> {!login?"Login":"Logout"} </button>
                 |
                <button onClick={() => setGlogin(!glogin)}> {!glogin?"GroupLogin":"GroupLogout"} </button>
                <Routes>
                    <Route path='/' element={<HomePage />} />
                    <Route path='/about' element={<AboutPage />} />
                    {/*<Route path='/prof'>
                        {login ? <Profile />:<Navigate to='/' />}  Nope, in react_router_dom6 putting other things rather than function that returns pages are not valid
                    </Route>*/}
                    <Route path='/group' element={<GroupProfile g_login={glogin} />} />
                    <Route path='/prof/*' element={<Profile l_ogin={login} />} />

                    <Route path='/post/:id' element={<Post />} />
                    <Route path='*' element={<NotFoundPage />} />

                </Routes>
            </Router>

    )
}

export default App;

And these are groupprofile page and profile page.
GroupProfile.js
import React from 'react';
import {useEffect} from 'react';
import {useNavigate} from 'react-router-dom';

function GroupProfile({ g_login }){
    let nav = useNavigate();
    useEffect(() => {
        if (!g_login) {
            nav("/");
        }
    },[g_login, nav])  //you know useEffect hook, if dependancy list is given, when they change then hook will be triggered.

    return(

This is the GroupProfile

    )
}

export default GroupProfile;

Profile.js
import React, {useEffect} from 'react';
import {Route, Routes, useRouteMatch, Link, useNavigate, useLocation} from 'react-router-dom';

import EditProfile from '../components/EditProfile';
import ViewProfile from '../components/ViewProfile';

/*
function Profile(){
    const { path, url } = useRouteMatch();
    //console.log(useRouteMatch());

    return(
        <>

Profile Page

<Link to={`${url}/viewprofile`}>View Profile</Link>

<Link to={`${url}/editprofile`}>Edit Profile</Link>

            <Route path={`${path}/viewprofile`} component={ViewProfile} />
            <Route path={`${path}/editprofile`} component={EditProfile} />
        </>
    )
}
*/
function Profile({l_ogin}){
    let nav = useNavigate();
    let location = useLocation();
    //console.log(location)
    useEffect(() => {
        if (!l_ogin) {
            nav("/");
        }
    },[l_ogin, nav])  //you know useEffect hook, if dependancy list is given, when they change then hook will be triggered.
    return(

Congrats! you made it to the profile page mate...

<Link to={`${location}/viewprofile`}>View Profile</Link>

<Link to={`${location}/editprofile`}>Edit Profile</Link>

            <Routes>

                <Route path={`${location}/viewprofile`} element={<ViewProfile />} />
                <Route path={`${location}/Editprofile`} element={<EditProfile />} />
            </Routes>

    )
}

export default Profile;

I have commented the Profile component that works in react router version 5 and it is supposed to navigate to /prof/viewprofile when View Profile link is clicked. ViewProfile.js and EditProfile.js are simple components
ViewProfile.js
import React from "react";

const ViewProfile = () => {
    return(

This is what you have to see in the profile.

    )
}

export default ViewProfile;

The code I used in react router 5 works fine and when I clicked View Profile it navigates to /prof/viewprofile without any problem. But when I use react router 6 it doesn't navigate to /prof/viewprofile and it just stays in the /prof, but url changes to something like /prof/[object%20Object]/viewprofile. Can someone show me what am I doing wrong here?

A: location is an object, and if this is what you were trying to use you'd need location.pathname, but this is not what you want to try and use to build paths for descendent routes. When rendering Routes components and descendent routes, the routes are already built relative to the parent route. There is no need to try and build/implement the relative-ness yourself.
Example:
function Profile({ l_ogin }){
  const navigate = useNavigate();

  useEffect(() => {
    if (!l_ogin) {
      navigate("/", { replace: true });
    }
  }, [l_ogin, navigate]);

  return(

Congrats! you made it to the profile page mate...

<Link to="viewprofile">View Profile</Link>

<Link to="editprofile">Edit Profile</Link>

      <Routes>
        <Route path="viewprofile" element={<ViewProfile />} />
        <Route path="editprofile" element={<EditProfile />} />
      </Routes>

  );
}

If you wanted to keep the first route implementation you were trying to use then this is the correct syntax. You still need to render the routed content on the element prop.
<Route
  path='/prof'
  element={login ? <Profile /> : <Navigate to='/' replace />}
/>

A: I realize these are the docs for v5: https://v5.reactrouter.com/web/api/Hooks/uselocation
But I suspect that before you didn't use the useLocation() hook by default?
From the url that gets parsed you can tell that the location variable not a string but an object [object%20Object]
Could you try: ${location.pathname} where you now have ${location} ?


text:
Q: how to fix Incorrect syntax near 'value' I am trying to make feedback form and I am getting syntax near 'value' error
my asp.net code is below , 'i' tage is used for adding icons
<form id="form1" runat="server">

                                What do you think of this?

                                <asp:RadioButtonList CssClass="size" ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal">
                                    <asp:ListItem Text='sentiment_very_dissatisfied' Value="1"></asp:ListItem>
                                    <asp:ListItem Text='sentiment_dissatisfied' Value="2"></asp:ListItem>
                                    <asp:ListItem Text='sentiment_satisfied' Value="3"></asp:ListItem>
                                    <asp:ListItem Text='sentiment_satisfied_alt' Value="4"></asp:ListItem>
                                    <asp:ListItem Selected="True" Text='sentiment_very_satisfied' Value="5"></asp:ListItem>
                                </asp:RadioButtonList>

                                Your Feedback
                    <asp:RequiredFieldValidator ForeColor="#EB3E59" ID="RequiredFieldValidator2" runat="server" ErrorMessage=" *" ControlToValidate="feedTxt"></asp:RequiredFieldValidator>

                            <asp:TextBox CssClass="input" placeholder="enter your feedback" ID="feedTxt" runat="server" MinLength="10" MaxLength="100" TextMode="MultiLine" Height="50px"></asp:TextBox>

                                how likely are you to recommend us to your friends and colleagues?

                                <asp:RadioButtonList CssClass="size" ID="RadioButtonList2" runat="server" RepeatDirection="Horizontal">
                                    <asp:ListItem>1</asp:ListItem>
                                    <asp:ListItem>2</asp:ListItem>
                                    <asp:ListItem>3</asp:ListItem>
                                    <asp:ListItem>4</asp:ListItem>
                                    <asp:ListItem Selected="True">5</asp:ListItem>
                                    <asp:ListItem>6</asp:ListItem>
                                    <asp:ListItem>7</asp:ListItem>
                                    <asp:ListItem>8</asp:ListItem>
                                    <asp:ListItem>9</asp:ListItem>
                                    <asp:ListItem>10</asp:ListItem>
                                </asp:RadioButtonList>

                            <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
                            <asp:TextBox CssClass="size input" ID="TextBox1" runat="server" placeholder="email ( optional )" TextMode="Email"></asp:TextBox>
                            <asp:Button CssClass="input loginbox_submit" ID="Submit" runat="server" Text="Submit" Height="42px" OnClick="Submit_Click" />
                        </form>

I think I got error cmd.parameters.........
my c#
 protected void Submit_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
            con.Open();
            string feed;
            if (string.IsNullOrEmpty(TextBox1.Text.Trim()) || Session["email"] == null) //textbox1 takes email which is optional
            {
                feed = "insert into feedback (feedback,stars,recommend) value(@feedback,@stars,@recommend)";
            }
            else
            {
                feed = "insert into feedback (email,feedback,stars,recommend) value(@email,@feedback,@stars,@recommend)";
            }

            SqlCommand cmd = new SqlCommand(feed, con);
            if (!(string.IsNullOrEmpty(TextBox1.Text.Trim()) || Session["email"] == null))
            {
                cmd.Parameters.AddWithValue("@email", TextBox1.Text);
            }
            cmd.Parameters.AddWithValue("@feedback", feedTxt.Text);
            cmd.Parameters.AddWithValue("@stars", RadioButtonList1.SelectedValue);
            cmd.Parameters.AddWithValue("@recommend", RadioButtonList2.SelectedValue);
            cmd.ExecuteNonQuery();
            passbox.Visible = false;
            passdone.Visible = true;
            con.Close();
        }

in this case I got System.Data.SqlClient.SqlException: 'Incorrect syntax near 'value'.'
I am not good in c#
please help ASAPThank You

A: This is not a C# issue, it is a SQL issue :)
Replace value with values in your SQL query.