text:
Q: Android Google Map v2 - Start new Activity by clicking somewhere on the GoogleMap This is my situation:
I have an Activity which reads the current Location, shows the Address in a TextView and sets a Marker on a "small" GoogleMap" at the bottom area of the Activity. At this map ScrollGestures are disabled - it's just to show the current location to the user.
IF the currect Location is not correct the User should be able to click somewhere on the map,  which opens a new activity where he can drag the marker to his correct position.
My question is:
How can i start a new Activity by clicking somewhere on the map.
I tried this, but i was not able to put an Intent in the onClick method:
a link!
Here is my code:
    private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();
        //googleMap.setMyLocationEnabled(true);

        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
                lat, lng), 13));
        googleMap.getUiSettings().setScrollGesturesEnabled(false);
        googleMap.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng arg0) {

                Intent intent2 = new Intent(this, SettingsActivity.class);
                startActivity(intent2);
            }
        });
        addMarker();

        }
    }
}

A: When you use this in your call to startActivity, you are not referencing a Context as you should be. Instead, you are referencing the instance of the anonymous inner class you have created for the onMapClickListener. You either need to replace this with YourActivityName.this or with YourFragmentName.this.getActivity() depending on what the outer class is (seems like it's a Fragment...)
Please more clear about what error you are receiving next time.


text:
Q: Use Calendar function for leap year I'm trying to use the import function to calculate my leap year, however I've been getting error messages for my code:
import calendar
year=input("Enter a year: ")
check=calendar.isleap(year)
if check == True:
    print("In",year,"February has 29 days.")
else:
    print("In",year,"February has 28 days.")

Would appreciate it if anyone can point out my mistake here!
I've also tried the
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

method by using 'if-else' statements, but have also seem to stumble onto a roadblock using that method as well...My code for that method is shown below:
print ('hi')
input_year= input("Please enter a year: ")
if (input_year) % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
    print ("Yes sir")
else:
    print ("no sir")

A: Python 2 will automatically attempt to convert the string the user typed into a number and return an int from the input function if it can.  But Python 3 will be more consistent and always return a string even if the characters the user typed are logically understood to be a number.
Hence, do this:
import calendar
year=input("Enter a year: ")
year = int(year)
check=calendar.isleap(year)
if check:
    print("In",year,"February has 29 days.")
else:
    print("In",year,"February has 28 days.")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get Ground when 5V are available This may sound like a basic task, but I am new to Electrical engineering.
I want to combine an QI Charging matt into my SmartHome. When my phone is charged by the mat a Green LED lights up. This LED is feed with 5V. I am using a window sensor to integrate this into my SmartHome. The sensor has a little magnet switch that pulls 5V to GND.
I now need to somehow get GND when the 5V are supplied by the QI charger and I have no idea how.
Thanks!

A: Use this circuit. Provide the 5V from the charger LED at control signal terminal. Connect the terminal on/off switch in the place of your window sensor.
The window sensor will get a GND when there is 5V at the charger.


text:
Q: Bulk theme settings in wordpress multisite I have a multisite with 500+ subsites.
I would like to install the same theme in all 500+ sites. Most of them requires configuration like selecting sidebar(left/right), Selecting primary menu etc.
Is there any plugin available to do this job?
OR
Can anyone give me some idea?
Thanks

A: If you configure your Theme settings code properly, the Theme will work fine without having any user-defined settings.
The key is to define a defaults array, and anytime you need to output a Theme option, run an array_merge() on the defaults array, and the theme's options DB entry. Something like this:
<?php
global $mytheme_options;
$mytheme_options = mytheme_get_options();

function mytheme_get_options() {
    // Defaults array, defined elsewhere
    $option_defaults = mytheme_get_option_defaults();
    // Return parsed args
    $options = wp_parse_args( get_option( 'theme_mytheme_options', array() ), $option_defaults );
}
?>

Then you only ever use the globalized $mytheme_options, which will always contain either the default option, or the user-defined option, if defined.


text:
Q: Is there an easy way to bind a Swing interface with a data source I am programming the admin part of a Swing application using WindowBuider, it would basically be tables filled with items which I need to do a CRUD operations on them. the Data comes from MySQL database.
I can do it by hand but, it will take too long
Is there an easy way to do that ? using something like in Access forms...
Thanks

A: Standard Swing components a too low level and do not provide anything like you need. If commercial solution is suitable from you, have a look at JIDE components.

A: The article Binding Beans and Data in a Desktop Application shows how to bind persistent data to Swing components. NetBeans can generate entity classes from a database and create the corresponding Persistence Unit using any of several providers. This very simple example began with a Customer entity derived from an H2 Database and accessed via a Top-Link Essentials provider.

A: The NetBeans Platform contains all kinds of tables and data binding. Because it's built with Swing, you can use the components in regular swing apps.


text:
Q: vim how to highlight current buffer in :ls I recently discovered the use of buffers in vim and I was wondering if it is possible to highlight the line of the current buffer in the window which show :ls result?
I know that the current buffer is marked with % but highlighting the line would be easier to see.
Any vim-master can give me hand with this?

A: There's no built-in option, so you'd either have to directly modify Vim's sources, or write a custom command in Vimscript. I would not recommend any of those.
For the latter, you can use :redir to capture the output of built-in :ls, split() into lines, then :echo each in a loop, matching with the leading % to detect the current one, and in that case use :echohl to change the highlighting group. The cmdalias.vim - Create aliases for Vim commands could allow you to install that new :LS command over the built-in :ls, but again, I think this is too cumbersome for too little effect.


text:
Q: Elasticsearch - search for keys inside nested field value, which is a json I needed some help with a query that I trying to execute.
I have a field called scores inside one of my indexes which stores some ai model scores for as a json. The basic structure of this field is like (showing a couple of records from the index):
[{"scores":
    {"a/b": 1.231,
     "a/c": 23.11,
     "x/a": 1232.1}},
 {"scores":
    {"a/d": 3.1}}]

And the mapping is something like:
{"scores":
  {"properties":
    {"a/b": {"type":"float"},
     "a/c": {"type":"float"},
     "a/d": {"type":"float"}}}}

The value for the field scores, which is another json will have arbitrary fields i.e. I won't know which fields are present in that json beforehand.
What I want to do is to search for the keys inside that json i.e. if I search for a/, it should return ["a/b", "a/d", "a/c"].
I know this is possible via nested query, but looks like for that I'll need to re-map my indexes, so that the field scores has a flatter data structure. However I didn't want to do that for now and just wanted to use the existing structure and execute my query.
If anyone has ideas about this, kindly throw them my way.

A: You can use _source to limit what's retrieved:
POST indexname/_search
{
 "_source": "scores.a/*"
}

Alternatively, you could employ script_fields which do exactly the same but offer playroom for value modification too:
POST indexname/_search
{
  "script_fields": {
   "scores_prefixed_with_a": {
     "script": {
       "source": """params._source.scores.entrySet()
                        .stream()
                        .filter(e->e.getKey().startsWith(params.prefix))
                        .collect(Collectors.toMap(e->e.getKey(),e->e.getValue()))""",
       "params": {
         "prefix": "a/"
       }
     }
   }
 }
}

A: Use .filter() - .reduce() on Object.keys()

const data = [{"scores": {"a/b": 1.231, "a/c": 23.11, "x/a": 1232.1}}, {"scores": {"a/d": 3.1}}];

const allowed = 'a/';

const res = data.map((d) =>
    Object.keys(d.scores)
    .filter(key => key.startsWith(allowed)))
    .reduce((prev, curr) => prev.concat(curr));

console.log(res)

[
  "a/b",
  "a/c",
  "a/d"
]

Originial, with object instead off keys;

const data = [{"scores": {"a/b": 1.231, "a/c": 23.11, "x/a": 1232.1}}, {"scores": {"a/d": 3.1}}];

const allowed = 'a/';

const res = data.map((d) =>
  Object.keys(d.scores)
    .filter(key => key.startsWith(allowed))
    .reduce((obj, key) => { obj[key] = d.scores[key]; return obj; }, {}));
console.log(res);


text:
Q: how to pass plot arguments when using split for multivariate point process To learn some plotting in spatstat, I am trying to plot database mucosa using the split function to create a multivariate plot. I get two different subplots of mucosa, but by default they both have the same symbology.
library(spatstat)
plot(split(mucosa))

Now in the two subplots, I would like to customise each subplot in terms of colour, size, shape etc. How can I do this? please advice.
I tried to pass pch and cex and col as a vector of two elements (because I know it is two types), but I get error
plot(split(mucosa), pch=c(19,3))
Error in symbolmap(..., chars = chars, cols = cols) :
  Argument 'pch' is neither a function nor a constant

A: It seems untraditional to plot the types with different plotting characters when they are split into different panels. Why do you want to do that?
If you plot them in the same single plot you can just do as you suggest:
plot(mucosa, pch = c(19, 3))

And here you can add cols, cex, ...
However, if you first split the point pattern the more complicated plot.listof is called and you can look at that help file for details. Also if you look at our book Baddeley, Rubak and Turner (2015) you may find multi-panel plots which may inspire you. On the companion website for the book you can find code to generate all the figures of the book (requires a bit of searching though).

A: Use the argument chars instead of pch to specify several plotting characters.
In the call to split, you need to specify the argument un=FALSE which ensures that each of the split point patterns retains its original mark information (i.e. the type of each point).
So you need
plot(split(mucosa, un=FALSE), chars=c(19,3))


text:
Q: Area (quadratics) go negative vs. Volume (cubics) goes to infinity Consider a typical "fenced garden" problem, which is easily represented by a quadratic, e.g.,
$a(w)=-10w^{2}+100w$ where $w$ is the width (or the wall, if you prefer).
which peaks at $(5,250)$ and has zeros at $0$ and $10$.
And a similarly typical "box volume with cutouts" problem which is easily represented by a cubic, e.g.,
$v(c)=4c^{3}-12c^{2}+9c$ where $c$ is the length of the cutout.
which peaks at $(0.5,2)$ and has zeros at $0$ and $1.5$.
Now, to the left of each lower bound of the domain of each function lies a non-sensical negative length, and the values of the area and volume functions reflect this by having similarly non-sensical negative area and volume. However, to the right of the upper root they behave differently! Even though the lengths (i.e., the domains: $w$ and $c$) are real and sensible (positive), the quadratic is negative, reflecting that you're over-running the total fence length, and would have to create fence from the air (that is, you have negative fence) in order to make this work. However, the quadratic does a completely different thing, in essence allowing you to create cardboard from the air in exactly the way that the quadratic appears to $not$ permit! And, of course, you can go happily on your way making a larger and larger $positive\ volume$ box, whereas you can't do that with the area! (You can go happily on your way, but you end up with a larger and larger $negative$ non-sense area!)
This may be a philosophical question instead of a mathematical one, and I'm happy to be told so. It also may be a "that's just how it is" thing, like Gabriel's Horn, and, again, I'm happy to be told so. Or maybe there's some interpretation where these both make sense, and if that's the case, I'd love to learn it!
Thanks in advance!


text:
Q: dynamic xml nodes using xslt I use a transformation in SAP in order to generate an XML file. I've already achieved that by referring only to explicit nodes. Now, the requirement would be to enhance the existing XML result by adding new nodes dynamically, based on a number of tags that can vary in number.
Here is the XML source :
<!-- edited with XMLSpy v2011 rel. 3 sp1 (http://www.altova.com)-->
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
    <asx:values>
        <MSAPO01>
            <LOGICALID>SAP-AMG</LOGICALID>
            <COMPONENT>Whatever</COMPONENT>
            <CONFIRMATION>Always</CONFIRMATION>
            <CREATIONDATE/>
            <BOID/>
            <SYNC_CONFIRM>Never</SYNC_CONFIRM>
            <SYNC_ACTION>Change</SYNC_ACTION>
            <DATAAREA>
                <item>
                    <ACTION>Change</ACTION>
                    <STATUS_HEAD>Z00</STATUS_HEAD>
                    <CREATIONDATE/>
                    <VBELN>0050023362</VBELN>
                    <POSNR>000001</POSNR>
                    <SHIPTO>C001991</SHIPTO>
                    <QUALITY>C</QUALITY>
                    <MTSMTO>MTO</MTSMTO>
                    <INTEXP>IN</INTEXP>
                    <NTGEW>22.520 </NTGEW>
                    <GEWEI>TO</GEWEI>
                    <DELIVERYMODE>Librex</DELIVERYMODE>
                    <PROPERTIES>
                        <ZPEL_PROPERTY_S>
                            <ID>ACTION</ID>
                            <DESCRIPTION>Action code</DESCRIPTION>
                            <DATAVALUE>007</DATAVALUE>
                            <DATATYPE>CHAR</DATATYPE>
                            <UM/>
                            <ANY>002</ANY>
                        </ZPEL_PROPERTY_S>
                        <ZPEL_PROPERTY_S>
                            <ID>AUGRU</ID>
                            <DESCRIPTION>Order reason (reason for the business transaction)</DESCRIPTION>
                            <DATAVALUE>01</DATAVALUE>
                            <DATATYPE>CHAR</DATATYPE>
                            <UM/>
                            <ANY/>
                        </ZPEL_PROPERTY_S>
                        <ZPEL_PROPERTY_S>
                            <ID>ZTERM</ID>
                            <DESCRIPTION>Terms of payment key</DESCRIPTION>
                            <DATAVALUE>0401</DATAVALUE>
                            <DATATYPE>CHAR</DATATYPE>
                            <UM/>
                            <ANY/>
                        </ZPEL_PROPERTY_S>
                        <ZPEL_PROPERTY_S>
                            <ID>QUALF</ID>
                            <DESCRIPTION>IDOC qualifier reference document</DESCRIPTION>
                            <DATAVALUE>001</DATAVALUE>
                            <DATATYPE>CHAR</DATATYPE>
                            <UM/>
                            <ANY>Z022</ANY>
                        </ZPEL_PROPERTY_S>
                        <ZPEL_PROPERTY_S>
                            <ID>QUALF</ID>
                            <DESCRIPTION>IDOC qualifier reference document</DESCRIPTION>
                            <DATAVALUE>002</DATAVALUE>
                            <DATATYPE>CHAR</DATATYPE>
                            <UM/>
                            <ANY>Z023</ANY>
                        </ZPEL_PROPERTY_S>
                    </PROPERTIES>
                </item>
            </DATAAREA>
        </MSAPO01>
    </asx:values>
</asx:abap>

The 'Properties' node is dynamically determined (in numbers and content). My original XSLT is:
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.siemens.com/ad/mes/b2mt-1.0" xmlns:amg="Pelican@AMG" xmlns:bml="http://www.wbf.org/xml/b2mml-v02" xmlns:oag="http://www.openapplications.org/oagis"
xmlns:sit="http://www.siemens.com/ad/mes/b2mml-v02-SITExt-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" xsi:schemaLocation="http://www.siemens.com/ad/mes/b2mt-1.0 C:\DATA_EXCHANGE\B2MT\B2MT_Schemas\AMG_ProductionSchedule.xsd">
  <xsl:template match="MSAPO01">
    <SyncProductionSchedule>
      <oag:ApplicationArea>
        <oag:Sender>
          <oag:LogicalId>
            <xsl:value-of select="LOGICALID"/>
          </oag:LogicalId>
          <oag:Component>
            <xsl:value-of select="COMPONENT"/>
          </oag:Component>
          <oag:Confirmation>
            <xsl:value-of select="CONFIRMATION"/>
          </oag:Confirmation>
        </oag:Sender>
        <oag:CreationDateTime>
          <xsl:value-of select="CREATIONDATE"/>
        </oag:CreationDateTime>
        <oag:BODId>
          <xsl:text>0000000000017092</xsl:text>
        </oag:BODId>
      </oag:ApplicationArea>
      <DataArea>
        <xsl:comment> WorkOrder  </xsl:comment>
        <oag:Sync>
          <xsl:attribute name="confirm">
            <xsl:value-of select="SYNC_CONFIRM"/>
          </xsl:attribute>
          <oag:SyncCriteria>
            <oag:SyncExpression>
              <xsl:attribute name="action">
                <xsl:value-of select="SYNC_ACTION"/>
              </xsl:attribute>
            </oag:SyncExpression>
          </oag:SyncCriteria>
        </oag:Sync>
        <xsl:apply-templates select="DATAAREA"/>
      </DataArea>
    </SyncProductionSchedule>
  </xsl:template>
  <xsl:template match="DATAAREA">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="DATAAREA/item">
    <bml:ProductionSchedule>
      <bml:ID>
        <xsl:text>Default</xsl:text>
      </bml:ID>
      <bml:ProductionRequest>
        <bml:ID>
          <xsl:value-of select="concat(VBELN,'/',POSNR)"/>
        </bml:ID>
        <bml:Any>
          <sit:ProductionRequestExtension>
            <sit:Quantity>
              <bml:QuantityString>
                <xsl:value-of select="NTGEW"/>
              </bml:QuantityString>
              <bml:DataType>
                <xsl:text>float</xsl:text>
              </bml:DataType>
              <bml:UnitOfMeasure>
                <xsl:value-of select="GEWEI"/>
              </bml:UnitOfMeasure>
            </sit:Quantity>
            <sit:ProducedQuantity>
              <xsl:value-of select="PROD_QTY"/>
            </sit:ProducedQuantity>
          </sit:ProductionRequestExtension>
          <amg:ProductionRequestExtension>
            <amg:SAPOrder>
              <amg:SAPOrderID>
                <xsl:value-of select="VBELN"/>
              </amg:SAPOrderID>
              <amg:SAPOrderItem>
                <xsl:value-of select="POSNR"/>
              </amg:SAPOrderItem>
              <amg:SAPStatusHead>
                <xsl:value-of select="STATUS_HEAD"/>
              </amg:SAPStatusHead>
              <amg:SoldTo>
                <xsl:value-of select="SOLDTO"/>
              </amg:SoldTo>
              <amg:SoldToName>
                <xsl:value-of select="NAME_SOLDTO"/>
              </amg:SoldToName>
              <amg:ShipTo>
                <xsl:value-of select="SHIPTO"/>
              </amg:ShipTo>
              <amg:Quality>
                <xsl:value-of select="QUALITY"/>
              </amg:Quality>
              <amg:DistributionChannel>
                <xsl:value-of select="INTEXP"/>
              </amg:DistributionChannel>
              <amg:DeliveryMode>
                <xsl:value-of select="DELIVERYMODE"/>
              </amg:DeliveryMode>
            </amg:SAPOrder>
          </amg:ProductionRequestExtension>
        </bml:Any>
      </bml:ProductionRequest>
    </bml:ProductionSchedule>
  </xsl:template>
</xsl:transform>

please help me with the dynamic part in XSLT file in order to get the following output, regardless of the number of properties. The XML output should look like this:
<?xml version="1.0" encoding="utf-8"?>
<!-- edited with XMLSpy v2011 rel. 3 sp1 (http://www.altova.com) -->
<SyncProductionSchedule xmlns="http://www.siemens.com/ad/mes/b2mt-1.0" xmlns:amg="Pelican@ArcelorMittalGalati" xmlns:bml="http://www.wbf.org/xml/b2mml-v02" xmlns:oag="http://www.openapplications.org/oagis" xmlns:sit="http://www.siemens.com/ad/mes/b2mml-v02-SITExt-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <oag:ApplicationArea>
        <oag:Sender>
            <oag:LogicalId>SAP-AMG</oag:LogicalId>
            <oag:Component>Whatever</oag:Component>
            <oag:Confirmation>Always</oag:Confirmation>
        </oag:Sender>
        <oag:CreationDateTime>2014-02-10T12:52:32</oag:CreationDateTime>
        <oag:BODId>0000000000017092</oag:BODId>
    </oag:ApplicationArea>
    <DataArea>
        <!-- WorkOrder  -->
        <oag:Sync confirm="Never">
            <oag:SyncCriteria>
                <oag:SyncExpression action="Change"/>
            </oag:SyncCriteria>
        </oag:Sync>
        <bml:ProductionSchedule>
            <bml:ID>Default</bml:ID>
            <bml:ProductionRequest>
                <bml:ID>0050023362/000001</bml:ID>
                <bml:Any>
                    <sit:ProductionRequestExtension>
                        <sit:Quantity>
                            <bml:QuantityString>22.520 </bml:QuantityString>
                            <bml:DataType>float</bml:DataType>
                            <bml:UnitOfMeasure>TO</bml:UnitOfMeasure>
                        </sit:Quantity>
                        <sit:ProducedQuantity>0.000 </sit:ProducedQuantity>
                    </sit:ProductionRequestExtension>
                    <amg:ProductionRequestExtension>
                        <amg:SAPOrder>
                            <amg:SAPOrderID>0050023362</amg:SAPOrderID>
                            <amg:SAPOrderItem>000001</amg:SAPOrderItem>
                            <amg:SAPStatusHead>Z00</amg:SAPStatusHead>
                            <amg:SoldTo>C001991</amg:SoldTo>
                            <amg:Quality>C</amg:Quality>
                            <amg:DistributionChannel>IN</amg:DistributionChannel>
                            <amg:DeliveryMode>Librex</amg:DeliveryMode>
                            <!-- New Node - OrderProperty -> Begin  -->
                            <amg:SAPOrderProperties>
                                <amg:OrderProperty>
                                    <amg:ID>ACTION</amg:ID>
                                    <amg:Description>Action code</amg:Description>
                                    <amg:Value>
                                        <amg:ValueString>007</amg:ValueString>
                                        <amg:DataType>CHAR</amg:DataType>
                                        <amg:UnitOfMeasure>n/a</amg:UnitOfMeasure>
                                        <amg:Any>002</amg:Any>
                                    </amg:Value>
                                </amg:OrderProperty>
                                <amg:OrderProperty>
                                    <amg:ID>AUGRU</amg:ID>
                                    <amg:Description>Order reason (reason for the business transaction)</amg:Description>
                                    <amg:Value>
                                        <amg:ValueString>01</amg:ValueString>
                                        <amg:DataType>CHAR</amg:DataType>
                                        <amg:UnitOfMeasure>n/a</amg:UnitOfMeasure>
                                        <amg:Any/>
                                    </amg:Value>
                                </amg:OrderProperty>
                                <amg:OrderProperty>
                                    <amg:ID>ZTERM</amg:ID>
                                    <amg:Description>Terms of payment key</amg:Description>
                                    <amg:Value>
                                        <amg:ValueString>0401</amg:ValueString>
                                        <amg:DataType>CHAR</amg:DataType>
                                        <amg:UnitOfMeasure>n/a</amg:UnitOfMeasure>
                                        <amg:Any/>
                                    </amg:Value>
                                </amg:OrderProperty>
                                <amg:OrderProperty>
                                    <amg:ID>QUALF</amg:ID>
                                    <amg:Description>IDOC qualifier reference document</amg:Description>
                                    <amg:Value>
                                        <amg:ValueString>001</amg:ValueString>
                                        <amg:DataType>CHAR</amg:DataType>
                                        <amg:UnitOfMeasure>n/a</amg:UnitOfMeasure>
                                        <amg:Any>Z022</amg:Any>
                                    </amg:Value>
                                </amg:OrderProperty>
                                <amg:OrderProperty>
                                    <amg:ID>QUALF</amg:ID>
                                    <amg:Description>IDOC qualifier reference document</amg:Description>
                                    <amg:Value>
                                        <amg:ValueString>001</amg:ValueString>
                                        <amg:DataType>CHAR</amg:DataType>
                                        <amg:UnitOfMeasure>n/a</amg:UnitOfMeasure>
                                        <amg:Any>Z023</amg:Any>
                                    </amg:Value>
                                </amg:OrderProperty>
                            </amg:SAPOrderProperties>
                            <!-- New Node - OrderProperty -> End -->
                        </amg:SAPOrder>
                    </amg:ProductionRequestExtension>
                </bml:Any>
            </bml:ProductionRequest>
        </bml:ProductionSchedule>
    </DataArea>
</SyncProductionSchedule>

A: This seems to be a straightforward extension of your existing stylesheet, you just need to add templates for PROPERTIES and ZPEL_PROPERTY_S
<xsl:template match="PROPERTIES">
  <amg:SAPOrderProperties>
    <xsl:apply-templates select="ZPEL_PROPERTY_S"/>
  </amg:SAPOrderProperties>
</xsl:template>

<xsl:template match="ZPEL_PROPERTY_S">
  <amg:OrderProperty>
    <amg:ID><xsl:value-of select="ID" /></amg:ID>
    <!-- etc. -->
  </amg:OrderProperty>
</xsl:template>

and apply these templates at the appropriate place
          <amg:DeliveryMode>
            <xsl:value-of select="DELIVERYMODE"/>
          </amg:DeliveryMode>
          <xsl:apply-templates select="PROPERTIES" />
        </amg:SAPOrder>


text:
Q: css borders with transparent background (when going from Sketch to HTML/CSS)

The first image is the sketch screenshot, it's a square with no background and a 1 px border with a solid 1px shadow. The second picture is my attempt to make this in html/css however it blocks my border, even if the background is transparent.
How can I make it look more like the first image?
code:

.box {
  width:100px;
  height:100px;
  border: 4px solid #191919;
  box-shadow: 4px 4px 0 0 rgba(137, 137, 137, 0.48);
}

A: Use pseudo element to create the second square:

.box {
  border: 4px solid #191919;
  width:100px;
  height:100px;
  position:relative;
}
.box:before {
  content:"";
  position:absolute;
  top:5px;
  left:5px;
  width:100px;
  height:100px;
  border: 4px solid rgba(137, 137, 137, 0.48);
  z-index:-1;
}

Or use drop-shadow filter like this:

.box {
  width: 100px;
  height: 100px;
  border: 4px solid #191919;
  filter: drop-shadow(10px 10px 0px rgba(137, 137, 137, 0.48));
}

Another idea with linear-gradient:

.box {
  width: 100px;
  height: 100px;
  background:linear-gradient(to right,#191919 4px,transparent 4px, transparent 86px,#191919 86px,#191919 90px,transparent 0) 0 0/100px 90px no-repeat,
  linear-gradient(to bottom,#191919 4px,transparent 4px, transparent 86px,#191919 86px,#191919 90px,transparent 0) 0 0/90px 100px no-repeat,
  linear-gradient(to right,rgba(137, 137, 137, 0.48) 4px,transparent 4px, transparent 86px,rgba(137, 137, 137, 0.48) 86px,rgba(137, 137, 137, 0.48) 90px,transparent 0) 10px 10px/100px 90px no-repeat,
  linear-gradient(to bottom,rgba(137, 137, 137, 0.48) 4px,transparent 4px, transparent 86px,rgba(137, 137, 137, 0.48) 86px,rgba(137, 137, 137, 0.48) 90px,transparent 0) 10px 10px/90px 100px no-repeat;
}


text:
Q: MVC2 - Running Application on II7 results in 403 forbidden I am trying to run our MVC2 application in IIS7 using an application pool that is targeting .net 4.0 and using the Integrated pipline. If I run my application using the dev webserver (Cassini iis 6) it will work. When I try to run the application using my local iis7 webserver I just get the HTTP Error: 403.14. I have read other posts claiming that setting runAllManagedModulesForAllRequests = true should fix the issue but it does not resolve the issue on this machine. Can anyone give me a suggestion?
Thanks!

A: Found the solution. This is a new machine. The following command fixed the issue.
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir


text:
Q: Django flatpages and images I'm interested in using the Flatpages app for my project but would also like a place (somewhere in the admin) to upload images that I want to reference on those flatpages.
Is there a way to do this without resorting to a CMS app?

A: simplest way is to upload images to a photo hosting (picasa, flickr etc). If you prefer to stick with django admin, you can write a simple app with a single model like this:
class Image(models.Model):
    title    = models.CharField(max_length=255)
    file    = ImageField(upload_to='car_images')

    def get_absolute_url(self):
        return (self.file and self.file.url) or ''


text:
Q: How do you find the point touching the tangent line on a unit circle? For a unit circle and a normalised vector representing the tangent (could be pointing in either direction), of which, would be touching the circle's perimeter, how do you find the point on the circle for it ?

A: For spheres the normal pointing outwards in a point $p$ on the boundary is given by the vector $p$. The tangent vectors are  orthogonal to the normal.
So in your case, finding the point where, given a tangent direction, the tangent can meet the circle is just a matter of rotating the direction by 90 degrees. However the question and this solution don't specify a unique such point, but rather two antipodal points. But this can be easily modified to result in a unique solution, at least for 2d spheres: We fix a vector field of tangent directions, say counterclockwise. Then rotating the tangent directions by 90 degrees in clockwise direction will give you normals pointing outwards, which are unique and give you the corresponding touching point.


text:
Q: Android: getting different file size on the same file I download the database file to Android storage. I am confused why the querying file size is different after opening the database. After downloading, it returns "size".After opening, it returns "size on disk".
    //download database file to storage
     ...(the content length from server is 52224)

    //query size
    databaseFile = new File(DBGlassConfig.getDatabasePath());
    long sizeBeforeLoading = databaseFile.length(); // 52224

    //open database
    if (databaseHandler == null)
        databaseHandler = new DatabaseHandler(MainActivity.this);

    //query size
    databaseFile = new File(DBGlassConfig.getDatabasePath());
    long sizeAfterLoading = databaseFile.length(); // 53248

//open database
public DatabaseHandler(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
            db =
SQLiteDatabase.openOrCreateDatabase(DBGlassConfig.getDatabasePath(), null);
            }


text:
Q: Windows 10 Backup - Delete old data backups automatically Good morning,
we have some computers that create a backup by week, in a external drive (since 2-3 months).
The problem is that Windows 10 isn't deleting old backups and drive is being full so fast. I want to know if it exists some way to do this task automatically, because now I am deleting old backups manually and I think that this task should be done in some easier way.
In the following example, I have backups from July 31, and all of the backups are 352,51 GB:
Image:

Kind regards, Iggy.


text:
Q: git thinks my Macbook pro is a Galaxy-S9 in the terminal See photo below.
I don't use a Galaxy-S9 nor do I know anyone who does...
Anyone know how this could have happened?

A: This is Visual Studio Terminal which is very similar to Ubuntu Terminal.
Basically, the syntax for the prefix in the terminal is:
USERNAME@DEVICE_NAME$
For example, mine is like this(where username is anupam and device name is g3):
anupam@g3:~$

So, you can edit these two parameters in your system and it will start showing you these parameters in the terminal.

A: You named your computer  "Galaxy-S9". You can change that in the settings of computer


text:
Q: Should I free global memory after GlobalRealloc? I just want to check whether I understood meaning of GlobalReAlloc function correctly. Shortly, GlobablRealloc changes size or memory object or its attributes. I have following questions:
 HGlobal old_mem = GlobalAlloc(...);
 HGlobal new_mem = GlobalReAlloc(12345, old_mem, 0); // Should I free old_mem?

*

*Should I free old memory object after reallocing? As I understood function just changes memory object itself and returns updated memory object. Please, correct me if I am wrong

*Should I free old memory object in the case of failed reallocation?

A: *

*No, if the function succeeded, the old memory is now invalid, the contents were copied to the newly allocated area, and you should use the new pointer from now on. So if the function succeed, do not free the old memory

*If the function fails, no changes were done. This means that the old pointer is still valid and you can use it. Now, if you want to free the old pointer, you can. Generally, the state of the program now is the same as before you called GlobalReAlloc.


text:
Q: Freeing programmatically modified UIImage throws exception I have programmed an image filter which generates a new UIImage from the old one pixel by pixel. In the class that contains my image the declaration is as follows:
@property   UIImage *imageHandle;       // contains the image of the class

My filter in my CBImage class extracts the bitmap as a char array (pixels) from the UIImage, allocates a new char array buffer (newPixels) with the same size and then runs through the RGBA pixels to reconstruct the filtered image in newPixels. Finally it generates a new UIImage and returns this.
This is the code (CBImage is my class which contains the declaration as above):
-(CBImage *)doMyFancyStuff
{
// set up some convenience variables
UIImage *image = self.imageHandle;
CGImageRef imageRef = image.CGImage;
NSData *imageData = (NSData *)CFBridgingRelease(CGDataProviderCopyData(CGImageGetDataProvider(imageRef)));
NSLog(@"NumPixels %d", [imageData length]);
char *pixels = (char *)[imageData bytes];

char *newPixels = (char *)calloc([imageData length], sizeof(char));

// run through the image and manipulate the image
for (NSInteger i=0; i< [imageData length]; i+=4)
{
    if ([whatEverIWantIsTrueForMyFilter])
    {
        // color pixel white and ALPHA = 1.0
        newPixels[i] = 255;
        newPixels[i+1] = 255;
        newPixels[i+2] = 255;
        newPixels[i+3] = 255;
    }
    else
        newPixels[i+3] = 0;  // make pixel translucent
}

// create new image
CBImage *result = [[CBImage alloc] init];

// construct new UImage
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
size_t bitsPerPixel = CGImageGetBitsPerPixel(imageRef);
size_t bytesPerRow = CGImageGetBytesPerRow(imageRef);

CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, newPixels, [imageData length], NULL);

CGImageRef newImageRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorspace, bitmapInfo, provider, NULL, FALSE, kCGRenderingIntentDefault);

result.imageHandle = [UIImage imageWithCGImage:newImageRef];

// clean up
free(pixels);
free(newPixels);
CGImageRelease(imageRef);
CGColorSpaceRelease(colorspace);
CGDataProviderRelease(provider);
CGImageRelease(newImageRef);
newImageRef = Nil;

return result;

}
All this seems to work nicely and I can display the newly created UImage in my view controller:
CBImage *overlayImage = [testCBImage doMyFancyStuff];
self.overlayView.image = overlayImage.imageHandle;

But...a BAD_ACCESS exception is thrown if I want to release the image again:
self.overlayView.image = Nil;

I don't know what's wrong here. The only suspicion I have is the calloc call in line #10 in my filter method above because I sort of "manually" allocate memory (although I release it again at the end of the method), which is then not referenced any more when the UIImage handle is set to Nil...but I'm not sure.
I am using iOS7 and ARC.
Any ideas?
Beschi

A: char *pixels = (char *)[imageData bytes];

And then, later on ...
free(pixels);

However, pixels was not created using a create / malloc / ... etc., and does not need to be released.
Also, consider having the property declared with retain (or strong, same stuff).
@property (nonatomic, retain)UIImage *imageHandle;       // contains the image of the class


text:
Q: Is version control (ie. Subversion) applicable in document tracking? I am in charge of about 100+ documents (word document, not source code) that needs revision by different people in my department. Currently all the documents are in a shared folder where they will retrieve, revise and save back into the folder.
What I am doing now is looking up the "date modified" in the shared folder, opened up recent modified documents and use the "Track Change" function in MS Word to apply the changes. I find this a bit tedious.
So will it be better and easier if I commit this in a version control database?
Basically I want to keep different version of a file.

What have I learn from answers:

*

*Use Time Machine to save different
version (or Shadow copy in Vista)

*There is a difference between text
and binary documents when you use
version control app. (I didn't know
that)

*Diff won't work on binary files

*A notification system (ie email) for revision is great

*Google Docs revision feature.
Update :
I played around with Google Docs revision feature and feel that it is almost right for me. Just a bit annoyed with the too frequent versioning (autosaving).
But what feels right for me doesn't mean it feels right for my dept. Will they be okay with saving all these documents with Google?

A: I've worked with Word documents in SVN. With TortoiseSVN, you can easily diff Word documents (between working copy and repository, or between two repository revisions). It's really slick and definitely recommended.
The other thing to do if you're using Word documents in SVN is to add the svn:needs-lock property to the Word documents. This will prevent two people from trying to edit the same document at the same time, since unfortunately there's no good way to merge Word documents.
With the above two things, handling revision controlled Word documents is at least tolerable. It certainly beats the alternative of using a shared folder and track-changes.

A: Sharepoint also does a good (ok decent) job of versioning MS-specific documents.

A: How about trying git , It seems git can support word .doc and open document .odf files if you configure it in .gitattributes file.
Here is a reference , Scroll down to diffing binary files .

A: For what it's worth, there is also Google Docs. I guess it's not a perfect fit, but it's versioning is very convenient.

A: What on Earth are you all Word-is-binary-so-no-diff people talking about? TortoiseSVN, for example, integrates right out of the box with Word and enables you to use Word's built-in diff and merge functionality. It works just fine.
I have worked on projects that store documents in version control. It has worked out pretty well, although if people are unfamiliar with version control, they are probably going to have conceptual difficulties with things like "working copy" and "merge" and "conflict". Don't overestimate the users' capabilities when you plan your document management system.
I believe there exist big and powerful commercial solutions for all of this, as well. I'm sure if you have enough kilodollars, you can get something that fits your needs perfectly. Document management systems are a big business for big enterprise.

A: Clearcase integrates with Word for revision tracking. I believe Telelogic DOORs does as well.

A: I use Mercurial with the TortoiseHg overlay. I can right-click a changeset, choose "Visual Diff", then choose the "docdiff" tool (comes bundled), which launches the document in Word with the Track Changes.

A: I guess one thing that nobody seems to have asked is if you have a legal requirement to store history of changes to the doc's?
Whether you do or don't is going to have an impact on what solutions you can consider.
Also a notification mechanism for out of date copies is also a bundle of fun. If engineer A has a copy of a document and engineer B then edits it and commits the changes you want engineer A to be notified that his copy is out of date.
Document control can become a real can of worms quite easily.
Maybe keep the doc's under CVS or SVN and set it up so that emails are generated to whoever has checked out a copy when updates for the same doc. are checked in to the repository?
Edit: I forgot to add don't forget to use the binary switch, e.g. -kb for CVS, when adding the new doc. Otherwise, you will get any sequences of data that happen to match the ascii for keyword strings having the relevant config management data appended thereby corrupting your doc. data.

A: Thinking out of the box, would migrating to a Wiki be out of the question?
Since you consider it feasible to force your users into Subversion (or something similar), a larger change seem acceptable.
Another migration target could be to use some kind of structured XML document format (DocBook comes to mind). This would enable you to indeed use diffs and source control, while getting all sorts of document formats for free.

A: You can, but you will allways compare the document versions with Word itself.
I haven't heard a version control database which can track changes in Word documents.
However there are some tools which can compare Word documents, so if you set up your version control client to use these tools for comparison, you can have some fun.

A: Not necessarily. It depends on how often the new files are committed to the repo. If the files are edited several times before a commit, then you're precisely where you are now. The biggest benefit is if the file becomes corrupted.
You can version any file; this is how Time Machine in Mac OS X Leopard works, for example, and there is an interesting article by someone who committed his entire computing environment into CVS and then just maintained working copies on his home and work machines.
But "better" and "easier" are specific to your situation, and I'm not sure I completely understand your problem as things stand.

A: Subversion, CVS and all other source control systems are not good for Word documents and other office files (such as Excel spread sheets), since the files themselves are stored in a binary format. That means that you can never go back and annotate (or blame, or whatever you want to call it), or do diffs between documents.
There are revision control systems for Word documents out there, unfortunately I do not know any good ones. We use such control systems for Excel at my work, and unfortunately they all cost money.
The good thing is that they make life a lot easier, especially if you ever have to do an audit or due diligence.

A: If you use WinMerge it has added support for merging Word and Excel binary files.

A: Have a look at Sharepoint. If cost is an issue, Sharepoint portal sevices can also work for you. Read this for more info

A: Just wanted to clarify an answer someone gave but I don't have enough points yet.
diff will work on binary files but it is only going to say something not really useful like "toto1 and toto2 binary files differ".

A: You could use something like the Revisionator, which is like google docs but with built in revision control including diffs, forks, and 3 way merges. http://revisionator.com
UPDATE: It also fixes the problem of too frequent autosaving that you mention with Google Docs. It'll still autosave to prevent data loss, but it will only create a new version in the revision history and share with other users when you explicitly "release" your changes.

A: You could do that, but if that files are binary you should always put a lock on it before editing. You won't get a conflict (which would be unresolvable).

A: Many of the new version control projects are better suited to entire directories, and not so much for single files.
Convincing someone that they need to get an entire project, when they only want to update an individual file can be a "fun" way to spend an afternoon.

A: Another option you have is a piece of software and cloud computing magic called dropbox. Or, you could ditch the word documents and make a locally shared mediawiki instead.
DropBox:
getdropbox DOT com
MediaWiki:
mediawiki DOT org

A: YES, it's applicable! I totally agree to say that the combo SVN+TortoiseSVN suits well to track MS Office documents. You can lock a document for edition, write protect all unlocked files to avoid conflicts (i.e. parallel modifications), diff two versions of the same file, see the history of all the modifications and of course rollback to an older revision.
I tried to describe all of those tips in a dedicated blog post. (disclaimer: I'm the blog owner)
All of this could even be accessible from the web with a SVN web client! (might need some software development)
But if you're not accustomed to Version Control Systems in an other context this may not be the obvious choice. The needed work for a good integration with docs give dedicated tools an advantage: "electronic document management" systems are made just for that. A VCS like SVN may stay a good alternative for cost reasons :-)
Did you test the online service Simul? It looks promising, I personally like the GitHub-like orientation. Note that I'm not affiliated to Simul!


text:
Q: Generic sections of non-null sets are non-null Consider the Cantor space $\mathcal C={}^\omega2$ with the usual product measure, and let $r$ be a random real (over a transitive model $V$ of ZFC). Let $B\subset \mathcal C^V\times\mathcal C^V$ a Borel set of positive measure in $V$ and let $B^{V[r]}$ the Borel set in $\mathcal C^{V[r]}\times \mathcal C^{V[r]}$ with the same Borel code as $B$.
Is the section $B^{V[r]}_r=\{y\in\mathcal C^{V[r]}:(r,y)\in B^{V[r]}\}$ non-null?
I know that the set $C=\{x\in\mathcal C^V : m(B_x)>0\}$ is non-null, by Fubini's theorem, and also, by randomness, $r\in C^{V[r]}$. The answer is yes if $C^{V[r]}=\{x\in\mathcal C^{V[r]}: m(B^{V[r]}_x)>0\}$, but I do not know how this could be justified.

A: No, let  $(r,y)\in B $ iff $r (0)=0$.
Then if  $r $ is a random real with  $r (0)=1$ you have a counterexample.


text:
Q: Different types of octahedral dice How many types of octahedral  dice exist?
We know that cubic dice have two types: one where the 1,2 and 3 are placed clockwise relatively to their common vertex and one where they are placed counterclockwise, given that the sum of the values between opposite faces is constant and equal to 7.
In an octahedral die the sum of opposite faces is 9. My answer is that there are 16 different types of octahedral dice, here are the steps I took:
-Take the triangle with the value of 1 as a reference: it has a side in common with 3 of the other 7 triangles, and only a vertex with other 3. The remaining face contains the 8.
-Placing the number 2 (and the 7, consequentially) we have 2 choices: letting it have an edge in common with the 1 or not.
-Now we allign the solid with the 7 under the 1 and the 2 over it. The 3 can be placed in one of the 4 spots remaining and the combination can be determined with no ambiguity or repetitions, so 4 different placements.
-We have then only 2 combinations for the placement of the 4 and the 5
The total combinations are then 2x4x2=16, is it right?

A: If we drop the constraint about opposite faces having fixed sum, we arrive at a different answer: A priori, there are $8!$ ways to label eight faces with eight numbers. But some of these labellings are "the same" in that a rotation of the octahedron turns one into the other. In fact, if the number of possible rotations is $n$, then there are always sets of $n$ labellings that we identify, and the number of actually different labellings is $\frac{8!}n$.
So what is $n$? We can always rotate the octahedron in such a way that an arbitrary of the $8$ faces is at the bottom. After that, we can rotate in $3$ ways (in steps of $120^\circ$) while fixing that bottom face. Hence $n=8\cdot 3=24$ and there are $\frac{8!}{24}=1680$ ways (or $840$ if we additionally consider reflections as symmetry).

A: We can also solve this using burnside's lemma. Since all the faces have distinct numbers, the formula is greatly simplified and easily intuitive.
Let's first solve the case of the 6 sided die. It is well known that there are $24$ elements of the rotation group on a cube (this is also non-coincidentally the same number as that for an octahedron). I.e. if we rotate a painted cube so that it is in the same orientation (but its faces do not necessarily have to be in the same position), then there are $24$ different orderings of the distinct faces.
Now we must find how many ways there are to place the numbers on the cubical die without considering indistinguishability from rotation. We will take a constructive approach.
There are $6$ places to put the 1-face. The position of the 6-face will then be decided. There are then $4$ places left for the 2-face, which will also decide the position of the 5-face. There are $2$ places left for the 3-face, which also decides the 4-face. Hence, there are $6!!=6\cdot 4\cdot 2=48$ ways to place the numbers on the die. It follows that there are $(2n)!!$ ways to place the numbers on a die with $2n$ faces.
By burnside's lemma, we have that the total number of possible valid dice when rotations are considered distinct is
$$\frac{6!!}{24}$$
$$\frac{48}{24}$$
$$\boxed{2}$$
Going back to the octahedron problem. We again have that there are $24$ elements in the rotation group. However, there are $8!!$ ways to place the numbers disregarding indistinguishability from rotation.
Hence, by burnside's lemma, the number of possible valid octahedral die when rotations are considered distinct is
$$\frac{8!!}{24}$$
$$\frac{8\cdot 48}{24}$$
$$\boxed{16}$$
P.S. while this may seem like a long approach, most of the text here was exposition to burnside's lemma. If you are already comfortable with burnside's lemma, this will be a quick, surefire method that can be easily extended to other types of dice.


text:
Q: JsonConvert.DeserializeObject error mvc asp.net newtonjson I use HttpRequestMessage my model is some different VirtualStock. My API JSON model as below
[{
        "_id": "5f2d66ae6abb1d6870e926ac",
        "MessageId": "EAD8B97887FFC1F180F3005056BF2302",
        "MessageType": "CreateDiscount",
        "RequestedBy": "AAA",
        "RequestedDate": "2020-08-07T17:22:58.000Z",
        "Data": {
            "_id": "5f2d66ae6abb1d6870e926ad",
            "Sku": "A",
            "SkuId": "EAD8B97887FFC0F180F3005056BF2302",
            "Price": 1759.17,
            "PurchasePrice": 1768.88,
            "StartDateTime": "2020-08-07T17:24:34.000Z",
            "EndDateTime": "2020-09-01T00:00:00.000Z",
            "VirtualStock": "1000",
            "MaximumQuantityForCart": 10,
            "CurrencyCode": "949"
        },
        "__v": 0
    },
    {
        "_id": "5f2d65daf7168b686d9474b9",
        "MessageId": "EAD8B8F92D90CDF180F3005056BF2302",
        "MessageType": "UpdateDiscount",
        "RequestedBy": "AAA",
        "RequestedDate": "2020-08-07T17:19:26.000Z",
        "Data": {
            "_id": "5f2d65daf7168b686d9474c5",
            "Sku": "A",
            "SkuId": "EAD8B8F92D90C5F180F3005056BF2302",
            "DiscountId": "8c3975a0-ea85-48e9-9c31-ea488bdad5c4",
            "Price": 296.2,
            "PurchasePrice": 239.91,
            "StartDateTime": "2020-08-01T14:35:00.000Z",
            "EndDateTime": "2020-08-07T17:23:08.000Z",
            "VirtualStock": {
                "Value": "100",
                "IsAssigned": true
            },
            "MaximumQuantityForCart": 25,
            "CurrencyCode": "949"
        },
        "__v": 0
    }
]

I defined my model VirtualStock like object and nullable.
public object? VirtualStock { get; set; }

but I get error parsing how can fix this?
I saw with debug Deserialize Success but showing JSON GetDiscount method I have exceptions
controller code as below
public IActionResult Discount()
{
    return View();
}
public async Task<IActionResult> GetDiscount()
{
    return Json(new { data = await _log.GetAllAsync("http://0.0.0.0/DiscountLog?pagesize=9&page=16") });
}

my Repository
public async Task<IEnumerable<T>> GetAllAsync(string url)
{
    var request = new HttpRequestMessage(HttpMethod.Get, url);

    var client = _clientFactory.CreateClient();

    HttpResponseMessage response = await client.SendAsync(request);
    if (response.StatusCode == System.Net.HttpStatusCode.OK)
    {
        var jsonString = await response.Content.ReadAsStringAsync();

        var jsonSerializerSettings = new JsonSerializerSettings()
        {
            NullValueHandling = NullValueHandling.Ignore,
            MissingMemberHandling = MissingMemberHandling.Ignore
        };

        return JsonConvert.DeserializeObject<IEnumerable<T>>(jsonString,jsonSerializerSettings);
    }

    return null;
}

My error:

An unhandled exception occurred while processing the request.
NotSupportedException: The collection type 'System.Object' on
'RetailLogWeb.Models.LogItem.VirtualStock' is not supported.
System.Text.Json.JsonPropertyInfoNotNullable<TClass,
TDeclaredProperty, TRuntimeProperty,
TConverter>.GetDictionaryKeyAndValueFromGenericDictionary(ref
WriteStackFrame writeStackFrame, out string key, out object value)
NotSupportedException: The collection type 'System.Object' on
'RetailLogWeb.Models.LogItem.VirtualStock' is not supported.
System.Text.Json.JsonPropertyInfoNotNullable<TClass,
TDeclaredProperty, TRuntimeProperty,
TConverter>.GetDictionaryKeyAndValueFromGenericDictionary(ref
WriteStackFrame writeStackFrame, out string key, out object value)
System.Text.Json.JsonPropertyInfo.GetDictionaryKeyAndValue(ref
WriteStackFrame writeStackFrame, out string key, out object value)
System.Text.Json.JsonSerializer.HandleDictionary(JsonClassInfo
elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter
writer, ref WriteStack state)
System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, int
originalWriterDepth, int flushThreshold, JsonSerializerOptions
options, ref WriteStack state)
System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, object
value, Type inputType, JsonSerializerOptions options,
CancellationToken cancellationToken)
Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext
context, JsonResult result)
Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext
context, JsonResult result)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0<TFilter,
TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next,
Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed
context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter,
TFilterAsync>(ref State next, ref Scope scope, ref object state, ref
bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, object state, bool
isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed
context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State
next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, object state, bool
isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker
invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint
endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext
context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext
context)

