text:
Q: Putting PHP variables into javascript I've created a simple theme options page for my site. The options page contains three input fields. I can output the the fields by using get_option.
The three fields are called using the following:
<?php echo get_option( 'map_zoom' ); ?>
<?php echo get_option( 'map_longitude' ); ?>
<?php echo get_option( 'map_latitude' ); ?>

These variables are for controlling the zoom level, the longitude and latitude of a map. I have a javascript file that renders the map using the google maps api. I'd like to put these variables into that javascript file. When I put the javascript into a php file and add these variables the map renders but I lose all the rest of my map functions which are considerable. Also I then have to call the script php in the header instead of using wp_enqueue_script in the functions file.
Here is the map javascript:
var infowindow = new google.maps.InfoWindow();
var shadow = new google.maps.MarkerImage('/wp-content/themes/re-aligned/images/shadow.png', new google.maps.Size(37, 34) );

var markers = [];
var categories = [
    {
        name: 'People',
        slug: 'people',
        url: 'marker-people.png'
    }, {
        name: 'Works',
        slug: 'works',
        url: 'marker-works.png'
    }, {
        name: 'Discourse',
        slug: 'discourse',
        url: 'marker-discourse.png'
    }, {
        name: 'Other',
        slug: 'other',
        url: 'marker.png'
    }
];

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

function initialize() {

    jQuery('body').append(jQuery('

Map Categories

'));

    // add checkboxes to toolbar
    for (var i = 0; i < categories.length; i++) {
        jQuery('#toolbar').append(
            jQuery('<input />', {
                type: 'checkbox',
                id: 'tog-marker-'+categories[i].slug,
                name: 'tog-marker-'+categories[i].slug,
                class: 'squaredTwo',
                value: i,
                checked: true
            })
        );
        jQuery('#toolbar').append(
            categories[i].name
        );
    }

    jQuery('#toolbar > input[type=checkbox]').click(function() {
        for(var i = 0; i < markers.length; i++) {

            if(markers[i].icon.url.endsWith(categories[jQuery(this).val()].url)) {
                if(jQuery(this).is(':checked')) markers[i].setVisible(true);
                else markers[i].setVisible(false);

            }
        }
    });

    // Create an array of styles.
    var styles = [

        {
            "featureType": "landscape.natural",
            "stylers": [
                { "color": "#ff412d" },
                { "visibility": "on" }
            ]
        },{
            "featureType": "administrative.land_parcel",
            "stylers": [
                { "visibility": "off" }
            ]
        },{
            "featureType": "administrative.neighborhood",
            "stylers": [
                { "visibility": "off" }
            ]
        },{
            "featureType": "administrative.province",
            "stylers": [
                { "visibility": "simplified" }
            ]
        },{
            "featureType": "administrative.country",
            "stylers": [
                { "visibility": "on" }
            ]
        },{
            "featureType": "water",
            "stylers": [
                { "color": "#ffebc5" }
            ]
        },{
            "featureType": "road",
            "stylers": [
                { "visibility": "simplified" },
                { "color": "#ffebc5" }
            ]
        },{
            "featureType": "poi",
            "stylers": [
                { "visibility": "off" }
            ]
        },{
            "featureType": "road.highway",
            "stylers": [
                { "visibility": "off" }
            ]
        },{
            "featureType": "administrative.locality",
            "stylers": [
                { "visibility": "off" }
            ]
        },{
            "featureType": "administrative.country",
            "elementType": "geometry",
            "stylers": [
                { "visibility": "off" }
            ]
        }
    ];

    // Create a new StyledMapType object, passing it the array of styles,
    // as well as the name to be displayed on the map type control.
    var styledMap = new google.maps.StyledMapType(styles,
        {name: "Styled Map"});

    // Create a map object, and include the MapTypeId to add
    // to the map type control.
    var mapOptions = {
        zoom: <?php echo get_option( 'map_zoom' ); ?>,
        scrollwheel: true,
        center: new google.maps.LatLng(<?php echo get_option( 'map_latitude' ); ?>, <?php echo get_option( 'map_longitude' ); ?>),
        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'],
        mapTypeControl: true,
        mapTypeControlOptions:  {
            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
            position: google.maps.ControlPosition.BOTTOM_CENTER
        },
        panControl: false,
        panControlOptions: {
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE,
            position: google.maps.ControlPosition.LEFT_CENTER
        },
        scaleControl: false,
        scaleControlOptions: {
            position: google.maps.ControlPosition.LEFT_CENTER
        },
        streetViewControl: false,
        streetViewControlOptions: {
            position: google.maps.ControlPosition.LEFT_TOP
        }
    };
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);

    var oms = new OverlappingMarkerSpiderfier(map);

    //Associate the styled map with the MapTypeId and set it to display.
    map.mapTypes.set('map_style', styledMap);
    map.setMapTypeId('map_style');

    oms.addListener('click', function(marker, event) {
        infowindow.setContent(marker.desc);
        infowindow.open(map, marker);
    });

    for (var i = 0; i < locations.length; i++) {
        var marker = new google.maps.Marker({
            position: locations[i].latlng,
            desc: locations[i].info,
            icon: locations[i].marker,
            shadow: shadow,
            map: map
        });
        oms.addMarker(marker);
        markers.push(marker);
    }

}

How can i correctly output the variables into the javascript file?
UPDATE:
After taking on board the information about wp_localize_script I've done the following:
I've put this in my functions.php
wp_enqueue_script( 'map-script' );
    $object = array(
        'zoom' => get_option('map_zoom'),
        'longitude' => get_option('map_longitude'),
        'latitude' => get_option('map_latitude'),
    );
wp_localize_script('map-script', 'JSObject', $object);
    }