A: OP figured it out as shared in the comments, but I'll provide an answer here just to close out the question.  As explained in this answer, the solution was to add a variant of this line:
services.AddControllers().AddNewtonsoftJson();

This was needed because Newtonsoft.Json was removed during a recent upgrade to .NET Core, and this adds it back in.  Note that this assumes you have the Microsoft.AspNetCore.Mvc.NewtonsoftJson package installed.
More info here.


text:
Q: How did it get from line 1 to line 2 to line 3 (Vector Cross Product)
How does it get from line 1 to line 2
can someone explain it in verybbasic terms
Thanks

A: The second $=$ expands the cross-product; like ordinary multiplication, it's linear in both arguments. The last $=$ uses antisymmetry $u\times v=-v\times u$, including the "diagonal" special case $u=v=a$, giving$$a\times a=-a\times a\implies 2a\times a=0\implies a\times a=0.$$

A: Remember that for any vectors $u,v$, we have $u \times v = -v \times u$ and $v \times v = 0$. So,
$$
b \times c - a \times c - b \times a + a \times a =\\
b \times c - -(c \times a)  --(a \times b) + 0 =\\
b \times c + c \times a + a \times b.
$$


text:
Q: select from to view image php i would like to know what is wrong with my code i cant see the images from DB. i have looked all over the web for answers and they seem to be all old code i tried using PDO but for some reason i cant get that to work can someone please help me figure out what is wrong with my code?