and used JSObject.variable in my map javascript like so:
var mapOptions = {
        zoom: JSObject.zoom,
        scrollwheel: true,
        center: new google.maps.LatLng(JSObject.latitude, JSObject.longitude),
        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'],
        mapTypeControl: true,
        mapTypeControlOptions:  {
            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
            position: google.maps.ControlPosition.BOTTOM_CENTER
        }

But that returns the error: Uncaught Error: Invalid value for property <zoom>: 9
9 is the actual zoom variable so it appears to be working sort of...

A: I sugges you use wp_localize_script: http://codex.wordpress.org/Function_Reference/wp_localize_script to include arbitrary js data in your page

A: Use wp_localize_script:
wp_enqueue_script('YOUR_SCRIPT_HANDLE');
$object = array(
    'zoom' => get_option('map_zoom'),
    'longitude' => get_option('map_longitude'),
    'latitude' => get_option('map_latitude'),
);
wp_localize_script('YOUR_SCRIPT_HANDLE', 'JSObject', $object);

And then use it in your JS file like JSObject.zoom and the like.


text:
Q: AWS DynamoDB query and sort A social media app where people can leave posts. A post consists of a Author, TimeStamp, Subject and Body.
The posts are stored in DynamoDB with Author as partition key and TimeStamp as sort key.
How can I query for all posts of today? I want the results returned sorted on TimeStamp, so scanning DynamoDB is not an option.
The Query operation finds items based on primary key values. So I have to define a global secondary index. But I cannot find a suitable option to retrieve all of today's posts. What is the good choice here?

A: You can add an attribute for representing the days (your GSI primary key) and make the timestamp attribute your GSI sort key
Example:
|   AuthorId  | Timestamp(GSI SK) | DayAttribute (GSI PK) |
|:-----------:|------------------:|:---------------------:|
| authord_id  |    1534522921     |     2018-08-17        |
| authord_id2 |    1534522922     |     2018-08-17        |
| authord_id3 |    1534522923     |     2018-08-18        |

When you query GSI it will be sorted by time.
Edit on your comment:
Its not a good approach adding attributes to cover your query needs. What I can suggest in this case is to use Sort Keys hierarchically.
This means combine your most relative queries in a single GSI key and make use of hierarchical sort keys. Lets say you wanna query for only segmented in months weeks, days, hours, minutes..
This would be the table
|   AuthorId  |      Timestamp(GSI SK)      |   MonthAttr (GSI PK)  |
|:-----------:|----------------------------:|:---------------------:|
| authord_id  |    2018:08:17::10:03:25     |       2018-08         |
| authord_id  |    2018:08:17::10:03:25     |       2018-08         |
| authord_id  |    2018:08:18::10:03:25     |       2018-08         |

In this table, by using sort key conditions like begins_with, you can query all items this month, or between days 10 to 15, or specific day between 10 and 12 hours so on..
For instance, for past 13 days query the SortKey condition would be begins_with(2018:08:04:) and past hour query is like begins_with(2018:08:17:10:).
This approach introduces hot partition key problem. Take a look at the Time Series Data model to understand more about this approach and how to deal with it

A: Say if you have table as follows:

resources:
  Resources:
    BotChatHistory:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        TableName: ${self:provider.environment.DYNAMODB_BOT_CHAT_HISTORY_TABLE_NAME}
        AttributeDefinitions:
          - AttributeName: messageId
            AttributeType: S
          - AttributeName: userId
            AttributeType: S
          - AttributeName: createdDate
            AttributeType: S
        KeySchema:
          - AttributeName: messageId
            KeyType: HASH
        BillingMode: PAY_PER_REQUEST
        GlobalSecondaryIndexes:
        - IndexName: ${self:provider.environment.DYNAMODB_BOT_CHAT_HISTORY_TABLE_GSI_1}
          KeySchema:
          - AttributeName: userId
            KeyType: HASH
          - AttributeName: createdDate
            KeyType: RANGE
          Projection:
            ProjectionType: ALL

Then you can query like follows:

/**
 *
 * getChatHistory
 *
 */
const getChatHistory = async (organizationId, userId) => {
  return db('query', organizationId, {
    TableName: process.env.DYNAMODB_BOT_CHAT_HISTORY_TABLE_NAME,
    IndexName: process.env.DYNAMODB_BOT_CHAT_HISTORY_TABLE_GSI_1,
    KeyConditionExpression: "userId = :userId",
    ExpressionAttributeValues: {
        ":userId": userId
    },
    ScanIndexForward: true,
  });
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Confusion about radius of convergence of a power series I'm a bit confused about the following statement from a script. We look at the power series with coefficient $ a_k = (1+1/k)^{k^2}$ and want to compute the radius of convergence $R$ of the series. The solution given is $R=1$, applying the $k^2$ root to $a_k$. I don't get this: The Cauchy-Hadamard formula involves the $k$th root which would give $R=1/e$ in my opinion. Is this a mistake in the script or is it me who is mistaken?

A: You are indeed correct.
For coefficients $a_k:=(1+\frac {1}{k})^{k^2}$, the Cauchy-Hadamard formula gives:
$$R=\frac {1}{\limsup_{k\to\infty}(|a_k|)^{\frac {1}{k}}}=\frac {1}{\limsup_{k\to\infty}(|(1+\frac {1}{k})^{k^2}|)^{\frac {1}{k}}}=\frac {1}{\limsup_{k\to\infty}((1+\frac {1}{k})^{k^2})^{\frac {1}{k}}}=\frac {1}{\limsup_{k\to\infty}(1+\frac {1}{k})^k}=\frac {1}{e}$$

A: Just another way to do it.
$$a_k=(1+\frac {1}{k})^{k^2}\implies \log(a_k)=k^2\log \left(1+\frac{1}{k}\right)$$
$$\log(a_k)-\log(a_{k+1})=k^2\log \left(1+\frac{1}{k}\right)-(k+1)^2\log \left(1+\frac{1}{k+1}\right)$$ Now, use Taylor expansions to get
$$\log(a_k)-\log(a_{k+1})=-1+\frac{1}{3 k^2}+O\left(\frac{1}{k^3}\right)$$
Continue with Taylor
$$\frac{a_k} {a_{k+1}}=\frac{1}{e}+\frac{1}{3 e k^2}+O\left(\frac{1}{k^3}\right)$$ making $R=\frac{1}{e}$ as you found.


text:
Q: CSS media queries - why both min and max-device-height are requested for a specific device and orientation? I trying to define a media query for iPhone 6 portrait only, I found this on SO
@media only screen
    and (min-device-width : 375px)
    and (max-device-width : 667px)
    and (orientation : portrait)
    and (-webkit-min-device-pixel-ratio : 2)
{ }

Why must I define both min-device-width and max-device-width if the orientation is define, why not only a unique fixed device-width ?


text:
Q: Removing the application published under alpha release in play store I have an application published in plays store for production. I published an alpha release to the testers for testing the new update of the application. Now the testing is completed and i need to update the app. How to unpublish the app which is already in the alpha release.
I have checked the unpublish option in pricing & distribution under store presence. It will unpublish the entire app from play store. I don't want the production app to get removed, only the app release under alpha release.

A: You don't need to remove it (and you can't probably). You just need to publish your app in production mode (with higher version code than the one in alpha mode), then the alpha's version will be unavailable.

A: If  app  in Alpha means no one can downloaded it expect(access given to some mail ids) . if you don't want to view others means remove all mail ids.


text:
Q: ORA-00913: too many values with a nested case I am currently working on my first year assignment to build a database using Oracle Apex and am trying to create a report with fields to filter the table displayed. To do this using 2 parameters (in this case date of a dentist appointment and the staff member performing said appointment)I am using a nested case to check each field. I am getting the Error:
ORA-06550: line 6, column 23: ORA-00913: too many values.
Me, my fellow students and my tutors are failing to see how to fix it. Hoping someone here can see my mistake.
Here is my code:
SELECT
CASE :P5_APPOINTMENT_DATE
    WHEN (NULL)
        THEN CASE :P5_STAFF
            WHEN (NULL)
                THEN (select
                      APPOINTMENT_ID AS "Appointment ID",
                      Patient.Surname AS "Patient Surname",
                      Patient.Forename AS "Patient Forename",
                      Staff.Surname AS "Staff Surname",
                      A_DATE AS "Date"
                      FROM Appointment
                      Inner Join Patient ON Patient.Patient_ID = Appointment.Patient_ID
                      Inner Join Staff ON Staff.Staff_ID = Appointment.Staff_ID)

                ELSE (select
                      APPOINTMENT_ID AS "Appointment ID",
                      Patient.Surname AS "Patient Surname",
                      Patient.Forename AS "Patient Forename",
                      Staff.Surname AS "Staff Surname",
                      A_DATE AS "Date"
                      FROM Appointment
                      Inner Join Patient ON Patient.Patient_ID = Appointment.Patient_ID
                      Inner Join Staff ON Staff.Staff_ID = Appointment.Staff_ID
                      Where STAFF.STAFF_ID = :P5_STAFF)
                END

        ELSE CASE :P5_STAFF
            WHEN (NULL)
                THEN (select
                      APPOINTMENT_ID AS "Appointment ID",
                      Patient.Surname AS "Patient Surname",
                      Patient.Forename AS "Patient Forename",
                      Staff.Surname AS "Staff Surname",
                      A_DATE AS "Date"
                      FROM Appointment
                      Inner Join Patient ON Patient.Patient_ID = Appointment.Patient_ID
                      Inner Join Staff ON Staff.Staff_ID = Appointment.Staff_ID
                      Where A_DATE = :P5_APPOINTMENT_DATE)
                ELSE (select
                      APPOINTMENT_ID AS "Appointment ID",
                      Patient.Surname AS "Patient Surname",
                      Patient.Forename AS "Patient Forename",
                      Staff.Surname AS "Staff Surname",
                      A_DATE AS "Date"
                      FROM Appointment
                      Inner Join Patient ON Patient.Patient_ID = Appointment.Patient_ID
                      Inner Join Staff ON Staff.Staff_ID = Appointment.Staff_ID
                      Where A_DATE = :P5_APPOINTMENT_DATE AND STAFF.Surname = :P5_STAFF)
                END

        END
        FROM APPOINTMENT

A: As Gordon Linoff said in a comment, a case returns a single value. Since the bulk of the subqueries are the same and you're only varying the filter conditions, you can move the case to the where clause; except here you don't even really need a case, you can get the same effect with or, something like:
SELECT APPOINTMENT_ID AS "Appointment ID",
  Patient.Surname AS "Patient Surname",
  Patient.Forename AS "Patient Forename",
  Staff.Surname AS "Staff Surname",
  A_Date AS "Date"
FROM Appointment
JOIN Patient ON Patient.Patient_ID = Appointment.Patient_ID
JOIN Staff ON Staff.Staff_ID = Appointment.Staff_ID
WHERE (:P5_APPOINTMENT_DATE IS NULL OR A_Date = :P5_APPOINTMENT_DATE)
AND (:P5_STAFF IS NULL OR STAFF.Surname = :P5_STAFF);

If both bind variables are null you'll get all records; if either or both are not null then you'll get the subset of matching values. Which seems to be what you want - four possible outcomes depending on which of the two variables are set.


text:
Q: PHP: generating html code with a for loop that won´t show up in page source? I want to generate some HTML code (a form with several text inputs, actually) with a for loop.
I´ve tried two ways (with and without an array).
After the expected output appears into the screen, I try to view it using the browser´s "page source" utility, but even when the html code shows up into the screen it won´t show up into the page source.
WHY?
After filling the form inputs created with the for loop, I then try to get the information using $_POST, but nothing actually prints out... Maybe because of the same reason it won´t appear at the page source?
ie. typing this produces nothing: echo $_POST['fmes1'];
This is my first try:
  $numOrder=1;
  $mes=1;
  $anio=1;

for ($i=0; $i<$cantMeses; $i++) {
    $celdas = array(
        $i => 'Mes <input name="fmes'.$mes.' class="ancho-celda2">
                   Año <input name="fanio'.$anio.' class="ancho-celda">',
                    );
        foreach ($celdas as $elemento) {
            echo $numOrder.' '.$elemento.'
';
        }
$numOrder=$numOrder+1;
$mes=$mes+1;
$anio=$anio+1;
}

And this is my second try, not using an array:
for ($i=0; $i<$cantMeses; $i++) {
    echo "
".$numOrder. "º
    Mes <input name='fmes".$mes." class='ancho-celda2'>
    Año <input name='fanio".$anio." class='ancho-celda'>
    ";
}
    $numOrder=$numOrder+1;
    $mes=$mes+1;
    $anio=$anio+1;

This is the form on calculadora.php:
<form onsubmit='return validar()' name="generar-tabla" action="calcular.php" method="POST">
    Calcular intereses hasta:
        Mes <?php echo ''.$tMonth.'';?>
        Año <?php echo ''.$tYear.'';?>

Con tasa de Interés del <input value='<?php echo $interes;?>' type='text' name='interes' class="ancho-celda">% mensual

Cuántos meses se adeudan? <input type='text' name='cantMeses' class="ancho-celda" value="<?php echo $cantMeses;?>">

<input type='submit' name='submit' value='Generar tabla para cálculo'>
</form>

And it goes to calcular.php:
(it is still very much empty, because I´m trying to get the information form the other form. I´cve tried using the same file too)
session_start();
include ('calculadora.php');

echo $_POST['fmes1'];

A: In the first code snippet, I can't see where are you closing the for loop. Besides, you are resetting the $celdas contents in each loop, when you should instead append to the array.
$numOrder=1;
$mes=1;
$anio=1;
$celdas = array();
for ($i=0; $i<$cantMeses; $i++) {
    $celdas[$i] = 'Mes <input name="fmes'.$mes.' class="ancho-celda2"> Año <input name="fanio'.$anio.' class="ancho-celda">';
}
foreach ($celdas as $elemento) {
    echo $numOrder.' '.$elemento.'
';
}

Anyway, I don't see why you need to perform a loop at all. The even if $cantMeses was set somewhere else, the contents of each $celda array element doesn't seem to depend on the month index. Perhaps the $mes variable should instead be the one to iterate? Something like
$numOrder=1;
$anio=1;
$celdas = array();
for ($mes=1; $mes<=$cantMeses; $mes++) {
    $celdas[$mes] = 'Mes <input name="fmes'.$mes.' class="ancho-celda2"> Año <input name="fanio'.$anio.' class="ancho-celda">';
}
foreach ($celdas as $mes=>$elemento) {
    echo $mes.': '.$numOrder.' '.$elemento.'
';
}

This is just a wild guess.


text:
Q: Internet Exporer 11 rendering table improperly on my page I have a table with a few elements in it, but it messes up in Internet Explorer 11. Any help appreciated
Here is what it looks like in VS:

In Chrome:

And here IE:

My Code:

                <asp:Label ID="lbl_dm_rvi" runat="server" Text="sometext RVI"></asp:Label>

                <asp:Label ID="lbl_dm_odv" runat="server" Text="sometext ODV"></asp:Label>

                <asp:Label ID="lbl_hochrechnung" runat="server" Text="Hochrechnung_RX_SM_KVBEZ"></asp:Label>

                <asp:Label ID="lbl_modul1" runat="server" Text="Modul 1"></asp:Label>

                <asp:Label ID="lbl_modul_30" runat="server" Text="Modul 3.0"></asp:Label>

                <asp:Label ID="lbl_modul_31" runat="server" Text="Modul 3.1"></asp:Label>

                <asp:Label ID="lbl_modul3" runat="server" Text="Modul 3"></asp:Label>

                <asp:Label ID="lbl_modul2" runat="server" Text="Modul 2"></asp:Label>

                <asp:Label ID="lbl_odv" runat="server" Text="ODV"></asp:Label>

                <asp:Label ID="lbl_modul2a" runat="server" Text="Modul 2a"></asp:Label>

                <asp:Label ID="lbl_modul4" runat="server" Text="Modul 4"></asp:Label>

                <asp:Label ID="lbl_modul4a" runat="server" Text="Modul 4a"></asp:Label>

A: What I see at the first is that the table on IE is take the full width, the other two are not.
This is usually done because its browser did not have the same default setting for all elements.
A quick solution is to set the width on the table as

so you not left it random.
You can also try to use any "Reset CSS" (like Eric Meyer's) thats try to bring all browser styles to the same point.
Related: What is the easiest or fastest way to make CSS render the same in all browsers


text:
Q: Why CSS hover use a lot of CPU when I have a lot of DOM nodes I have an application that creates a lot of DOM Nodes (it starts with 2k DOM Nodes) when using it like Elementor, when I use it for a long time (when I reach 50k DOM Nodes) I see that the hover styles are laggy and the CPU usage goes up (on Chrome Performance Monitor) when I hover on elements that have hover styles.
The hover rule is:
.element {
  background-color: white;
  transition: all .3s;
}
.element:hover {
  background-color: #ddd;
}

How can I improve the performance?
Thanks
Edit:
I disabled the hover rule (background-color: #DDD and transition: all .3s) but I still see the CPU usage goes up...
Edit 2:
The CPU usage goes up not just on this element, any other element I hover is slow and laggy ...

A: The problem is from a library that I was using not the DOM Nodes, it wasn't resetting the event listeners, and they kept stacking ...
I had to re-init them manually.
Thanks for the help ✌


text:
Q: Visual studio cordova sign app I'm tring to make an app using visual studio 2015 and Cordova.
When I build the release everything works, but the distribution doesn't, and appear:

The Android packages must be signed when you are debugging with configuration type version . To configure the signing Android , follow the instructions in http://go.microsoft.com/fwlink/?LinkID=613579

I cannot understand where is the error,
Thanks
UPDATE
now my build.json is:
{
    "android": {
        "release": {
            "keystore": "example.keystore",
            "storePassword": "example",
            "alias": "example",
            "password" : "example",
            "keystoreType": ""
         }
    }
 }

but when I try to build the release I have this
A problem occurred evaluating root project 'android'.
Keystore file does not exist: C:\Users\Simone\Desktop\example\example\platforms\android\..\..\example.keystore

the keystore is in the folder  platform\android but i don't understand why there are \...\...\   I never add this

A: Looks like you need to sign your application. Here are a couple links to help get you started:

*

*Android's documentation on signing your app. This probably should be your first stop, as it explains both the debug and release build signing process: https://developer.android.com/tools/publishing/app-signing.html

*A Tutorial on signing your app for release distribution: https://blog.nraboy.com/2014/09/signing-apache-cordova-android-app-release/


text:
Q: sprintf - repeating arguments I want to format a string with sprintf but repeating many times an argument. see..
$str = "Str 1: %s - Str 2: %s - Str 2 again: %s";

Considering that string to format, I want to repeat the second arg two times.
echo sprintf($str, "I'm string 1", "My name is string 2");

And the wanted result like:
Str 1: I'm string 1 - Str 2: My name is string 2 - Str 2 again: My name is string 2

There's a way to do that??

A: It's all in the documentation!
$str = 'Str 1: %1$s - Str 2: %2$s - Str 2 again: %2$s';
echo sprintf($str, "I'm string 1", "My name is string 2");

Note: Use single quotes for the format string otherwise you'll get PHP Notice:  Undefined variable: s in /path/to/tofile:line
You can also escape the $ with a \ if you are using double quotes.


text:
Q: UpdateIf removing focus of item in PowerApps Gallery I am currently troubleshooting a PowerApp made by a different company where tabbing between fields is not working as expected.
I discovered within a gallery containing text boxes that the "OnChange" properties of these items of a "UpdateIf" function inside them, which appears to be causing the form to lose focus on the item selected.
I was trying to do something like a SetFocus on the item, but that apparently is not supported within the gallery.
I am open to any suggestions including maybe a different best practice to achieve the same sort of result, if there is anything I can do to clarify please ask.

A: You can make colour change as selected items to show focus.
Thisitem.selected may work
To display focus


text:
Q: Where to find selected filepath of SaveFileDialog (C#, Visual Studio) I'm trying to export my dataTable as an Excel file. I can do this from (https://stackoverflow.com/a/13973274), but I'd like the user to be able to input the location the file is saved to. It seems like the SaveFileDialog class would work well.
My issue stems from the fact that I can't figure out where to find the filepath that has been specified by the user after hitting "save". I need that filepath to input into the ExportToExcel(ExcelFilePath) when I actually do the export of my dataTable.
SaveFileDialog Class
Sorry if I'm unclear, this is my first time asking a question here.

A: As you've noted, the SaveFileDialog class is documented here.
If we look at the top of that page, it shows the inheritance hierarchy:
Inheritance → Object → MarshalByRefObject → Component → CommonDialog → FileDialog → SaveFileDialog
Now if we follow the link to the FileDialog class and go to Properties, we see:
FileDialog.FileName Property
Property Value
String
The file name selected in the file dialog box. The default value is an empty string ("").
Remarks
The file name includes both the file path and the extension. If no files are selected, this method returns an empty string ("").


text:
Q: Specificity and Direct Targeting I'm running loops between my understanding of specificity and targeting an element. I understand the base concept of specificity and read numerous articles on how to calculate specificity using a,b,c,d, where d is the lowest specificity and a is the highest.
I'm losing scope of where specificity comes into practice. In the snippet below, even though some specificity rules are "higher" than others, lower specificities are applied, e.g.

/* 0001 */

span {
  color: red;
}

/* 0001 */

p {
  color: blue;
}

/* 0010 */

.main {
  color: orange;
}

/* 0100 */

#h4-id {
  color: limegreen;
}

/* 0002 */

div h4 {
  color: purple;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

this should be orange

ID Selector

    text inside paragraph
    hello world

There is a div with the ID h4-id. The rule sets all text to limegreen.
There is another selector with lower specificity div h4, this rule "wins" and the declarations in that rule is applied.
I believe the reason is that it is a "direct" target.
Here is another example:

  /* 0002 */

p span {
  /*     font-size: 200px; */
  text-decoration: underline dotted red;
  font-style: normal;
  color: teal;
  background-color: yellow;
}

/* 0001 */

span {
 background-color: teal;

}

/* 0010 */

.main {
  font-family: monospace;
  color: blue;
  font-size: 22px;
  background-color: lightgrey;
}

/*  0001 */

p {
  font-family: cursive;
  color: indigo;
  font-size: 100px;
  background-color: limegreen;
  font-style: italic;
  text-decoration: underline;

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut Tristique magna sit amet purus gravida quis blandit turpis. Tellus elementum sagittis vitae et. Faucibus pulvinar elementum integer enim neque  volutpat ac tincidunt vitae. At tempor commodo ullamcorper a.

https://stackoverflow.com/questions/ask#

In this example, once again, the lower specificity wins, but these are "direct targets" (I believe), which is why they win. The class "main" does not have higher priority over the descendant selector p span.

*

*the .main class score is 10, all the text inside it should have the ruleset applied unless there is an ID

*the p span selector is 2, the reason this wins is that it is directly targeted (even though the specificity score is lower? this is where my confusion is).

Here is one of the many types of articles and references I've been reading to solidify my knowledge of specificity
Is it correct to say, before applying specificity rules and calculating specificity, if the element is directly targeted, specificity rules do not apply and the direct target always takes precedence(like the examples I posted)? If this is the case, just for my own mental model, I'd prefer using the CSS diagram to calculate specificity as so:
false, 0, 0, 0, 0 (false means it is not a direct target, this could always be a 1 or 0 as well). Is this valid reasoning?

A:
I'm losing scope of where specificity comes into practice

Specificity matters when two or more competing selectors are applying styles to the same element(s) - the rule with the higher specificity wins.
Specificity does not matter when evaluating styles that are being applied to different elements, even if that style is inherited from an ancestor.

Is it correct to say, before applying specificity rules and calculating specificity, if the element is directly targeted, specificity rules do not apply and the direct target always takes precedence

No, I would say that is incorrect. I wouldn't get wrapped up in the phrase "directly targeted"... in a sense all CSS selectors are directly targeting a set of elements, yet some properties of that rule-set can cascade to descendants, like color. Inherited styles do not also inherit the specificity from the rule-set they originated from; otherwise, to change the color of a child element you'd have to match or beat the specificity every time.
For example, the text in the following snippet is red because #main (the selector) has a higher specificity than div (the selector) and the styles are applied to the same element:

#main {
  color: red;
}

div {
  color: blue;
}

text

However, in the next example, p wins the day because the selectors are affecting different elements:

#main {
  color: red;
}

p {
  color: blue;
}

text

Now, take that last example and add a new, more specific selector that applies color to p:

#main {
  color: red;
}

p {
  color: blue;
}

#main p {
  color: green;
}

text

The text is now green because the selector #main p (0,1,0,1) is higher than the selector p (0,0,0,1) and both selectors affect the same element.

A: First, note that color is an inherited property:

When no value for an inherited property has been specified on an element, the element gets the computed value of that property on its parent element.

So, if no color property is directly applied to an element, it will inherit its value from its parent.
Now take a look at this example:

/*Rule A*/
#divId {
  color: orange;
}

/*Rule B*/
.divClass {
  color: green;
}

/*Rule C*/
div {
  color: blue;
}

  div 1 (id="divId" class="divClass")

    div 2 (class="divClass")

      div 3
       and a span

We have 3 divs and a span. Let's break down how each one gets its color:

*

*Div 1 is targeted by rules A, B, and C. Rule A has the highest specificity, because it uses an id selector.

*Div 2 is targeted by Rules B and C. Rule B has higher specificity, because it uses a class selector.

*Div 3 is targeted only by rule C.

*The span is not targeted by any css rule. So it will inherit its color from its parent, div 3.


text:
Q: CSS - Wrap text along angle I'm trying to get text to wrap along an angle. This illustrates what I'm trying to do better than I can describe it:
http://bdub.ca/angle.png http://bdub.ca/angle.png
I found a solution here but it uses a heck of a lot of empty floated divs to create the effect. I will need to do this a bunch of times on a page so it would be better to have a solution that is lighter in weight. JavaScript is okay if it's something that I can just run on page load to spare the DOM from an overload of extra elements.
My brainstorming for a JS solution got as far as trying to figure out how to wrap each line in a span and set the left margins of the spans successively larger. The caveat is that the text is a paragraph that will auto wrap to fit in the container - I unfortunately can't ask my client to insert line breaks from Wordpress - so to wrap each line in a span would involve somehow detecting the automatic line breaks using javascript.
Any suggestions?

A: It's very tricky in that you can't legitimately (w3c standards; monitor screen resolution size and privacy) detect the actual width of characters.  You could set the font-size to a specific width and insert a line-break yourself when it comes close to the width.  (in b4 monitor)
so css: .paraIncrement { font-size: 12pt; }
I'm a little rusty with javascript so let's psudo-code this one:
outputstr[] = array();
int index = 0;
int startmax = 80;
int innerCount = 0;
for (int i = 0; paragraph.length; i++) {
   outputstr[index] += paragraph[i];
   innercount++;
   if (innercount == startmax) {
      startmax -= 5; // how much you want the indent to shrink progressively.
      innercount = 0;
      index++;
   }
}
for (int i = 0; i < output.length(); i++) {
   echo ''+output[i]+'';
}

This section expects the maximum length of the start to be 80 characters long, decrementing by 5 each time.  Also if you want to be sure it doesn't break early, ensure the the css.overflow is set to hidden/visible.

A: Having an blank image (jagged like steps) you want inline on the left of the paragraph should do it.


text:
Q: How to Pass in Parameters of CTE in view or stored procedure I have multiple CTEs and I want to pass in two parameters: one being the date and the other being the CTE table name.
This is for an Oracle database.
The CTEs are like this
WITH big_table1 AS
(
    SELECT * FROM mini_table1
),
big_table2 AS
(
    SELECT * FROM mini_table2
)

The date will be calculated by the select statements in the CTE. I want to do something like select * from &&big_table where &&date = date or any other way (in a view/stored procedure) that would help me pass in dynamically the CTE name and a specific date (like '10-23-2021').
I have tried this and it works: select * from &&big_table where &&date = date. But it needs to be in a stored procedure or view or something that is established I guess. Not really sure why but those are the requirements I need to satisfy.
Appreciate any help.