include('configur.php');

$tbl_name="shirt_table";

$email=$_SESSION['email'];

 $query="SELECT * FROM $tbl_name WHERE email='$email'";
 $result=mysqli_query($link, $query);

// If successfully queried
 if($result){

// Count how many row has this passkey
 $count=mysqli_num_rows($result);

// if found this passkey in our database, retrieve data from table "first_table"
 if($count==1){

 $rows=mysqli_fetch_array($result);

  $images3=$rows['images3'];

 }}

<img src="http://torcdesign.com/shirtimgs/<?php echo $images3 ?>" width="490" height="500" alt="no image found"/>


text:
Q: How to clean HP6715 laptop? hp6715 series - I need to open it and clean it, and by the looks of it, it doesn't seem to be that simple of a job.
I searched through hp's pages, but couldn't find any manual that describes the process. Is there something I missed ? Anyone here knows of a manual that describes the disassembling the aforementioned ?
Any general tips on disassembling laptops ?
(fan cleaning is my priority for now)

A: All laptop companies issue a service manual for each model which includes full disassembly details. This is the manual used by hardware technicians working with the laptop. This is distinct from the user manual, which is what the user gets, and which is a lot less technical in nature.
I've searched for and found the service manual for my laptops online, but not without going to some trouble. If you're lucky, you might find a site that gives you the service manual for free, else you might have to shell out a small fee.
If you can find the service manual for your model, that would be the preferred way as you'll be following the HP-approved way to open up the laptop.
If you can't find the exact service manual you need, do a bit of research on these:

*

*The same laptop often has a completely different name in a different market. I couldn't find the service manual for my Acer Travelmate model sold in UK/Europe, but the same laptop is marketed in the US under a different line, and I found the service manual for that.

*A number of laptops of the same family have the same shell/body, and consequently the same instructions to open them up. If you can find other HP laptops belonging to the same family as yours, search for their service manuals.

If you can't find anything at all to help you, play it by ear and be careful when you open up the laptop. Make sure you have the right tools.

A: Service and maintenance manual for the 6710 and 6715 is two-thirds of the way down on:
http://h20000.www2.hp.com/bizsupport/TechSupport/DocumentIndex.jsp?contentType=SupportManual&lang=en&cc=us&docIndexId=64179&taskId=101&prodTypeId=321957&prodSeriesId=3368540

A: As always VideoJug has come great general advice video on how to clean a laptop.  But I couldn't find anything specific for your laptop.


text:
Q: Gatsby, problem with using SCSS Modules, css works normally but SCSS don't I have a problem with CSS modules in Gatsby. Everything was working just fine until I had changed the file format of modules from CSS to scss. Of course, I have a sass plugin installed. The weirdest part is that the global style file works normally as scss without any problems. After changing the file format of modules from CSS to scss I'm getting this error in the terminal:
ERROR #98123 WEBPACK