A: If you know what table names could be involved and if the query from any of the tables return the same number of columns of the same datatype then you could try something like this:
WITH
    MINTBL_1 (ID, A_DATE, COL_1, COL_2) AS
        (
            Select 1, To_Date('01.03.2023', 'dd.mm.yyyy'), '1.something in COL_1', 'something else for COL_2' From Dual Union All
            Select 2, To_Date('01.03.2023', 'dd.mm.yyyy'), '2.something in COL_1', 'something else for COL_2' From Dual Union All
            Select 3, To_Date('02.03.2023', 'dd.mm.yyyy'), '3.something in COL_1', 'something else for COL_2' From Dual Union All
            Select 4, To_Date('03.03.2023', 'dd.mm.yyyy'), '4.something in COL_1', 'something else for COL_2' From Dual
        ),
    MINTBL_2 (ID, A_DATE, COL_1, COL_2) AS
        (
            Select 1, To_Date('26.02.2023', 'dd.mm.yyyy'), '1.something in COL_1', 'something else for COL_2' From Dual Union All
            Select 2, To_Date('26.02.2023', 'dd.mm.yyyy'), '2.something in COL_1', 'something else for COL_2' From Dual Union All
            Select 8, To_Date('27.02.2023', 'dd.mm.yyyy'), '8.something in COL_1', 'something else for COL_2' From Dual Union All
            Select 9, To_Date('28.02.2023', 'dd.mm.yyyy'), '9.something in COL_1', 'something else for COL_2' From Dual
        )
SELECT  ID "ID", A_DATE "A_DATE", COL_1 "COL_1"
FROM    (     SELECT  CASE WHEN :input_tbl = 'MINTBL_1' THEN 'MINTBL_1' END "SOURCE", ID "ID", A_DATE "A_DATE", COL_1 "COL_1"
              FROM    MINTBL_1
          UNION ALL
              SELECT  CASE WHEN :input_tbl = 'MINTBL_2' THEN 'MINTBL_2' END "SOURCE", ID "ID", A_DATE "A_DATE", COL_1 "COL_1"
              FROM    MINTBL_2
        )
WHERE SOURCE Is Not Null And A_DATE = :input_dt

if we bound values MINTBL_1 and 01-MAR-23 to bind variables :input_tbl and :input_dt the result should be:
ID  A_DATE      COL_1
--- ----------- --------------------
1   01-MAR-23   1.something in COL_1
2   01-MAR-23   2.something in COL_1

... and for MINTBL_2 as table and 28-FEB-23 as date it will be:
ID  A_DATE      COL_1
--- ----------- --------------------
9   28-FEB-23   9.something in COL_1

Another way to do it could be to use function that returns REF CURSOR ...


text:
Q: Аналог `element.style.left = variable + 'px'`, только без 'px' Имеется элемент:
let element = document.getElementById('id')

Я могу изменить его css-свойство left вот так:
let left = ...
highlight.style.left = left + 'px';

Есть ли аналог этого, только без необходимости писать 'px'?

Например, с помощью jquery можно так:
$(element).css('left', left);

А можно без jquery (и без 'px')?

A: Да. Нет. Нет.
Хотя ну ладно, на последний вопрос - да:

var $ = (function () {
  var allowNumber = ['lineHeight', 'zIndex'];

  function $(el) {
    if (this instanceof $) {
      this.el = el;
    } else {
      return new $(el);
    }
  }

  $.prototype.css = function css(key, value) {
    key = key.replace(/-(\w)/g, function (m, ch) { return ch.toUpperCase() });

    if (+value == value && allowNumber.indexOf(key) === -1) {
      value += 'px';
    }

    this.el.style[key] = value;

    return this;
  }

  return $;
})();

$(document.querySelector("div")).css('left', 100).css('line-height', 3);
div {
  position: absolute;
  left: 0;
  top: 0;
  background: silver;
}

123

PS: Пиксели - зло.


text:
Q: Why can't Bouncycastle's PEMReader read this M2Crypto-generated PEM? I use the following Python code, using M2Crypto, to generate an RSA key pair in PEM format:
bio = BIO.MemoryBuffer()
key_pair = RSA.gen_key(1024, 65537)
key_pair.save_key_bio(bio, cipher=None)
return bio.read()

And the following Java code, using Bouncycastle, to try to read it:
String signPem = ...;
PEMReader pemReader = new PEMReader(new StringReader(signPem));
Object signingKey = pemReader.readObject();

The signPem string is the same as what bio.read() returned; no data that I can see is getting munged between the two programs; it's -----BEGIN RSA PRIVATE KEY-----\n etc.
However, the readObject() call throws a ClassCastException:
java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence
    at org.bouncycastle.asn1.ASN1Object.fromByteArray(Unknown Source)
    at org.bouncycastle.openssl.PEMReader.readKeyPair(Unknown Source)
    at org.bouncycastle.openssl.PEMReader.readObject(Unknown Source)

So obviously BC misidentifies the data in the PEM is not a key pair for some reason - but why?

A: After taking a debugger to Bouncycastle, I have discovered the "cause", but it only puzzles me more; the cast is failing even though all types seem to be correct.
If A extends B extends C, why can I cast to A but get a ClassCastException casting to C?


text:
Q: List Validation Settings: Ignore case when finding word I am validating a column to see if it contains blacklisted words. I want to capture the words whether they are upper case or lower case but I cannot seemed to find any solution on the internet. Does anyone know the proper syntax to ignore case? Or if I can compare the words by converting it to lower case first?
I have the following as my validation formula:
=AND(IF(ISERROR(FIND("blacklistword",Title)),TRUE),IF(ISERROR(FIND("blacklistwordtwo",Title)),TRUE),IF(ISERROR(FIND("blacklistwordthree",Title)),TRUE),IF(ISERROR(FIND("blacklistwordfour",Title)),TRUE))

Your help is much appreciated.
Thank you in advance!

A: I have found the answer.

=AND(IF(ISERROR(FIND("kns",LOWER([Title]))),TRUE),
  IF(ISERROR(FIND("lj",LOWER([Title]))),TRUE),
  IF(ISERROR(FIND("wah lau",LOWER([Title]))),TRUE),
  IF(ISERROR(FIND("lao jiao",LOWER([Title]))),TRUE))

This website shows all the synthax: http://msdn.microsoft.com/en-us/library/office/bb862071(v=office.14).aspx.


text:
Q: match values in dataframes with values in a column I have two data.frames that looks like these ones:
>df1
 V1
  a
  b
  c
  d
  e

>df2
 V1     V2
  1  a,k,l
  2  c,m,n
  3  z,b,s
  4  l,m,e
  5  t,r,d

I would like to match the values in df1$V1 with those from df2$V2and add a new column to df1 that corresponds to the matching and to the value of df2$V1, the desire output would be:
>df1
 V1  V2
  a   1
  b   3
  c   2
  d   5
  e   4