Generating development JavaScript bundle failed

Mini CSS Extract Plugin Loader Invalid Options

options.modules should be object

File: src/components/modules/footer.module.scss

failed Re-building development bundle - 0.477s

Footer component code:
import React from "react";
import { Link } from "gatsby";
import * as style from "../components/modules/footer.module.scss";

const Footer = (props) => {
  return (

Learn

        <Link>HOW</Link>

Contact

Privacy Policy

Terms of use

follow us

  );
};

    export default Footer;

Code from the module:
.feature {
  color: blue;
}

gatsby-config.js:
module.exports = {plugins: ["gatsby-plugin-react-helmet", `gatsby-plugin-sass`],};

Do you guys know what is the reason behind this error? I'm just guessing that it is something with project configuration, some problem with node, webpack, etc. but I've no idea what it is particularly. I've created a new project to test CSS modules and on the new project, it's working properly.


text:
Q: how to remove characters from end of the NSString till "/" I have a string like this @"Root/dbo-NewsLocation/Item 1/dbo-Relator-test/Item 1/Item 1"
When user taps on back button I need to remove @"/Item1" at the end of above string.
I am not able to remove @"Item1" If I do the stringByReplacingOccuranceOfString by using below code it remove all @"Item1" using the below code.
NSString *str1=self.lblCIPath.text;
        NSRange range = [str1 rangeOfString:@"/" options: NSBackwardsSearch];
        NSString *newString = [str1 substringFromIndex:(range.location)];
        self.lblCIPath.text=[self.lblCIPath.text stringByReplacingOccurrencesOfString:newString withString:@""];

I will be thankful if anyone can suggest me the way to delete the last componentPath from NSString.

A: Have you tried the method stringByDeletingLastPathComponent ?
NSString *updatedPath = [myFullPath stringByDeletingLastPathComponent];

A: As Mathieu Meylan suggested you can use stringByDeletingLastPathComponent, or you can simply adjust your code to use substringToIndex instead of substrinFromIndex as follows:
NSString *str1=self.lblCIPath.text;
NSRange range = [str1 rangeOfString:@"/" options: NSBackwardsSearch];
NSString *newString = [str1 substringToIndex:(range.location)];

Final result will be the same:
Root/dbo-NewsLocation/Item 1/dbo-Relator-test/Item 1


text:
Q: Find (Based on string name), Select, Copy & Paste I can't seem to figure out how to construct a vba code that searches across cells "A10000:XFD10000" for a string named "Apple" and copies that range until cells "A1:A10000" and pastes it into another tab within the same sheet called "Validation" in row "A".
Macro below
Sub Get_Date()

    Dim Partname As String
    Dim sh As Worksheet
    Dim ws As Worksheet

    Set sh = Sheets("Tests")
    Set ws = Sheets("Part Catalog")
    Partname = ActiveCell.Value

    ws.Cells.Find(Partname).Offset(0, 1).Copy
    sh.Cells.Find(Partname).Offset(0, 1).Paste
End Sub


text:
Q: change size of electron (Atom Shell) WindowBrowser from command line or external program I want to control the window size of an electron (atom-shell) WindowBrowser object from an external program. I know within the electron app code I can use the WindowBrowser.SetSize(w, h) method, but I need events in a different (non-electron) program to trigger this behavior. Is there a good way to do this? If Electron cannot do this, is there another desktop application framework or method that could accommodate this?
Currently, my hope is to set the WindowBrowser ID in a file, then read that file from the external program and send a command line string that tells the electron app to SetSize of the WindowBrowser referenced using its ID. I am totally new to Electron, and I have no idea if this will work or how to do it.


text:
Q: Скрыть определенное количество элементов из блока Хочу, чтобы при максимальном разрешении экрана 1140px со страницы скрывались, например, 2 последних элемента из блока. Возможно ли это сделать не присваивая каждому элементу отдельный класс?

* {
  box-sizing: border-box;
}
.block {
  max-width: 1140px;
  margin: auto;
}
.block-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.block-item {
  width: 165px;
  height: 165px;
  background-color: black;
  margin: 30px;
}

@media (max-width: 1140px) {

}

A: Eсть псевдокласс :nth-last-child (https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child)
Вот как будет выглядеть в вашем случае:

* {
  box-sizing: border-box;
}
.block {
  max-width: 1140px;
  margin: auto;
}
.block-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.block-item {
  width: 165px;
  height: 165px;
  background-color: black;
  margin: 30px;
  color: #fff;
}

@media (max-width: 1140px) {
  .block-item:nth-last-child(1), .block-item:nth-last-child(2) {
    display: none;
  }
}

1

2

3

4

5

6

7

8

9

10


text:
Q: Finding a document with a specific term on an array I'm trying to find a document containing a specific term in an array of strings.
I have a schema like this:
{
  "pages": {
    "mappings":{
      "site":{
        "properties":{
          "urls":{"type":"string"}
        }
      }
    }
  }
}

And the following data indexed on it:
% curl -XPOST 'http://local.dev:9200/pages/site/_search?pretty
{
  ...
  "hits" : {
    "total" : 1,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "pages",
      "_type" : "site",
      "_id" : "ae634fea-878f-42ca-8239-c67cca007a38",
      "_score" : 1.0,
      "_source":{ "urls":["https://github.com/fulano","http://fulano.com"] }
    }
  }

I'm trying to search for sites whose urls array contains a specific url, but I can't make it work. I tried using terms - exactly as described here but I never get any results:
% curl -XPOST 'http://local.dev:9200/pages/site/_search?pretty' -d '
{
  "query": {
    "filtered": {
        "filter": {
            "term": { "urls": "https://github.com/fulano" }
        }
    }
  }
}'
{
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}

Using terms (that gets expanded into a series of bool operations by elastic):
% curl -XPOST 'http://local.dev:9200/pages/site/_search?pretty' -d '
{
  "query": {
    "terms" : {
        "urls" : ["https://github.com/fulano"]
    }
  }
}'
{
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}

I'm guessing this is something really silly, but I can't spot the problem. :(

A: This is the problem with the analyzer you are using. You need to use not_analyzed or keyword tokenizer as outlined here.


text:
Q: rsyslog server template consideration for multiple remote hosts Linux Destro is : Centos 6.8
Below is what the rsyslog.conf looks like:
# cat /etc/rsyslog.conf

$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imklog   # provides kernel logging support (previously done by rklogd)
#$ModLoad immark  # provides --MARK-- message capability
# Provides UDP syslog reception
$ModLoad imudp
$UDPServerRun 514
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
$template server-dc, "/scratch/rsyslog/%HOSTNAME%/messages.log"
authpriv.*   ?server-dc
*.info,mail.none,authpriv.none,cron.none   ?server-dc
$IncludeConfig /etc/rsyslog.d/*.conf

#*.info;mail.none;authpriv.none;cron.none                /var/log/messages
#*.*                                                     @elk-rsyslog:514

Point for me to understand:
1)
$template server-dc, "/scratch/rsyslog/%HOSTNAME%/messages.log"
enter code here

So, in the above line /scratch/rsyslog is a Directory path on the rsyslog server where we are forwarding all the logs from the unix remote hosts which crearts a directory structure following a message file like:

/scratch/rsyslog/remot1-Ser1/messages.log
/scratch/rsyslog/remot1-Ser2/messages.log

So, this works okay, However at the same time we have few network devices as well which are forwarding the network logs into the same location in a below format:

/scratch/rsyslog/Sep/messages.log
/scratch/rsyslog/Oct/messages.log

In the above case of network logs its creating a Directory by month name following a message file So, I'm looking for a way in rsyslog to define a different path for network logs as such /scratch/rsyslog/network so the network logs can be collected into a Separate Folder, reason behind this is, i'm  processing these logs to Elasticsearch hence  i'm using wildcard for unix logs as /scratch/rsyslog/*/messages.log but this also includes the network logs being wildcard(*) called.
So, Is there a way i can say if the logs are coming from particular remote host or IP should go to a particular Folder in rsyslog server?
2) Here in $template server-dc, "/scratch/rsyslog/%HOSTNAME%/messages.log"  what is login for putting  server-dc as this is a another Hostname, Is this gets any purpose or we can change this to something relevant considering above requirement.
3) Same  server-dc also been included into another config parameters as well.
Desired
Would simply like to know if there is way i can Forward the logs for like systems , network, firewall into the separate distinct Directories like..
1 - /scratch/rsyslog/system/%HOSTNAME%/messages.log
2 -   /scratch/rsyslog/network/%HOSTNAME%/messages.log
3 -   /scratch/rsyslog/firewall/%HOSTNAME%/messages.log

A: You can have any number of templates, and test incoming messages for their hostname or ip address. If your hostnames are well-structured, for example all "systems" start with "sys" such as sys10 and sysabc, then the number of tests can be reduced.
For example,
$template mysystems,"/scratch/rsyslog/system/%HOSTNAME%/messages.log"
$template mynets,"/scratch/rsyslog/network/%HOSTNAME%/messages.log"
$template myfirewalls,"/scratch/rsyslog/firewall/%HOSTNAME%/messages.log"

if $fromhost startswith "sys" then -?mysystems
& stop
if $fromhost startswith "net" then -?mynets
& stop
if $fromhost startswith "fw" then -?myfirewalls
& stop

The & stop line stops the message that matches the previous line from being treated further.
You can test the ip address with, for example,
if $fromhost-ip startswith "192.168." then -?mynets

If you want to keep the *.info,... filter, you can modify the above, for example,
if $fromhost startswith "sys" then {
  *.info,mail.none,authpriv.none,cron.none   -?mysystems
  & stop
}

Note, however, that if you want to not log some items, you should really do this filtering at the sender, not at this end of the network. It is just wasting network bandwidth to send messages that you then filter out and throw away.
See the extensive rsyslog documentation, noting which version you have.