I've tried this approach but only works if df2$V2 contains just one element:
match(as.character(df1[,1]), strsplit(as.character(df2[,2], ",")) -> idx
df1$V2 <- df2[idx,1]

Many thanks

A: You can just use grep, which will return the position of the string found:
sapply(df1$V1, grep, x = df2$V2)
# a b c d e
# 1 3 2 5 4

If you expect repeats, you can use paste.
Let's modify your data so that there is a repeat:
df2$V2[3] <- "z,b,s,a"

And modify the solution accordingly:
sapply(df1$V1, function(z) paste(grep(z, x = df2$V2), collapse = ";"))
#     a     b     c     d     e
# "1;3"   "3"   "2"   "5"   "4"

A: Here's an approach:
library(qdap)
key <- setNames(strsplit(as.character(df2$V2), ","), df2$V1)
df1$V2 <- as.numeric(df1$V1 %l% key)

df1

##   V1 V2
## 1  a  1
## 2  b  3
## 3  c  2
## 4  d  5
## 5  e  4

First we used strsplit to create a named list.  Then we used qdap's lookup operator %l% to match values and create a new column (I converted to numeric though this may not be necessary).

A: Similar to Tyler's answer, but in base using stack:
df.stack <- stack(setNames(strsplit(as.character(df2$V2), ","), df2$V1))
transform(df1, V2=df.stack$ind[match(V1, df.stack$values)])

produces:
  V1 V2
1  a  1
2  b  3
3  c  2
4  d  5
5  e  4

One advantage of splitting over grep is that with grep you run the risk of searching for a and matching things like alabama, etc. (though you can be careful with the patterns to mitigate this (i.e. include word boundaries, etc.).
Note this will only find the first matching value.


text:
Q: AngularJS Material checkboxes in nested loop I am using AnjularJS with Angular Material. I'm trying to display a group of checkboxes, and each group is displayed for each location I have. My problem is if a check a checkbox for the first location, the same checkbox for the other locations are checked. I'm unsure of how to have these nested checkboxes.
Here is my controller code
$scope.subBrandList = [
  {sub_brand_id:"1", sub_brand_desc:"Brand 1"},
  {sub_brand_id:"2", sub_brand_desc:"Brand 2"}
];
$scope.servicesProvidedList = [
  {service_provided_id:"1", service_provided_desc:"Desc 1", sub_brand_id:"1"},
  {service_provided_id:"2", service_provided_desc:"Desc 2", sub_brand_id:"1"}
];
$scope.dealerLocationList = [
  {id:"1", dealer_location_name:"LOC 1"},
  {id:"2", dealer_location_name:"LOC 2"}
]
$scope.servicesSelected = [];
$scope.serviceSelection = {
  ids: {},
  objects: []
};

$scope.toggle = function (item, list) {
  var idx = list.indexOf(item);
  if (idx > -1) list.splice(idx, 1);
  else list.push(item);
};
$scope.exists = function (item, list) {
  return list.indexOf(item) > -1;
};

Here is my HTML:

{{location.dealer_location_name}}

      <md-list>
        <md-list-item ng-repeat="brand in subBrandList" style="padding-bottom:20px;">

                <md-checkbox class="md-primary" ng-checked="exists(item, servicesSelected)" ng-click="toggle(item, servicesSelected)" ng-model="serviceSelectionids.ids[item.service_provided_id]">
                {{ item.service_provided_desc }}
                </md-checkbox>

          <md-divider md-inset ng-if="!$last"></md-divider>
        </md-list-item>
      </md-list>


text:
Q: Detecting mp4 files on page and automatically wrapping them in jwplayer? I am trying to add jw player to a custom cms where a user can add an mp4 file and it appears in the page as a link. But what I would like to do is detect each mp4 file on the page and have jw player wrap each mp4 file on the page and allow it to be played. Is this possible? If so is there an example of this somewhere.

A: Assuming the rendered result is some kind of list containing anchor tags like:
File1
File2
...

You can parse every single anchor tag and regex it's href attribute content, i.e.:
$("a").each(function() {
  var href = $(this).attr('href');

  if(href.search(/*\.mp4/) != -1) {
    // this is an anchor tag where the href attribute points to an mp4 file
    // so you can replace it with some other html code

    // for instance, hide the anchor tag
    $(this).hide();

    // add some other html code after the hidden anchor tag, eg. jw player
    $(this).after('
 <-- player code goes here -->
');
  }
});

It's even easier if you can modify the template that's being renderd the way the server side determines which links should be replaced. For instance if you can produce something like:
File1
...

You could just do
$(".mp4-file").each(function() {
  // no need to regex here

  $(this).hide();
  $(this).after('
 <-- player code goes here -->
');
});

I think you get the idea...


text:
Q: How do I retrieve the unevaluated value of an attribute from a directive in Angular? I have a directive which is using $observe to watch when the value of one of the attributes changes. When this fires, I need to be able to retrieve the unevaluated value of the attribute not the evaluated value.
So my HTML would look like this:

Then the link function in my directive:
attrib.$observe('myAttrib', function(val) {
    // Both val and attrib.myAttrib contain "ABC"
    // I would like the uncompiled value instead
    var evaluatedValue = attrib.myAttrib;
});

If the controller had done this:
$scope.myAttrib = "ABC";
When $observe first, evalutedValue returns "ABC". I actually need it to return "{{scopeVar}}".
EDIT: Per the comment below from François Wahl I ended up moving this into a ng-repeat element which is bound to an array of one item. Then I just remove/add the new item in the controller which updates $scope. This eliminates the need to retrieve the uncompiled attribute value and actually cleans things up quite a bit. It's definitely odd when looking at the view since it's not immediately clear as to why it's in a repeater, but it's worth it since it cleans up the code quite a bit.

A: You have to grab it in the compile: function of the directive link this:
.directive('myAttrib', function() {
  return {
    compile: function(tElement, tAttrs) {
      var unevaluatedValue = tAttrs.myAttrib;

      return function postLink(scope, element, attrs) {
        attrs.$observe('myAttrib', function(val) {
          // Both val and attrib.myAttrib contain "ABC"
          // I would like the uncompiled value instead
          var evaluatedValue = attrs.myAttrib;

          console.log(unevaluatedValue);
          console.log(evaluatedValue);
        });
      }
    }
  }
})

Example Plunker: http://plnkr.co/edit/bHDmxJvnENqz8Mpg1qpd?p=preview
Hope this helps.


text:
Q: Threading leading to crash (python) I am making a game and I need to run the function popup() and Maze() at the same time. I tried to do this with threading however it leads to a crash. I have tried many fixes but not found a solution.
def popup():
  threading.Timer(10.0, popup).start()
  Qscreen = Toplevel(screen)
  Qscreen.geometry("1920x1080")
  Qscreen.title("QUESTION")
  Label(Qscreen, text = MediumQ[random.randint(0,1)]).pack()

def Maze():
  app = MyApp()
  app.run()

def play():
    a = threading.Thread(target = popup)
    a.start()
    b = threading.Thread(target = Maze)
    b.start()

running this code always leads to a crash. Any fixes?


text:
Q: Stripey videos on all media players Ubuntu 20.04 Hi I did a clean install of Ubuntu for the first time yesterday.
When I tried to watch a video with vlc the quality is very "stripey".
I found this question VLC - much worse video quality than other players (horizontal stripes)
The problems are similar.
But that solution didn't work for me.
I also tried the mpv media player with the same results.
Youtube plays in good quality.
EDIT: added a screenschot with the artefact clearly visible
here

A: My guess is that what you are seeing is called tearing.
This happens in video games that render at a high framerate and don't turn on v-sync.
It is better to turn on v-sync, however, the game rendering will be limited to your monitors refresh rate (which is not necessarily a bad thing).
Another thing is that maybe your Ubuntu is using the Compositor in order to do various animation effects with OpenGL. If v-sync is not enabled, then you will have tearing since the Compositor, just like a game, would be rendering at a high frame rate like 200 FPS while your monitor might be only 60 Hz.
In my case, I use Kubuntu 20.10. (This uses the KDE interface. I don't know about the GNOME interface of Ubuntu)
Press on
-Start → Applications → Settings → System Settings
-The System Settings window opens
-On the left side, click on Display and Monitor
-In the next list, click on Compositor (It is the second one in the list)
-On the right side, Tearing prevention ("vsync") , set it to Automatic.
-At the bottom right, click the Apply button


text: Q: Spring mvc ,debug application when i code a sample of Spring mvc and ant build it ,i input the site at the web broswer.But it just say could not find the page.How can i debug the application?i just want to know the log and what exception is.thanks.


text:
Q: Strange LD behavior when section name is equal to output name I have section in LDS script file
MEMORY
{
        boot (r)        : ORIGIN = 0x00000000, LENGTH = 0x10000
        flash  (rx)     : ORIGIN = 0x00010000, LENGTH = 1080K
        tcm   (rw!x)    : ORIGIN = 0x003F0000, LENGTH = 60k
        itcm   (rwx)    : ORIGIN = 0x003FF000, LENGTH = 4k
        ram   (rw!x)    : ORIGIN = 0x00400100, LENGTH = 192k - 0x100
}
SECTIONS
{
    .tcm ALIGN(8) :
    {
      /* some other files */
        *ate_app*.o(.bss .bss.* .scommon .sbss .dynbss COMMON)
      /* some other files */
    }>tcm AT>flash

/* other sections */
}

When my output file is ate_app.elf then linking fails with .tcm section overlap error.
When I change output name to qwerty.elf or change the ate_app.o directive to something else linking goes successfuly.
Why is this strange behavior?


text:
Q: How to decode time stored as integer in SQL Server database I got some dump of SQL Server database to extract some data out of it. In particular I have to extract start and end datetime of appointments. I managed to identify date column which stores values like 41640, 41641 and so on.
Casting those values into date time (cast (41640) as datetime)) gives nice date with no time (2014-01-03 00:00:00).
Next there are two columns which I suspect (based on their names: from, to) represent start and end time. The problem is that values in those two columns are either NULLs or integers in the range from 29 to 82. Looking for any hints how to convert those values into time of the day (these should be pretty much even times).
Here are some sample values:
date, from, to
41640   29  68
41640   29  68
41640   29  68
41640   29  68
41640   29  68
41641   29  68
41641   29  68
41641   29  31
41641   29  30
41641   41  41

A: Values 'from' and 'to' represent number of quarters passed since midnight. So for Example 28*15min = 420mins. 420min/60min = 7h (am). 68*15min = 1020min / 60min = 17h.
These are actually for even hours, but knowing this it's pretty easy to calculate minutes too.


text:
Q: What is the maximum statement length in Oracle I'm building a SQL statement that contains data and I'm wondering if I would break some maximum statement length in Oracle 10g.
The statement would be about 3 200 000 bytes, cannot be split and has to be parsable in its entirety.
Before I'm investing too much time this way, I was wondering if I would be limited by the size of this statement.
I am using SQL developer but I think that if the server can do it, so can SQL developer.

A: There is no fixed number. See "Logical Database Limits":  http://docs.oracle.com/cd/B19306_01/server.102/b14237/limits003.htm
"The limit on how long a SQL statement can be depends on many factors, including database configuration, disk space, and memory".
You might also be affected by other limits, such as the maximum levels of subqueries.
Given that the maximum length of PL/SQL procedures is given as 2000-3000 lines, my feeling is that you may run into problems with a 3M bytes query. I also think that if it works at all, the parse time will be "interesting".

A: According 11.2 Limits documentation:

Maximum length of SQL statement, including the NULL terminator.   409,600

https://docs.oracle.com/cd/E11882_01/timesten.112/e21643/limit.htm#TTREF455


text:
Q: Pandas: Reshape DataFrame without MultiIndex I need to reshape my dataframe
data = [
    ['Name 1', '17-11-2018', '2'],
    ['Name 2', '17-11-2018', '4'],
    ['Name 3', '17-11-2018', '6'],
    ['Name 1', '18-11-2018', '4'],
    ['Name 2', '18-11-2018', '6'],
    ['Name 3', '18-11-2018', '8'],
]
df = pd.DataFrame(data, columns = ['name', 'date', 'price'])
print(df)

  product        date price
0  Name 1  17-11-2018     2
1  Name 2  17-11-2018     4
2  Name 3  17-11-2018     6
3  Name 1  18-11-2018     4
4  Name 2  18-11-2018     6
5  Name 3  18-11-2018     8

I want to get such result:
name   17-11-2018 18-11-2018
Name 1          2          4
Name 2          4          6
Name 3          6          8

but my best solution was such with MultiIndex.
qty = pd.pivot_table(df, index='name', values='price', columns='date', aggfunc=np.sum, fill_value=0)
print(qty)

date   17-11-2018 18-11-2018
name
Name 1          2          4
Name 2          4          6
Name 3          6          8

Need some advise or solution how can I get the result, which I need.

A: You can use reset_index to reset your index and rename_axis to rename you column index:
qty = pd.pivot_table(df, index='name', values='price', columns='date', aggfunc=np.sum, fill_value=0)\
        .reset_index()\
        .rename_axis(None, axis=1)

     name 17-11-2018 18-11-2018
0  Name 1          2          4
1  Name 2          4          6
2  Name 3          6          8

If you want name as index, only use rename_axis:
qty = pd.pivot_table(df, index='name', values='price', columns='date', aggfunc=np.sum, fill_value=0)\
        .rename_axis(None, axis=1)

       17-11-2018 18-11-2018
name
Name 1          2          4
Name 2          4          6
Name 3          6          8


text:
Q: Why does typeof(null) return "object", but you can't assign properties to it? Bear with me here, I'm going to try something stupid.
When I evaluate typeof(null) in the console, I get "object", so logically, I should be able to assign properties to it, but  null.foo = 42 gives TypeError: Cannot set property 'foo' of null.
Is Javascript just picky when it comes to which global objects are mutable?

A: The specification  determines that typeof should return "object" for the null value, and at the same time defines null as a primitive:

A primitive value is a member of one of the following built-in types: Undefined, Null, Boolean, Number, and String; an object is a member of the remaining built-in type Object; and a function is a callable object.

So, null is not an object. That's why you can't assign properties to it. The value returned by typeof is artificial.

A: This page has a nice description of the history here surrounding why typeof(null) gives "object":
JS Data Types - Null
Here is the relevant portion (although I would suggest you read the whole post):

Why does typeof null return "object"?
// What's happening here?
typeof null === "object"; // true
The answer might disappoint some, but the truth is simply because the table above says to do so.
The reasoning behind this is that null, in contrast with undefined, was (and still is) often used where objects appear. In other words, null is often used to signify an empty reference to an object. When Brendan Eich created JavaScript, he followed the same paradigm, and it made sense (arguably) to return "object". In fact, the ECMAScript specification defines null as the primitive value that represents the intentional absence of any object value (ECMA-262, 11.4.11).

To draw a parallel here, consider typeof(NaN) === "number".  So why does JavaScript give "number" as the type of NaN (not a number)?  It is because NaN is used where numbers appear, it is a value that represents the intentional absence of a number value.  Similar reasoning applies to null, the only difference being that null is implemented as a primitive and NaN is actually implemented as a Number object (so NaN.foo = 42 would actually work).

A: null is a primitive data type. it has one value: null. it does not have a constructor. it is an object that is build in to the language. you can't create an object of the type null, in other words.


text:
Q: PHP file not uploading I don't mess with PHP alot, but I don't see what's wrong with this. I had this same exact code working about 15 minutes ago, but now it just stopped working. I didn't change anything, so I'm a little confused.
Anyways, It's a form and you are supposed to submit a screenshot, here's the code for my form,
<form method="post"
enctype="multipart/form-data">
Screenshot of them agreeing to terms:
<input type="file" name="file" id="file" />

<input type="submit" name="submit" value="Submit" />
</form>

I don't think anything is wrong with that. Here's the PHP that handles all this (I think/hope)
 if(isset ($_POST['loanee'])) {
            if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "
";
    }
  else
    {
    $name = md5_file(sys_get_temp_dir() . $_FILES['tmp_name']);
      move_uploaded_file(sys_get_temp_dir() . $_FILES["files"]['tmp_name'], "public_html/mc/images/{$name}.jpeg");
    }
  }

I am not getting anything echoed to me, and no errors are showing up in the error log, so what's wrong?
Thanks for any help.
Loanee is not the problem, as my sql database IS being updated after the picture is "uploaded", I didn't put the whole form, as some of it has some information I don't think is necessary, the form is working fine as I said before, sorry to everyone that keeps telling me that loanee isn't set in the form, it is.

A: You don't have to use sys_get_temp_dir(). The $_FILES["files"]['tmp_name'] will already point to the temp dir.
So change your code to something like this:
$name = md5_file($_FILES["file"]['tmp_name']);
move_uploaded_file($_FILES["file"]['tmp_name'], "public_html/mc/images/{$name}.jpeg");

Edit: Oh, and you should use is_uploaded_file to check whether or not a file has been uploaded.

A: I don't see where $_POST['loanee'] gets set, but it needs to be set. Otherwise the interesting code is just skipped.

A: At the first line of your php script you check for the loanee variable that is supposed to come from the HTML Form, but you don't have any field in your form with that name.
More specific :
if(isset ($_POST['loanee'])) {    // That line does not correspond to any input element into your form

To solve your problem either remove that statement control or add a new field into your form with that name.


text:
Q: Microsoft Graph API - 503 ErrorServiceUnavailable I'm using Microsoft Graph API for track my changes in some events in a calendar.
Currently, I get an HTTP 503 error in the endpoint: /me/calendarView/delta.
{
    "error": {
        "code": "ErrorServiceUnavailable",
        "message": "Active Directory operation did not succeed. Try again later.",
        "innerError": {
            "request-id": "0d70abca-dba6-4c27-9e99-2fa6cc6eb731",
            "date": "2018-10-09T13:27:46"
        }
    }
}

I thought it was my client, but I tried the example request on Microsoft Graph Explorer and I got the same.
Anyone has faced the same issue? Thanks for your guidance.

A: I can't upvote this or comment on this due to the reputation limit but we are seeing the same issue with some of our users.
We are hitting the endpoint: https://graph.microsoft.com/v1.0/me/mailFolders/<redacted>/messages/delta
For this particular user,
https://graph.microsoft.com/v1.0/me/mailFolders and
https://graph.microsoft.com/v1.0/me/mailFolders/<redacted>/childFolders
work.
But, asking for the messages with https://graph.microsoft.com/v1.0/me/mailFolders/<redacted>/messages/delta for a folder returns the error posted by OP


text:
Q: Merge two Strings in java with overlap and with allowed difference I want to 'Merge' two Strings, see the code:
public class Test {

    public static void main(String[] args) {
        printAllPossibleMergedString("abcdefdefd", "defdefdefghi");
    }

    public static void printAllPossibleMergedString(String a, String b) {
        System.out.println(a + b);
        int maxOverlap = Math.min(a.length(), b.length());
        for (int i = 1; i <= maxOverlap; i++) {
            if (b.startsWith(a.substring(a.length() - i, a.length()))) {
                System.out.println(a + b.substring(i));
            }
        }
    }
}

output:
abcdefdefddefdefdefghi
abcdefdefdefdefdefghi
abcdefdefdefdefghi
abcdefdefdefghi

Now I want to this method become 'Fault Tolerance' (wish you can understand), something like this:
void printAllPossibleMergedString(String a, String b, int tolerance);

So if I do:
// 'x' means a wrong character
printAllPossibleMergedString("abcdefdefx", "defdefdefghi", 1);

will output:
abcdefdefxdefdefdefghi
abcdefdefdefdefghi
abcdefdefdefghi

while:
printAllPossibleMergedString("abcdefdefxx", "defdefdefghi", 1);

only output:
abcdefdefxxdefdefdefghi

and of course:
printAllPossibleMergedString("abcdefdefxx", "defdefdefghi", 2);

will output:
abcdefdefxdefdefdefghi
abcdefdefdefdefghi
abcdefdefdefghi

So how to implement this efficiently?
Thanks.

A: It isn't clear what "Fault Tolerance" is, but a formal way of processing this would be as follows:
For all possibilities on comparing two strings, you can implement something called Edit Distance (or at least a variant of it).  Vary the weights of the different operations (eg. insertion at beg/end costs= 1, substitution at beg/end costs= 2), and everything else has infinite costs.  Then generate all possibilities with non-infinite costs.
https://en.wikipedia.org/wiki/Edit_distance

A: Even if that is not the whole solution to your point, this is a good starting point:
public static String mergeStrings(String s1, String s2) {

    if (s1.isEmpty() || s2.isEmpty()) {
        return s1 + s2;
    }

    if (s1.equals(s2)) {
        return s1;
    }

    int i = 0;
    String sub = s1.substring(i);
    while (i < s1.length()) {

        if (s2.startsWith(sub)) {
            return s1 + s2.replace(sub,  "");
        }

        i++;

        sub = s1.substring(i);
    }

    return s1 + s2;
}

No go ahead to calculate the Levenshtein distance for the if clause:
if (s2.length() > sub.length() && s2.substring(0, sub.length).levenshtein(sub) < tolerance)


text:
Q: How can I filter posts by user profiles with a certain field value? - Django I am creating a blog application using Django and I would like to filter the blog posts using user profiles with a certain field value. For example, let's say that there is a field for professions in the profile model of the users, I would like to filter all the posts posted by doctors. Is this possible and if so, how would I achieve this?

A: If you have a foreign key from Blog to User, then do this:
Blog.objects.filter(user__profile='doctor')


text:
Q: Add unique value to each iterate element HTML Angular 2 I have a problem with Angular 2.
I want to made List HTML like this:

..

With links but I don't know how to add iterate argument to HTML object in NG2.
It is my code:

        {{ item.name }}

     <show-NameG></show-NameG>

And I want to add a different name to each of the element li to recognize from has been clicked. In AngularJS worked something like this:
(click)="showNameG{{index}}= !showNameG{{index}}"

A: *ngFor provides an index context variable

{{ item.name }}

update

{{ item.name }}

export class MyComponent {
  get self() {
    return this;
  }
}

A: Use item, create a property showNameG and toggle its value

A: You must add following to your *ngFor:
let index = index;

At the end you should have this:

{{ item.name }}

Here is good description of *ngFor:
https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html


text:
Q: Sub queries, Aliases and Stored Values- MySQL I am given a problem as following:
Create a SQL statement that shows all shipped orders with a total of more than $14,000. The results must contain the customer's first_name, last_name, order_id, order shipped_date, number of items and total amount. Make sure any discount is taken into account when calculating the total amount.
Tables to draw from are:
Order Items: quantity, list_price, discount, order_id
Order: order_id, shipped_date, order_status, customer_id
Customers: first_name, last_name, customer_id.
I'm pretty new to SQL and sub-queries so I tried to build it from inside out and it kept giving me rows returned...until the last join ("sub2"). My code is below (inelegant, but I do need to figure out the problem before worrying about that).
select c.first_name, c.last_name, sub2.order_id, sub2.shipped_date, sub2.quantity, sub2.total_amount from customers AS c
    INNER JOIN(
            select o.order_id,  o.shipped_date, o.order_status, o.customer_id, sub1.total_price FROM orders as o
                INNER JOIN  (
                            SELECT oi.order_id, SUM((oi.list_price * oi.quantity) - ((oi.list_price * oi.quantity) * (oi.discount))) AS total_price
                                FROM order_items AS oi
                                group by oi.order_id
                            ) AS sub1
                ON o.order_id = sub1.order_id
                WHERE
                    sub1.total_price > 14000
                            AND
                    o.order_status = 4
                    ) AS sub2
ON c.customer_id = sub2.customer_id
;

The error I'm getting is "Unknown column 'sub2.quantity' in 'field list'"
I imagine Mysql does not like this double nesting, so how can I go about solving this?

A: There's no problem with nested queries, your problem is that the names on your nested statements don't correlate with the ones used outside as the alias.
eg: ... INNER JOIN(select o.order_id,  o.shipped_date, o.order_status, o.customer_id, sub1.total_price FROM ...
doesn't has a quantity casted, so when it's rows are called outside as sub2 there is an Unknown column 'sub2.quantity' in field list, it will fail also with sub2.total_amount for the same reason.
I'm guessing that since you are grouping by the total amount of an order, it should also give the sum of the items quantities. So the SQL should be like so:
select c.first_name, c.last_name, sub2.order_id, sub2.shipped_date, sub2.quantities, sub2.total_amount from customers AS c
    INNER JOIN(
            select o.order_id,  o.shipped_date, o.order_status, o.customer_id, sub1.total_price as total_amount, sub1.total_quantities FROM orders as o
                INNER JOIN  (
                            SELECT oi.order_id,SUM(oi.quantity) as total_quantities, SUM((oi.list_price * oi.quantity) - ((oi.list_price * oi.quantity) * (oi.discount))) AS total_price
                                FROM order_items AS oi
                                group by oi.order_id
                            ) AS sub1
                ON o.order_id = sub1.order_id
                WHERE
                    sub1.total_price > 14000
                            AND
                    o.order_status = 4
                    ) AS sub2
ON c.customer_id = sub2.customer_id group by sub2.order_id;


text:
Q: How do I add content for warning macro using storage format? I'm creating a markdown to confluence tool (using python markdown). I'm having an issue adding content for the warning macro.
The following creates the warning box with the title, but the content is missing.
<ac:structured-macro ac:name="warning">
  <ac:parameter ac:name="title">Do Not Modify This Page</ac:parameter>
  <ac:rich-text-body>

  This page is generated by a script. Any changes made
  here will be erased the next time this page is
  generated.

</ac:rich-text-body>
</ac:structured-macro>

The docs for the warning macro don't specify what should be used.
When I edit the warning box in the ui and get body.storage for the page this is what is returned.
<ac:structured-macro ac:name=\"warning\" ac:schema-version=\"1\" ac:macro-id=\"3520f15e-e8af-4b26-bf94-4dbc226d8284\">
  <ac:parameter ac:name=\"title\">Do Not Modify This Page</ac:parameter>
  <ac:rich-text-body>
blah frickin blah
</ac:rich-text-body>
</ac:structured-macro>

I have tried replacing <ac:rich-text-body> with nothing, plain-text-body, body, content and a few others I can't remember. None of these have worked.
Any ideas or pointers?

A: Adding the macro-id to the definition made it work.
  <ac:structured-macro ac:name="warning" ac:macro-id="3520f15e-e8af-4b26-bf94-4dbc226d8284">
    <ac:parameter ac:name="title">Do Not Modify This Page</ac:parameter>
    <ac:rich-text-body>

    This page is generated by a script. Any changes made
    here will be erased the next time this page is
    generated.

</ac:rich-text-body>
  </ac:structured-macro>


text:
Q: Run CMD code line in python, see results in terminal Anaconda I have this simple code I use to convert files with handbrake
"C:\Program Files\HandBrake\HandBrakeCLI.exe" -i c:\folder -o c:\folder2 --preset-import-file "D:\Handbreak\Script\dudeness.json"

I want to run this line in python and see the output it generates in the terminal
My Intention is to iterate "C:\folder" and "c:\folder2"

A: First,
import os
os.system("your command")

You can then use a cmd script to run python script


text:
Q: How can I make a script that opens terminal window, executes commands in it and remains open on Scientific Linux? I'm working in a remote server that uses Scientific Linux  (version=7.6 (Nitrogen)). I did a simple web application in Python3, and I found myself constantly opening a Mate Terminal (though, any terminal works), and writing
bash
python3 my_app.py

So, I can check if my app works locally in my browser.
I want a way to make this easier, and just click a shell script that opens a terminal windows and runs the commands mentioned. After that, the terminal window should remain open and I should be able to check my web application in the browser.
I wrote a shell script with this line:
gnome-terminal --tab --title="tab 1" --command="bash -c 'python3 my_app.py; $SHELL'"

As recommended here, in the case of Ubuntu: https://askubuntu.com/questions/46627/how-can-i-make-a-script-that-opens-terminal-windows-and-executes-commands-in-the
(Note: I tried all other answers and they didn't work, Gabriel Staples answer was the only one that almost worked). I also allowed the file to be executed as program.
There are 2 problems with this solution. First, the terminal does not remain open. Second, when I click the file I received the following message (before terminal is closed): ModuleNotFoundError: No module named 'flask'. This is because the script is using the wrong version of python3 in this server. There is one installed by the admin, and the anaconda version installed by me in my home directory. I've been getting around this problem by writing bash before using python3 my_app.py. It seems that after I use bash the file .bashrc in my home directory is used, and the variable $PATH gives priority to my version of python3 (I checked that $PATH is different before and after I write bash in the terminal).
I was wondering if there is a way to make a script (on Scientific Linux) that opens a terminal window and executes commands in them, and after that remains open.
I also was wondering if there is a way that the web application automatically pops up in my browser after this.

A: The terminal will close after the command is completed. To leave the terminal open, I generally prevent the script from completing, e.g. with a prompt as follows:
while [[ \$response != q ]]; do read -n 1 -p [q]uit? response; echo; done

Hence, for your script, append this to the end of the bash -c command.
gnome-terminal --tab --title="tab 1" --command="bash -c 'python3 my_app.py; $SHELL'; 'while [[ \$response != q ]]; do read -n 1 -p [q]uit? response; echo; done'"

For the wrong python being used, you can either load ~/.bashrc by using bash -i, or you could explicitly specify the python version with /path/to/python3 instead of plain python3 in your command.
Hence, your final command is either
gnome-terminal --tab --title="tab 1" --command="bash -ci 'python3 my_app.py; $SHELL'; 'while [[ \$response != q ]]; do read -n 1 -p [q]uit? response; echo; done'"

or
gnome-terminal --tab --title="tab 1" --command="bash -c '/path/to/python3 my_app.py; $SHELL'; 'while [[ \$response != q ]]; do read -n 1 -p [q]uit? response; echo; done'"


text:
Q: How does the Standard deal with self-referencing iterators in container insert functions? When dealing with C++ Standard Library containers like std::vector, how do their range-based insertion methods handle the user using iterators that reference the vector's own contents?
Presumably if they are say, vector::iterator already, then the implementation can special-case this scenario, but if they are a user-defined type which eventually results in accessing the vector, how does the vector deal with keeping those iterators valid whilst evaluating the range? Does the Standard simply ban referencing the vector in the range?
For a simple example, consider an iterator whose value_type is size_t, and the result of de-referencing it is the size of the vector being inserted into.
struct silly_iterator {
    vector<std::size_t>* v;
    unsigned number;
    std::size_t operator*() { return v->size(); }
    operator++() { --number; }
    bool operator==(silly_iterator other) const { return number == 0; }
    // other methods
};
std::vector<std::size_t> vec = { 3, 4, 5, 6, 7 };
vector.insert(vector.begin() + 2, silly_iterator(&vec, 10), silly_iterator());

What is the contents of vec after this code has executed?
For another example,
struct silly_iterator {
    std::vector<std::size_t>* v;
    std::size_t operator*() { return 0; }
    operator++() { --number; v->push_back((*v)[4]); }
    bool operator==(silly_iterator other) const { return number == 0; }
    // other methods
};
std::vector<std::size_t> vec = { 3, 4, 5, 6, 7 };
vec.insert(vec.begin() + 2, silly_iterator(&vec, 10), silly_iterator());

A: Basically, the only reason to invalidate iterators/references for vector is a reallocation, since otherwise you are still pointing at some part of your vector.
C++11 23.3.6.3/5:

Remarks: Reallocation invalidates all the references, pointers, and iterators referring to the elements
  in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after
  a call to reserve() until the time when an insertion would make the size of the vector greater than
  the value of capacity().

This is again reiterated in the remarks to the insert functions C++11 23.3.6.5/1:

Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens,
  all the iterators and references before the insertion point remain valid. [...]

With vector, you can consider your iterators to behave very much like pointers (which shows why exactly reallocation will cause problems). In fact, the reference type is value_type&, as defined by the standard, showing that references are indeed not even wrapped.
Note, that the iterators' target may change by the insertion, since the underlying data changes. Also, to be standards compliant, you would need to ensure that reallocation does not happen (e.g. with a call to reserve).

A: In C++11 n3242 (which is slightly old draft) in 23.2.3 table 100 we learn that for the iterator pair insert function, pre: i and j are not iterators into a. I believe based on that wording I would choose to broadly interpret that as i and j shall not access a, and that both of your iterators are undefined behavior.
But let's say that my broad interpretation is not what was intended by the standard. Then to answer your question, for input iterators the result is almost certainly going to be: 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 5, 6, 7 while for forward iterators or better one of 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7 or 3, 4, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 5, 6, 7 depending on whether the size is updated before or after the elements are copied into the open space. I don't see anywhere that the results for forward iterators in such a case would be specified.


text:
Q: Adding sub columns to every single existing columns in pandas I have a data frame with over 2000 columns with complicated names.
Each column has a price value, with an index of time and I want each column to have additional sub column of 'r'.
For ex.
col_1  col_2    col_3   col_4  ...........   col_n

to be changed into
col_1  col_2    col_3   col_4  ...........   col_n

I price I r I .................................. I price I r I

I have tried multi index method, but I am having trouble.
All the columns have a price, and I just want to use existing values for  the new price column, and add extra sub column called k.


text:
Q: d3.js general update pattern for stacked bar chart I am making a stacked bar chart in d3.js and have the following code which currently works for what I need:
    const stackedData = d3.stack().keys(keys)
    const layers = stackedData(this.data)

    let time = this.chart.selectAll('.time').data(layers);

    // removes time from the DOM
    time.exit().remove();

    // adds time to the DOM
    this.chart.append("g")
      .selectAll("g")
      .data(layers)
      .join("g")
      .style("fill", (d, i) => colors[i])
      .selectAll('.time')
      .data(d => d)
      .enter().append('rect')
        .attr('class', 'time')
        .attr('x', d => this.xScale(d.data.date))
        .attr('y', d => this.yScale(0))
        .attr("width", this.xScale.bandwidth())
        .attr('height', 0)
        .transition()
        .delay((d, i) => i * 10)
        .attr('y', d => this.yScale(d[1]))
        .attr('height', d => this.yScale(d[0]) - this.yScale(d[1]))

However, I am unsure on what the general update pattern should be to update the shapes already present in the DOM on refresh. for a standard (non-stacked) chart, it would be as follows, however these does not work for a stacked chart:
// update existing time
this.chart.selectAll('.time').transition()
  .attr('x', d => this.xScale(d.date))
  .attr('y', d => this.yScale(d.revenue))
  .attr('width', this.xScale.bandwidth())
  .attr('height', d => this.graphHeight - this.yScale(d.revenue))
  .attr("fill", "#007bff")


text:
Q: UIScrollview scrollable when contentView's size increases left and top I have a UIScrollView- scv and a UIView - ocv that have been generated dynamically (no IB), I have added ocv as a subView of scv. Initially i set the content size of scv to the frame size of ocv. But at run time I have to increase the width of ocv because I keep adding subviews onto ocv that extend beyond the left boundary of ocv. Now when I set a new contentSize for my scrollView, It scrolls to show the right side of ocv while the content I want to see is on the left.
Same is the case with top. I keep adding subviews beyond the top boundry of ocv, but i cant scroll to see the top part, i can only scroll to see the bottom empty part..please suggest me a solution..

A: I believe it is simple. Can u please check if u have selected sc are being checked in your
Interface builder? If everything is fine there, then please increase the height of your scroll view namely scv and also specify your UIView and the additions of subviews to it through code rather than from Interface builder?


text:
Q: How can I tell whether a given linux distro's wifi is managed via NetworkManager vs wpa_supplicant? It seems like different distros use either wpa_supplicant or NetworkManager to handle their wifi connections. It also appears to be the case that these are mutually exclusive and aren't meant to be used together.
Where can I find which distros use which methods to manage their connections?

A: use ps aux to get the computer processes and grep for finding the process
ps aux | grep network

output on Macintosh:
_networkd          206   0.0  0.1  4385868   8148   ??  Ss   Sun02PM   0:24.95 /usr/libexec/symptomsd

A: wpa_supplicant is a wireless daemon, it can work independently from the network managers (e,g: NetworkManager, wicd, connman ...)
NetworkManager require a wireless daemon to manage WPA : wpa_supplicant , iwd .


text:
Q: top 1 date foreach date I have this structure
table idc (numId,idInt, IdAffiliate)
table glob (idInt, IdAtt)
table gratt(IdAtt, dtRomp)
Table update(IdAffiliate, dateUpdate)

making this select statement will give me this :
SELECT
    NumId,
    dateUpdate,
    DtRomp,
    Idc.IdFiliale
FROM Idc inner join glob on glob .IdInt = Idc.IdInt
         inner join Grat on Glob.IdAtt = Grat.IdAtt
         inner join update on update.IdAffiliate = Idc.IdAffiliate
where NumId = 9976666

will give me this :
NumId   DtUpdate              DtRomp            filiale
9976666 01/05/2005            11/07/2006        27
9976666 01/05/2005            03/07/2008        27
9976666 01/05/2005            24/06/2010        27
9976666 01/05/2006            11/07/2006        27
9976666 01/05/2006              03/07/2008      27
9976666 01/05/2006            24/06/2010        27

I m trying to do this :
to select the most close dtUpdqte to DtRomp and that is inferior to it
Kindest regards
I have been trying but but with no solution yet.

A: You can do this with row_number():
select NumId, dateUpdate, DtRomp, Idc.IdFiliale
from (SELECT NumId, dateUpdate, DtRomp, Idc.IdFiliale,
             row_number() over (partition by NumID, DTRomp order by DTRomp desc) as seqnum
      FROM Idc inner join glob on glob .IdInt = Idc.IdInt
               inner join Grat on Glob.IdAtt = Grat.IdAtt
               inner join update on update.IdAffiliate = Idc.IdAffiliate
      where NumId = 9976666 and dateUpdate < DTRomp
     ) t
where seqnum = 1;

A: Try to use datediff function as below:
SELECT
    NumId,
    dateUpdate,
    DtRomp,
    Idc.IdFiliale
FROM Idc inner join glob on glob .IdInt = Idc.IdInt
         inner join Grat on Glob.IdAtt = Grat.IdAtt
         inner join update on update.IdAffiliate = Idc.IdAffiliate
where NumId = 9976666
and datediff(day,dateUpdate,DtRomp) = (
                                         SELECT
                                         min(datediff(day,dateUpdate,DtRomp))
                                         FROM Idc inner join glob on glob .IdInt = Idc.IdInt
                                         inner join Grat on Glob.IdAtt = Grat.IdAtt
                                         inner join update on update.IdAffiliate = Idc.IdAffiliate
                                         where NumId = 9976666

                                      )

More information about datediff().

A: It worked with this!!!!!
SELECT
NumId,
dateUpdate,
DtRomp,
Idc.IdFiliale
FROM Idc inner join glob on glob .IdInt = Idc.IdInt
         inner join Grat on Glob.IdAtt = Grat.IdAtt
         inner join update on update.IdAffiliate = Idc.IdAffiliate
where NumId = 9976666
and datediff(day,dateUpdate,DtRomp) = (
                                         SELECT
                                         min(datediff(day,dateUpdate,DtRomp))
                                         FROM Idc ainner join glob b on a.IdInt = c.IdInt
                                         inner join Grat con b.IdAtt = c.IdAtt
                                         inner join update d on d.IdAffiliate = Idc.IdAffiliate
                                         where NumId = 9976666 and Idc.IdAffiliate = a.IdAffiliate and Grat.DtRompu = c.DtRompu and Grat.DtRompu>DtDebValidite

                                      )

Regards


text:
Q: Python 3.75, importing package that is installed in edit mode Problem:
I'm setting up unit testing with pytest and need to import the objects I want to test. I installed the package that I am testing in edit mode. However, from my_pkg.file import File causes ImportError.
I can see the module installed with a reference to my remote repository, prepended with an -e semaphore when I run pip freeze.
I also see the egg object sitting in the package directory in /src.
Error Message in console:

ImportError while importing test module
'C:\Users\zzz\source\repos\proj\application\tests\test_file.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
return _bootstrap._gcd_import(name[level:], package, level)
from my_pkg.file import File E   ModuleNotFoundError: No module named 'my_pkg'

Package Directory:


text:
Q: Stop Ubuntu from hanging when video is run I'm running ubuntu 16.04, and I have a RV730 PRO [Radeon HD 4650] graphics card. It's fine, except that when I play video it usually locks up Ubuntu.
I can SSH in at this point and and kill the video player but it makes no difference; it's like it's done something to the window manager. Samba, virtualbox etc are all still running fine but I have to power cycle the box if I'm to do anything visually again; the mouse and keyboard do nothing (so no control-alt-f1).
I suppose I'll have to buy a graphics card which is more compatible with this version of Ubuntu (I understand some sort of decision was taken where this card will never be supported properly on recent versions of Ubuntu despite not being anywhere near as old as other hardware I'm happily running ubuntu) but I was wondering if there was some way of preventing whatever it is that's crashing from being run; ie, is there some sort of software emulation of video which doesn't crash? I don't mind if the result would be unusably slow as I don't watch video on this box, but it would be nice to not have to reboot if I accidentally double click on a video file.  Oddly, video never crashes when run from a browser.

A: As stated here, bottom of section 3,

Those of you on Radeon device should be aware that the standard AMD driver is NOT SUPPORTED in 16.04 at this time. A future point release is expected to bring support for the new AMDGPU driver. Expect a regression in system performance if you upgrade.

You will probably either have to find some open-source unofficial driver, or just unplug or disable your GPU, as it's not going to help 16.04 with video playback.

A: Best answer seems to be to associate all video file formats with VLC, then load VLC and select Tools -> Preferences -> Input/Codecs and set Codecs:Hardware-accelerated decoding to Disable.


text:
Q: SQLSTATE[22021]: Character not in repertoire I'm having this problem while seeding my PGSQL Database:
   Illuminate\Database\QueryException  : SQLSTATE[22021]: Character not in repertoire: 7 ERROR:  secuencia de bytes no válida para codificación «UTF8»: 0xe3 0x83 0xe2 (SQL: insert into "races" ("name", "public_name", "members", "updated_at", "created_at") values (harp��a, Harpía, 23, 2018-04-21 20:30:20, 2018-04-21 20:30:20) returning "id")

  at C:\Sandbox\rpgforum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[22021]: Character not in repertoire: 7 ERROR:  secuencia de bytes no válida para codificación «UTF8»: 0xe3 0x83 0xe2")
      C:\Sandbox\rpgforum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:330

  2   PDOStatement::execute()
      C:\Sandbox\rpgforum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:330

  Please use the argument -v to see more details.

And this is my Seeder's code:
<?php

use Illuminate\Database\Seeder;
use App\Models\Race;

class RaceTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {

      $races = [
        'Humano',
        'Orco',
        'Elfo',
        'Harpía',
        'Enano',
      ];

      for ($i = 0; $i < count($races); $i++) {

        $race_i = utf8_encode($races[$i]);

        $race = Race::create([
          'name' => strtolower($race_i),
          'public_name' => $race_i,
          'members' => mt_rand(10,30),
        ]);

      } // for

    }
}

My database configuration:
pgsql database
My config.database file config:
config.database file
Is there any solution for this problem? I can find the way to get rid of this problem...
EDIT:
I just noticed something weird. I got two records in my database:
database records
And both of them have symbols that gave me problem with the seeder. Maybe the problem is within the seeders logic? I'm doing the exact same thing I do the whole time with my Laravel/Postgresql projects so i can't find the reason why i can't seed words with accent mark but i can use a simple form to store that kind of information. Any ideas ?


text:
Q: Numerical discrepancy between tf.scan and matmul Following the answer here: Tensorflow - matmul of input matrix with batch data
I compared between the tf.scan-based results and the tf.matmul-based results. As far as I can see, the results should be identical, but I'm getting different results, consistently. I also compared with Keras' K.dot with the same functionality as reference.
I'll appreciate any explanation as to why that is, or what is my mistake.
Attached is the full MWE, with two results, evaluated on two separate computers (with different GPUs).
import tensorflow as tf
import keras.backend as K
from keras.layers import Lambda, Input
import numpy as np

na = 100
nb = 10000
mb = 10
v = Input( (1,na) )
e = tf.placeholder(dtype=tf.float32, shape=(na,nb))

def dot_a(v):
    res = K.dot(v,e)
    return res

initer = np.zeros((1,nb),dtype=np.float32)
def dot_b(v):
    res = tf.scan(lambda a,x: tf.matmul(x, e), v, initializer=tf.constant(initer))
    return res

def dot_c(v):
    v = tf.reshape(v, [-1, na])
    h = tf.matmul(v, e)
    res = tf.reshape(h, [-1, 1, nb])
    return res

mul1 = Lambda(dot_a)(v)
mul2 = Lambda(dot_b)(v)
mul3 = Lambda(dot_c)(v)

# inputs
v0 = np.random.random((mb,1,na)).astype(np.float32)
e0 = np.random.random((na,nb)).astype(np.float32)
v0 = np.round(v0,decimals=2)
e0 = np.round(e0,decimals=2)

sess = tf.Session()
out1,out2,out3 = sess.run([mul1,mul2,mul3], feed_dict={v:v0,e:e0})
print 'norm(out, out-matmul)',np.linalg.norm(out1-out2)
print 'norm(out, out-scan)',np.linalg.norm(out1-out3)

Output in computer 1:
norm(out, out-matmul) 0.000715436
norm(out, out-scan) 0.0

Output in computer 2:
norm(out, out-matmul) 0.000511952
norm(out, out-scan) 0.0


text:
Q: MyFaces: how to show error messages in console log Running a JSF web application on MyFaces, if there's an error at the server side such as null pointer, what I get is a message that pops up in the browser but nothing is logged in the server console where more information on the error would be displayed. Is there a way to revert this? For example, this is a message that I get:

A: Take a look at the error message, it's said that your project stage is development. that why the error don't get logged in the console. If you put your application in production mode it's should log normally in the console


text:
Q: Importing akka module using SBT I'm trying to import an akka dependency to my project using sbt.
The akka modules I need are akka-actor and akka-remote. The curious thing is that akka-actor has no problems importing, but the remote module appears as an unknown artifact.
I'm using IntelliJ and scala 2.12.1. Does someone have this problem or can help me in any way?

A: Try leave a blank line between the two libraryDependencies:
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.5.0"

libraryDependencies += "com.typesafe.akka" %% "akka-remote" % "2.5.0"

Or keep them in a Seq:
libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-actor" % "2.5.0",
  "com.typesafe.akka" %% "akka-remote" % "2.5.0"
)


text:
Q: No pending reply timeout I am trying to deveopemet synchronous  poc. My objective is i want to send message to  request topic and get back updated message.  I have request-topic for producer, and reply-topic with consumer.
i am able send the message to consumer and able to update the message as well. but i am not getting response on consumer side.  getting an error  " No pending reply-timeout, perhaps using shared reply topic.


text:
Q: How do I get a PHP form page to close on succesful submit? Is there a quick and easy way to make this form.php code close the window after submitting instead of redirecting? I can deal with the redirect if there is no way to do this, but would like to have the window just close, as the original form is being opened in a new window. Code below:
<?php
if (!empty($_POST)) {

// Used for later to determine result
$success = $error = false;

// Object syntax looks better and is easier to use than arrays to me
$post = new stdClass;

// Usually there would be much more validation and filtering, but this
// will work for now.
foreach ($_POST as $key => $val)
    $post->$key = trim(strip_tags($_POST[$key]));

// Check for blank fields
if (empty($post->First) OR empty($post->Last) OR empty($post->Email))
    $error = true;

else {

    // Get this directory, to include other files from
    $dir = dirname(__FILE__);

    // Get the contents of the HTML email into a variable for later
    ob_start();
    require_once($dir.'/html.php');
    $html_message = ob_get_contents();
    ob_end_clean();

    // Load the SwiftMailer files
    require_once($dir.'/swift/swift_required.php');

    $mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance     of SwiftMailer

    $message = Swift_Message::newInstance()
                   ->setSubject('Hospitality Recycling Program Calculator Results') // Message subject
                  ->setTo(array('bsmith@cleantheworld.org', $post->Email =>$post-> First ))  // Array of people to send

                   ->setFrom(array('bsmith@cleantheworld.org' => 'Clean the World')) // From:
                   ->setBody($html_message, 'text/html');

    // Send the email, and show user message
    if ($mailer->send($message))
        $success = true;
    else
        $error = true;

}

}
header("location: http://www.cleantheworld.org/newpartner.asp");
?>

A: I agree with @jeroen that a better solution would be to use AJAX but you can just output some javascript in the head of the redirect to close the page. Again I don't recommend this as a good solution to the problem but it will work as long as javascript is enabled in the users browser.
<script type="text/javascript>
    self.close();
</script>