text:
Q: How do I position an image correctly in MTKView? I am trying to implement an image editing view using MTKView and Core Image filters and have the basics working and can see the filter applied in realtime.  However the image is not positioned correctly in the view - can someone point me in the right direction for what needs to be done to get the image to render correctly in the view.  It needs to fit the view and retain its original aspect ratio.
Here is the metal draw function - and the empty drawableSizeWillChange!? - go figure.  its probably also worth mentioning that the MTKView is a subview of another view in a ScrollView and can be resized by the user.  It's not clear to me how Metals handles resizing the view but it seems that doesn't come for free.
I am also trying to call the draw() function from a background thread and this appears to sort of work.  I can see the filter effects as they are applied to the image using a slider.  As I understand it this should be possible.
It also seems that the coordinate space for rendering is in the images coordinate space - so if the image is smaller than the MTKView then to position the image in the centre the X and Y coordinates will be negative.
When the view is resized then everything gets crazy with the image suddenly becoming way too big and parts of the background not being cleared.
Also when resting the view the image gets stretched rather than redrawing smoothly.
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {

}

public func draw(in view: MTKView) {
    if let ciImage = self.ciImage  {
        if let currentDrawable = view.currentDrawable {              // 1
            let commandBuffer = commandQueue.makeCommandBuffer()

            let inputImage = ciImage     // 2
            exposureFilter.setValue(inputImage, forKey: kCIInputImageKey)
            exposureFilter.setValue(ev, forKey: kCIInputEVKey)

            context.render(exposureFilter.outputImage!,
                           to: currentDrawable.texture,
                           commandBuffer: commandBuffer,
                           bounds: CGRect(origin: .zero, size: view.drawableSize),
                           colorSpace: colorSpace)

            commandBuffer?.present(currentDrawable)
            commandBuffer?.commit()
        }
    }
}

As you can see the image is on the bottom left

A: let scaleFilter = CIFilter(name: "CILanczosScaleTransform")

That should help you out. The issue is that your CIImage, wherever it might come from, is not the same size as the view you are rendering it in.
So what you could opt to do is calculate the scale, and apply it as a filter:
    let scaleFilter = CIFilter(name: "CILanczosScaleTransform")
    scaleFilter?.setValue(ciImage, forKey: kCIInputImageKey)
    scaleFilter?.setValue(scale, forKey: kCIInputScaleKey)

This resolves your scale issue; I currently do not know what the most efficient approach would be to actually reposition the image
Further reference: https://nshipster.com/image-resizing/

A: The problem is your call to context.render — you are calling render with bounds: origin .zero. That's the lower left.
Placing the drawing in the correct spot is up to you. You need to work out where the right bounds origin should be, based on the image dimensions and your drawable size, and render there. If the size is wrong, you also need to apply a scale transform first.

A: Thanks to Tristan Hume's MetalTest2 I now have it working nicely in two synchronised scrollViews.  The basics are in the subclass below - the renderer and shaders can be found at Tristan's MetalTest2 project. This class is managed by a viewController and is a subview of the scrollView's documentView.  See image of the final result.
//
//  MetalLayerView.swift
//  MetalTest2
//
//  Created by Tristan Hume on 2019-06-19.
//  Copyright © 2019 Tristan Hume. All rights reserved.
//

import Cocoa

// Thanks to https://stackoverflow.com/questions/45375548/resizing-mtkview-scales-old-content-before-redraw
// for the recipe behind this, although I had to add presentsWithTransaction and the wait to make it glitch-free
class ImageMetalView: NSView, CALayerDelegate {
    var renderer : Renderer
    var metalLayer : CAMetalLayer!
    var commandQueue: MTLCommandQueue!
    var sourceTexture: MTLTexture!
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    var context: CIContext!
    var ciMgr: CIManager?
    var showEdits: Bool = false

    var ciImage: CIImage? {
        didSet {
            self.metalLayer.setNeedsDisplay()
        }
    }
    @objc dynamic var fileUrl: URL? {
        didSet {
            if let url = fileUrl {
                self.ciImage = CIImage(contentsOf: url)
            }
        }
    }

    /// Bind to this property from the viewController to receive notifications of changes to CI filter parameters
    @objc dynamic var adjustmentsChanged: Bool = false {
        didSet {
            self.metalLayer.setNeedsDisplay()
        }
    }

    override init(frame: NSRect) {
        let _device = MTLCreateSystemDefaultDevice()!
        renderer = Renderer(pixelFormat: .bgra8Unorm, device: _device)
        self.commandQueue = _device.makeCommandQueue()
        self.context = CIContext()
        self.ciMgr = CIManager(context: self.context)
        super.init(frame: frame)

        self.wantsLayer = true
        self.layerContentsRedrawPolicy = .duringViewResize

        // This property only matters in the case of a rendering glitch, which shouldn't happen anymore
        // The .topLeft version makes glitches less noticeable for normal UIs,
        // while .scaleAxesIndependently matches what MTKView does and makes them very noticeable
        //        self.layerContentsPlacement = .topLeft
        self.layerContentsPlacement = .scaleAxesIndependently

    }

    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func makeBackingLayer() -> CALayer {
        metalLayer = CAMetalLayer()
        metalLayer.pixelFormat = .bgra8Unorm
        metalLayer.device = renderer.device
        metalLayer.delegate = self

        // If you're using the strategy of .topLeft placement and not presenting with transaction
        // to just make the glitches less visible instead of eliminating them, it can help to make
        // the background color the same as the background of your app, so the glitch artifacts
        // (solid color bands at the edge of the window) are less visible.
        //        metalLayer.backgroundColor = CGColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)

        metalLayer.allowsNextDrawableTimeout = false

        // these properties are crucial to resizing working
        metalLayer.autoresizingMask = CAAutoresizingMask(arrayLiteral: [.layerHeightSizable, .layerWidthSizable])
        metalLayer.needsDisplayOnBoundsChange = true
        metalLayer.presentsWithTransaction = true
        metalLayer.framebufferOnly = false
        return metalLayer
    }

    override func setFrameSize(_ newSize: NSSize) {
        super.setFrameSize(newSize)
        self.size = newSize
        renderer.viewportSize.x = UInt32(newSize.width)
        renderer.viewportSize.y = UInt32(newSize.height)
        // the conversion below is necessary for high DPI drawing
        metalLayer.drawableSize = convertToBacking(newSize)
        self.viewDidChangeBackingProperties()
    }
    var size: CGSize = .zero
    // This will hopefully be called if the window moves between monitors of
    // different DPIs but I haven't tested this part
    override func viewDidChangeBackingProperties() {
        guard let window = self.window else { return }
        // This is necessary to render correctly on retina displays with the topLeft placement policy
        metalLayer.contentsScale = window.backingScaleFactor
    }

    func display(_ layer: CALayer) {

        if let drawable = metalLayer.nextDrawable(),
           let commandBuffer = commandQueue.makeCommandBuffer() {

            let passDescriptor = MTLRenderPassDescriptor()
            let colorAttachment = passDescriptor.colorAttachments[0]!
            colorAttachment.texture = drawable.texture
            colorAttachment.loadAction = .clear
            colorAttachment.storeAction = .store
            colorAttachment.clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0)

            if let outputImage = self.ciImage {

                let xscale = self.size.width / outputImage.extent.width
                let yscale = self.size.height / outputImage.extent.height
                let scale = min(xscale, yscale)

                if let scaledImage = self.ciMgr!.scaleTransformFilter(outputImage, scale: scale, aspectRatio: 1),

                   let processed = self.showEdits ? self.ciMgr!.processImage(inputImage: scaledImage) : scaledImage {

                    let x = self.size.width/2 - processed.extent.width/2
                    let y = self.size.height/2 - processed.extent.height/2
                    context.render(processed,
                                   to: drawable.texture,
                                   commandBuffer: commandBuffer,
                                   bounds: CGRect(x:-x, y:-y, width: self.size.width, height:  self.size.height),
                                   colorSpace: colorSpace)
                    }

            } else {
                print("Image is nil")
            }
            commandBuffer.commit()
            commandBuffer.waitUntilScheduled()
            drawable.present()
        }
    }
}


text:
Q: How to enable xdebug log in Laravel sail? I am trying to enable xdebug log in Laravel 8, using the sail package for docker.
According to xDebugs docs log will appear automatically when set the xdebug.log to a value.
This is what I tried:

*

*Publish sail's files using sail artisan sail:publish

*This created /docker/7.4, /docker/8.0, /docker/8.1

*With sail php -v I saw that I am using php 8.0.12

*Now I added xdebug.log =/var/www/html/storage/app to docker/8.0/php.ini

*I run sail build --no-cache and restart container. This takes about 8 minutes.

Unfortunately, checking phpinfo() shows that xdebug.log has no value:

According to my docker file, the php.ini should have been copied:
COPY php.ini /etc/php/8.0/cli/conf.d/99-sail.ini so I wanted to try to read the file. To do this, I tried the following:

*

*Log into container using sail shell

*Go to cd /etc/php/8.0/cli/conf.d/

*Read file using cat 99-sail.ini
That is the content:
[PHP]
post_max_size = 100M
upload_max_filesize = 100M
variables_order = EGPCS

# Extensions...
extension=swoole.so

# Zend Extensions...
zend_extension=xdebug.so

However in /docker/8.0/php.ini I have only this:
[PHP]
post_max_size = 100M
upload_max_filesize = 100M
variables_order = EGPCS
xdebug.log =/var/www/html/storage/app

Why is that? I also would like to try to just edit the file directly, but vim is not known. Also the command sudo is not known, although image is  ubuntu:21.04. I tried to install vim, but I am missing access rights.

A:
COPY php.ini /etc/php/8.0/cli/conf.d/99-sail.ini

You can just add Xdebug configuration in the php.ini file that gets copied. But if you update it, then you need to rebuild/restart your container.

A: Looks like this Laravel app used its own dockerfile. I forgot to check docker-compose.yml. Inside laravel.test was build that pointed to a different file. Thats why the php.ini inside docker file was not copied.
Also I had to use a path to an actual log file and put it in quotations like this:
xdebug.log ="/var/www/html/storage/app/xdebug.log"


text:
Q: Is there a preference if one of the functions in convolution of Mellin transform is divergent? The convolution of Mellin transform is
$$
\sigma \left( x \right) = \int _x^1 f \left( \epsilon \right) h \left( \frac{x}{\epsilon} \right) \frac{1}{\epsilon} \mathrm{d} \epsilon ,
$$
if both $f \left( \epsilon \right)$ and $h \left( \epsilon \right)$ vanish out of range $\epsilon \in \left( 0, 1 \right)$.
My question here is, if function $h \left( \zeta \right)$ is divergent at $\zeta = 1$, would there be a difference if we instead write
$$
\sigma \left( x \right) = \int _x^1 h \left( \epsilon \right) f \left( \frac{x}{\epsilon} \right) \frac{1}{\epsilon} \mathrm{d} \epsilon ?
$$
Though the convolution is symmetric for functions $f \left( \epsilon \right)$ and $h \left( \epsilon \right)$, but is this still true if one of the functions has a divergence within the interval?
Thanks in advance!

A: Fix an $x \in (0, 1)$. If $h$ has a singularity at $1$ and we define the convolution as an improper integral, we obtain
$$f*h = \lim_{y \downarrow x}
 \int_y^1 f(t) h {\left( \frac x t \right)} \frac {dt} t =
\lim_{y \downarrow x} G(y), \\
h*f = \lim_{y \uparrow 1}
 \int_x^y h(t) f {\left( \frac x t \right)} \frac {dt} t =
\lim_{y \uparrow 1}
 \int_{x/y}^1 f(t) h {\left( \frac x t \right)} \frac {dt} t =
\lim_{y \uparrow 1}  G {\left( \frac x y \right)}.$$
When $y$ tends to $1$ from below, $x/y$ tends to $x$ from above and $x/y \neq x$ (since $x \neq 0$). Under these conditions, the limit composition rule holds: either
$$\lim_{y \uparrow 1}  G {\left( \frac x y \right)} =
\lim_{y \downarrow x} G(y)$$
or both limits do not exist.


text:
Q: Separating actions from patterns Consider:
$ echo line1 | awk '1END{ print "line2"}'
line1
line2

Note the lack of space between 1 and END.  Is this standard, or a quirk of my implementation of awk?  What is the grammar rule for separating an action from the following address?

A: You are probably using an old version of awk. In the original awk language it wasn't necessary to separate rules on the same line with a semicolon. It was added for consistency with the treatment of statements within an action.
I found this:
http://www.gnu.org/software/gawk/manual/html_node/Statements_002fLines.html
This works for me using GNU Awk 4.0.1:
$ echo line1 | awk '1; END { print "line2" }'
line1
line2

If I remove the ; I get a syntax error. HTH


text:
Q: Constant minimization of a slowly time varying function Is there an algorithm to constantly minimize a function that maintains its rough shape over time but may drift (slowly) in its absolute position?
I have a feedback loop in some hardware where I want to keep parameter X to a minimum. Parameter X can be minimized by adjusting parameter Y, but the exact value of Y that minimizes X drifts over time. In this case the parameter X/Y relationship is roughly quadratic.
My naive solution so far just repeatedly minimizes X using e.g. hill climbing, and with the initial guess being the result of the previous minimization. Is there a better solution?


text:
Q: Como colocar scroll no fim da div? Tenho a seguinte div

...

Dentro dela vai ter vários textos e fará que apareça o scroll. Quando atualiza a página o scroll fica no começo, só que preciso que ele role (inicie) no fim da div. Como devo fazer para isso abrir no fim dessa div que criei ?

A: Adicione ao ScrollTop o valor da propriedade scrollHeight, O scrollHeight retorna a altura.
Ficaria assim em JS Puro:

var objDiv = document.getElementById("scroll");
objDiv.scrollTop = objDiv.scrollHeight;
#scroll {
    height:150px;
    overflow:scroll;
}

Praticamente em cima da terra, contém poucos túneis de 2 metros. Não há estações subterrâneas. Os projetistas tiveram a boa vontade de fazer uma estação abaixo do nível da terra, porém não deu certo, vide Estação Waldomiro Lobo abaixo. O metrô é tão grande como um fio de cabelo de um careca. O projeto que os políticos prometem, mas pegam o seu dinheiro e vão para Rio Branco. A extensão dos trens são de aproximadamente 25 cm 40 metros. Dentre os materiais usados na linha, destacam-se o plástico, durepox, energia roubada da CEMIG e ferro fudido. Atualmente a linha roda com um trem acoplado a outro trem virando um trem de oito vagões, ocupando por inteiro o espaço das plataformas nas estações, uma vez que os trens que circulam atualmente são metade do tamanho da plataforma. Porém este trem acoplado circula uma vez por dia e os presidentes da CBTU acreditam que por causa disso o problema da super-lotação foi resolvido. Para esse magnífico acoplamento foi necessário roubar mais energia da CEMIG.

A: Pode fazer isso com jquery:

$('#scroll-div').animate({
  scrollTop: $(this).height() // aqui introduz o numero de px que quer no scroll, neste caso é a altura da propria div, o que faz com que venha para o fim
}, 100);
div {
 height: 100px;
 overflow-y: auto;
}

O Lorem Ipsum é um texto modelo da indústria tipográfica e de impressão. O Lorem Ipsum tem vindo a ser o texto padrão usado por estas indústrias desde o ano de 1500, quando uma misturou os caracteres de um texto para criar um espécime de livro. Este texto não só sobreviveu 5 séculos, mas também o salto para a tipografia electrónica, mantendo-se essencialmente inalterada. Foi popularizada nos anos 60 com a disponibilização das folhas de Letraset, que continham passagens com Lorem Ipsum, e mais recentemente com os programas de publicação como o Aldus PageMaker que incluem versões do Lorem Ipsum.

A: Caso queira fazer apenas com CSS vc pode usar essas técnicas.
Opção 1:
A técnica com flexbox consiste em inverter a direção do conteúdo da div usando flex-direction: column-reverse então o conteúdo sempre começa embaixo e vai sendo empurrado pra cima.
Veja o exemplo para entender melhor:

.container {
  height: 100px;
  overflow: auto;
  display: flex;
  flex-direction: column-reverse;
  border: 1px solid;
}

Primeira mensagem

oi

oi

oi

oi

oi

oi

oi

oi

oi

oi

Última menssagem

OBS: Essa solução não funciona no IE...

Opção 2:
Se trata de uma div rotacionada para ficar de cabeça para baixo, depois uso direction:rtl para voltar a barra de scroll para direita e text-align:left para ajustar o texto. Depois o conteúdo da mensagens é rotacionado ao contrario para ficar de cabeça para cima.
A mensagem mais nova sempre fica no final na base do scroll.

.scrollable {
    transform-origin: 50% 50%;
    transform: rotate(180deg);
    border: 1px solid;
    width: 120px;
    height: 120px;
    overflow-y: auto;
    direction: rtl;
    text-align: left;
}
.message {
    padding: 0.5em;
}
.messages_wrap {
    float: left;
    width: 100%;
    transform: rotate(180deg);
}

Your message1

Your message2

Your message3

Your message4

Your message5

Your message6

Your message7

Your message8

Your message9


text:
Q: mod_headers is simply not working I have enabled mod_headers in my apache (2.2 on windows server 2008) config but it is not doing anything.
I have moved the headers directive to all parts of the config and even to a .htaccess file in the root and still it does nothing.
<VirtualHost *:80>

    ServerName [dedacted]
    ServerAdmin [dedacted]
    DocumentRoot "C:\data"

    Header always append Access-Control-Allow-Origin "*"

    ErrorLog "logs/data.log"
    CustomLog "logs/data.log" common

    <Directory C:\data>
        Options FollowSymLinks All
        AllowOverride All
        Order deny,allow
        Allow from all
    </Directory>

</VirtualHost>

I have checked the module is loaded via the command line and phpinfo(), see below:
Loaded Modules core mod_win32 mpm_winnt http_core mod_so mod_actions mod_alias mod_asis mod_auth_basic mod_authn_default mod_authn_file mod_authz_default mod_authz_groupfile mod_authz_host mod_authz_user mod_autoindex mod_cgi mod_dir mod_env **mod_headers** mod_include mod_isapi mod_log_config mod_mime mod_negotiation mod_rewrite mod_setenvif mod_php5

Im going out of my mind, and even getting to the point where im considering reinstalling apache.
Can anyone help!

A: Any chance you're doing this for the same reason the rest of us are doing this now, custom font files?   If so, here's what I wound up doing, might help:
<FilesMatch "\.(ttf|otf|eot)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

A: I think the Header directive should go inside a <Directory>, <File> or <Location> section. Like so:
<Directory C:\data>
    Options FollowSymLinks All
    AllowOverride All
    Order deny,allow
    Allow from all
    Header always append Access-Control-Allow-Origin "*"
</Directory>


text:
Q: How to get the eventType from Esper configuration object at runtime I am running an application using Esper as my core CEP engine.
When I try to get the event type that I had previously registered with the Esper runtime, I get an UnsupportedOperationException.
esperConfiguration.addEventType(streamName, fieldNames, fieldTypes);

--------
//several lines later
--------

String[] propertyNames = esperConfiguration.getEventType(streamName).getPropertyNames();

I get the following exception:
 java.lang.UnsupportedOperationException: Obtaining an event type by name is only available at runtime
         at com.espertech.esper.client.Configuration.getEventType(Configuration.java:905)

I am not able to understand why my API call is not "at runtime", even when I am reusing the same object that I used for initializing the Esper engine.

A: The EventType object is available on an initialized engine. So for example:
esperConfiguration.addEventType(streamName, fieldNames, fieldTypes);

EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(esperConfiguration);

String[] propertyNames = epService.getEPAdministrator().getConfiguration().getEventType(streamName).getPropertyNames();


text:
Q: JSON is not validating I am trying to validate a json object below
[{"post_content":"

"}, {"post_content":"

"}]

It fails. I have made it on one line like below
[{"post_content":"

"}, {"post_content":"

"}]

Now it works. I have more objects that cannot be edited repeatedly like this. Is there any workaround?

A: According to the RFC-4627

These are the six structural characters:
  begin-array     = ws %x5B ws  ; [ left square bracket

  begin-object    = ws %x7B ws  ; { left curly bracket

  end-array       = ws %x5D ws  ; ] right square bracket

  end-object      = ws %x7D ws  ; } right curly bracket

  name-separator  = ws %x3A ws  ; : colon

  value-separator = ws %x2C ws  ; , comma

Insignificant whitespace is allowed before or after any of the six
structural characters.
  ws = *(
            %x20 /              ; Space
            %x09 /              ; Horizontal tab
            %x0A /              ; Line feed or New line
            %x0D                ; Carriage return
        )

In your case 1 there is a whitespace next to a  which is why the json stands invalid.
In your case 2 the same whitespace is gone and hence you have a valid json.

A: The problem characters can be escaped or removed :

var json = `[{"post_content":"

"}, {"post_content":"

"}]`

console.log( JSON.parse( json.replace(/\n/g, '\\n') ) )


text:
Q: multiple hidden forms I have a php mysql application. On a detail view page, I am looking at rows of data. I want to use jquery form plugin to do form submitting. What I am not sure of is that i need to have a hidden form for every record in case they want to update a certain bit of data. Im not sure how i should create the form. Should the form be hidden and contain an unique id of each hidden form? Should i create the form using an ajax request to create the form by passing the same parameters that i would have used in create the forms once at page load? Should i create the form values on the fly?
What is a good practice for having hidden forms or dynamic forms using jquery form plugin. This could also be a terribly worded question.

A: If you're using AJAX to post forms, you don't even need a form on the page. You just need to tell your AJAX post code which fields you want to use, serialize them and then post to the server.
You can use class names to signify which fields belong to which "virtual form" to make it easy to collect your form data for each POST type.

A: There is a great deal of benefit to the concept of model binding. If you have many fields, hiddens, etc. that rely on the input of other fields, perhaps a library like Knockout would help. It integrates very nicely with jQuery. http://knockoutjs.com/