text:
Q: extjs4 MVC listeners in controller I'm having trouble creating a listener for the 'itemmouseup' event for my series chart, in the controller.
Controller:
init: function () {
    this.control({
        'monthbalance > chart': {
            render: this.onChartRendered,
            itemmouseup : this.onChartClick
        },
    });
},

if I insert the 'mouseup' event instead of 'itemmouseup' it works fine. But I need 'itemmouseup'. Where am I going wrong?
Thanks.
Update with view extract:
        },{
        id: 'card-1',
        xtype: 'chart',
        store: 'MonthBalances',
        title: 'This Year vs Previous Years',
        theme: 'Category1',
        legend: {position: 'right'},
        shadow: true,
        axes: [{
            type: 'Numeric',
            position: 'left',
            fields: ['monthbalance','monthlastyear','monthpreviousyear'],
            label: {
                renderer: Ext.util.Format.numberRenderer('0,0')
            },
            grid: true,
            minimum: 0
        },{
            type: 'Category',
            position: 'bottom',
            fields: ['month']
        }],

        series: [{
            type: 'line',
            title: 'this year',
            itemId: 'lineone',
            highlight: {
                size: 7,
                radius: 7
            },
            axis: 'left',
            xField: 'month',
            yField: 'monthbalance',
        //  listeners: {
        //      itemmouseup: function() {
        //          console.log('itemmouseup-thisyear');
        //      }
        //  },
        },{
            type: 'line',
            title: 'one year ago',
            itemId: 'linetwo',
            highlight: {
                size: 7,
                radius: 7
            },
            axis: 'left',
            xField: 'month',
            yField: 'monthlastyear',
        },{
            type: 'line',
            id: 'linethree',
            name: 'linethree',
            itemId: 'linethree',
            alias: 'widget.linethree',
            title: 'two years ago',
            highlight: {
                size: 7,
                radius: 7
            },
            axis: 'left',
            xField: 'month',
            yField: 'monthpreviousyear',

        }]
    }];

A: Because there is no itemmouseup event for Chart. This event is only available for classes that extend Ext.view.View or Ext.panel.Table

I think you need to access the series directly and not the chart that
  holds the series. Set your control to the series itself that you use within the chart and not to the chart.
  You may do this by setting the id property of the series chart so that you can bind the control to that id.

// untested but it should work
init: function () {
    this.control({
        '#your-id': {
            itemmouseup : this.onChartClick
        },
    });
},


text:
Q: SQL, datatype error I am working with data insertion in my sql database. I have a form, through which i am inserting some paragraph. The problem is whenever i try to insert this paragraph
Hi Friend, we will do it for you , we have a very good command on it , as we have been working with it since 3 years.We've done projects like you require, that's why we are excited to work on your project. We will assure you for quality work from our side. Working as a team , we came out with a quality work. I will show you my previouse work as well, Contact us for our professional work.Awaiting your reply.Regards, Team Code Tech
It shows me the follwing error, i guess i have missed something with the datatype of the column or what? The data type of the column is varchar(3000).

A: You will need to escape the paragraph properly, by adding slashes \ to the quotes in your paragraph, or using php's function to escape the paragraph.

A: You have Single Quotes in your paragraph.Escape the single quotes using \' for '.
Replace all the single quotes like these.
Or otherwise Use prepared Statements,then you need not to worry

A: This is because the site where you are writing this comment, is not escaping their SQL appropriately, and the single quote We've is causing the query to break.
You can try entering your paragraph, without using concatenated words, like this:

Hi Friend, we will do it for you , we have a very good command on it ,
  as we have been working with it since 3 years.We have done projects
  like you require, that is why we are excited to work on your project.
  We will assure you for quality work from our side. Working as a team ,
  we came out with a quality work. I will show you my previouse work as
  well, Contact us for our professional work.Awaiting your
  reply.Regards, Team Code Tech

..and you may want to reconsidering using a site that has such poor coding; or offer you sevices to the site owner.

redpajama_set_name: RedPajamaStackExchange


text: Q: How to solve an equation with a single and nested ln Given following equation $1444 = ln(p) * ln(ln(p))$. How do I solve this equation for p? I found (through WolframAlpha) that $p$ should be equal to $6.29*10^{112}$, but I can't seem to find a way to find this result algebraically.


text:
Q: xpath: How to combine multiple conditions on different axes I try to extract all links based on these three conditions:

*

*Must be part of

*Must have a

*Must not have a
The result should be "/product/1234".

      Link 1

      Link 2

I'm able to extract the links with the following xpath query.
//div[starts-with(@data-test,"cond")]/a[starts-with(@class,"cond")]/@href

(I know the first part is not really neccessary. But better safe than sorry.)
But I'm still struggling with excluding the links containing an descendant img tag and how to add it to the query above.

A: This should do what you want:
//div[@data-test="cond1" and not(.//img[@class="cond3"])]
/a[@class="cond2"]
/@href

/product/1234


text:
Q: implement custom loss function based on reconstructed output of neural network? I am trying to perform blind source separation using neural networks. I've tried using auto-encoders with different regularization/dropouts, but nothing seems to work.
Now, i've decided to move to implementing a custom loss function based on the reconstructed output. There are a couple i can use, such as correlation between output vectors (which should be minimized), or non-gaussianity of output vectors (which should be maximized).
However, I don't know how to do this in keras, or if its even possible. Basically, this is what I want to do:

*

*feed my linearly mixed signals into the input of the network

*have a few hidden layers where the signals can be re-combined according to various weights of the network

*every training step, reconstruct the output of my network, and compute statistics on the reconstructed outputs, then add these to my cost function, so for example if all my reconstructed outputs are highly correlated, I would penalize that weight combination, hoping for a set of weights in the future that would lead to decorrelated outputs (thus solving the blind source separation problem).
Does anyone know how to do this in keras? I don't mind moving to Tensorflow but would prefer to stay in Keras.
Thanks


text:
Q: How to upload shapefile as input to geoprocessing service using javascript api I need to pass a shapefile as input to my geoprocessing service so as to perform extra process with the features included in it?
 The geoprocessing service will be called from the clients web page using the javascript api. I am using arcgis 10.2.2
Is that feasible ?  If yes are there any examples ?

A: *

*yes, this is feasible.

*yes, here is an example:
https://developers.arcgis.com/javascript/jssamples/portal_addshapefile.html
rather than esriRequest, you will need to pass the zipped file as one of your inputParameters when calling Geoprocessor.execute()


text:
Q: Проблемы с запуском блазор Всем привет, решил изучить новый фреймворк называемый Blazor. Ничего даже еще не успел сделать, но уже возникают проблемы.
Делаю банальные шаги, запускаю студию, и создаю пустой блазор проект, далее при запуске меня должно просто перекинуть на их шаблон(как и в приложениях через разор). Но каждый раз запуск приложения срабатывает только со второго раза. То есть каждый раз после изменения кода, или просто желания запустить и проверить, мне приходится сначала запустить приложение(ничего не будет происходить), затем остановить его, и потом снова запустить, и вот со второго раза все будет работать.
Ктонибудь сталкивался с таким?


text:
Q: How to implement a semaphore class using the filesystem I am a huge fan of c# semaphore class, but I need to extend it to use files instead. The semaphore class will be implemented across many applications and need to be synchronized. These applications will control access to the windows clipboard and access to edit other files. In some cases multiple threads or processes can enter a semaphore at once.

A: Have you considered using named system semaphore? Named semaphore is controlled by the system, and can be used by many processes running on the same system. One process creates the semaphore and other just open it's instance. Windows is ensuring that the semapahore state is correct.
Example usage: http://msdn.microsoft.com/en-us/library/wz356skf.aspx


text:
Q: "Unique" number from several values I'm trying to create a unique unsigned "long" number ($64$ bits) from a list of $4$ other numerical values. Some function $f(n_1, n_2, n_3, n_4) = x$. The order of the values is important so unfortunately I can't use this technique (calculating unique value from given numbers) which seems to give the same unique value from a set of numbers where order doesn't matter.
For example $n_1 = 10, n_2 = 14, n_3 = 18, n_4 = 21$ should be different than $m_1 = 10, m_2 = 1, m_3 = 418, m_4 = 19$. In addition, $o_1 = 10, o_2 = 14, o_3 = 21, o_4 = 18$ should also be different.
I realize it might not be possible to get a truly unique number due to the 64-bit limitation but if you can help me to find a number that's very unlikely to be unique, that would be very very nice:)
Other interesting suggestions that I've looked at:
Function for unique hash code
Deduce a unique number from number
Calculate unique Integer representing a pair of integers
Perhaps that last one could be applied three times? Since $4$ values are two pairs, each pair could generate a unique value and then the two unique values could be used in the function again?

A: The first rule of hash functions is that you probably shouldn't be designing hash functions on your own (most people design pretty bad ones).
A simple way is to take a string hash function, put the numbers in with separators, and then hash the string, like "n1,n2,n3,n4". The programming language you're using may have a built in hash function for this purpose (for example, Java has a hash function for strings built in, which you can use [or reimplement - I don't think Java requires the hash functions to be consistent on different runs of the program] but it is 32 bits). Obviously a 32 bit hash function can be mapped to 64 bits by ignoring 32 bits. Or, you can concatenate 32-bit hashes for "n1,n2" and "n3,n4" into a 64 bit long.
A list of hash functions on wikipedia may be useful.
Do you have any restrictions on what values the numbers can take?


text:
Q: How to do PUT with netty 4.0 based client? I'd like to send a PUT request using netty, but get a timeout from the server. It seems as if the body is not sent. This is my code:
// open file to PUT
RandomAccessFile file = new RandomAccessFile("myFile", "r");
long fileLength = file.length();

// create request (without content, i.e. no DefaultFullHttpRequest)
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, path);
HttpHeaders headers = request.headers();
headers.set(HttpHeaders.Names.HOST, host);
headers.set(HttpHeaders.Names.CONTENT_LENGTH, fileLength);

// send request
ch.write(request);

// send body - is this correct?
ch.write(new DefaultFileRegion(file.getChannel(), 0, fileLength), ch.newProgressivePromise());
ch.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

// wait
ch.closeFuture().sync();

If this works Expect: 100-continue should be used of course.
Thanks for any hints.

A: You should use DefaultFullHttpRequest instead of DefaultHttpRequest
Doing that, you can use the method DefaultFullHttpRequest.content() to get a ByteBuf representing the content of the request. Just write your data into it before sending the request by calling ch.writeAndFlush( request ).


text:
Q: Using Amazon services to query products on the amazon website I'm creating a application where the user will type in the name of a video game and a query will be sent to a servlet. I want this query to search the amazon product database and if the game is found i want to grab the information such as the name, publisher, platform genre etc and add this information to my database. Just like price grabber does. There is an example below.
http://video-games.pricegrabber.co.uk/nintendo-ds-games/m/25813985/details/st=product_tab/
Can this be done and if so what will i need to know and learn to do this.

A: I believe you should be able to use the Amazon Product Advertising API to query for this kind of product information. However the current Terms of Use appear to restrict you from storing the data into your database for more than 24 hours.


text:
Q: Parse string to set of data in JavaScript(jQuery) to match series in HighCharts I want to format the following data from String to "set of data" to match the series in HighCharts.
I've tried parsing it with JSON.parse but, of course, this is not a JSON, so it won't work.
So I have the following string:
var str = "[
{name: 'Abril', data: [107, null, 635, 203, 2]},
{name: 'Mayo', data: [133, 156, 947, 408, 6]},
{name: 'Junio', data: [1052, null, 4250, 740, 38]}
]"

The desired result is:
var data = [
{name: 'Abril', data: [107, null, 635, 203, 2]},
{name: 'Mayo', data: [133, 156, 947, 408, 6]},
{name: 'Junio', data: [1052, null, 4250, 740, 38]}
]

Replacing the quotes with nothing won't work either.

A: I managed to do it with
var data = eval(str);


text:
Q: MSChart changing my value I have an MS Chart.
My code is the following:
chart.Series[chartType].Points.DataBindXY(xValues, xCaption, yValues, yCaption);
chart.ChartAreas[0].AxisX.LabelStyle.Format = "CustomAxisXFormat";
chart.FormatNumber += new EventHandler<FormatNumberEventArgs>(chart_FormatNumber);

Then
private void chart_FormatNumber(object sender, FormatNumberEventArgs e)
{
    if (e.ElementType == ChartElementType.AxisLabels &&
        e.Format == "CustomAxisXFormat")
    {
        e.LocalizedValue = string.Format("{0:hh tt}", new DateTime(1, 1, 2, (int)e.Value, 0, 0).AddHours(-1));
    }
}

xValues and yValues are are arrays of ints.
The problem I am having is, if xValues = int[]{1,2,3}, when chart_FormatNumber handles the event, the values (e.Value) change to {2,3,4}.
So have to do a subtraction there to make it the correct value.
Can somebody tell me what is going on and/or how to stop MSChart from changing my values?

A: Ok, after some head scratching, I figured out what was happening.  I was supplying my x parameters are int.  MS chart was adding +1 and -1 to the x axis range.  The x values I was providing was xValues = int[]{1,2,3}.  In chart_FormatNumber() I was getting {0,1,2,3,4} which was throwing me off.


text:
Q: link prefetch not working properly, script is fetched again on navigation I am having a simple markup.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="prefetch" href="page2.html">
    <link as="script" rel="prefetch" href="./src/script2.js">

Let's check

    Go to page 2 where script2 is there

Here I am prefetching the second script script2.js. It is prefetched successfully but when I click on page 2 link where I have my script tag script2.js, again script2 is downloaded it is not taking it from prefetch cache.
Here is the page2.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

This is page 2

A: Had similar issue and the cause for me was that I had disable cache enabled in Google Chrome.
You can see how to disable/enable caching in Chrome DevTools on this answer https://stackoverflow.com/a/7000899/2992661

A: I've been facing this issue for a while, just got a clue that HTTP header VARY will hurt prefetch cache. checkout the MDN description about VARY.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary
The Vary HyperText Transfer Protocol (HTTP) response header determines how to match future request headers. This information is required to decide whether or not a cached response can be served instead of requesting a fresh one from the origin server. This response header is used by the server to indicate the headers it used when selecting a representation of a resource in a content negotiation algorithm.
in my case, after i remove 'vary', the 'prefetch' script did load from 'prefetch cache'.


text:
Q: VBA code behaving differently when stepping I am trying to write code that will handle the "change" event of any ComboBox on my userform.
I went by this question's answer and created a separate class, etc.
However, it doesn't work. Using the same code on a new project works fine, this code on this project works sometimes when I use the "step by step" execution (F8), but when using normal running it doesn't.
Looking at other people's similar predicaments I added "DoEvents" but that didn't help.
This is my code in the UserForm
Private Sub UserForm_Initialize()

Dim ComboBox_Collection As Collection
Dim ctrl As Control
Dim cbc As ComboBox_Class

Set ComboBox_Collection = New Collection
    For Each ctrl In UserForm1.MultiPage.Pages(2).Controls
    DoEvents
        If TypeName(ctrl) = "ComboBox" Then
            DoEvents
            Set cbc = New ComboBox_Class
            Set cbc.Control = ctrl
            ComboBox_Collection.Add cbc
            DoEvents
        End If
    Next ctrl
Set cbc = Nothing

End Sub

And the class module, named "ComboBox_Class":
Private WithEvents TriggerComboBox As MSForms.ComboBox

Public Property Set Control(CB As MSForms.ComboBox)
    Set TriggerComboBox = CB
End Property

Private Sub TriggerComboBox_Change()
    MsgBox ("yay")
End Sub

A: ComboBox_Collection needs to be a Global variable (at least, Global to your form's code module), or it will disappear/go out of scope as soon as your UserForm_Initialize Sub is finished executing


text:
Q: Button inside textview After a long search on the web, I'm still struggling with this problem.
I'm developing an app for iOS in swift and I need to put a button inside a textview (not a textfield).
The button should be always in the right bottom corner of the textview, and it doesn't have to move when the textview expands when the user types his text.
Of course, the text shouldn't go over the button.
I found several solutions for this, but related to the textfield.
The same approach doesn't seems to work for me.
Can someone help?

A: Why not have your own container that holds both components.
Main View
 - > TextView
 - > Button

Add required constraints. Something along the lines of:
**button**: height constraint; bottom constraint to container.
**TextView** top + bottom constraint to container
**Main View** height constraint (and adjust it based on button action and text)


text:
Q: Sum and joined column data in same query I am using Oracle DB and have the following query which throws the error:

ORA-00937: not a single-group group function

Query:
select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText';

If I try to access the following individually, it works. As in calling sum separately, ct.CREAT_TS separately and so on.
The issue seems to be calling sum in this query. I plan to capture the output in an Object (Java if relevant). I expected the query to output  following. Is it possible to achieve this?
CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   8
2019-04-02 02:56:14.530000    SOME_EVENT 2

After Given answers, getting following results where the sum value is split per column:
CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   2
2019-04-02 02:56:14.530000    SOME_EVENT 2   6

A: You need to include group by clause.
select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText'
    group by ct.CREAT_TS, ev.EVENT;

A: If at least one aggregated column exists in the select list, you need to group by non-aggregated columns
select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText'
    group by ct.CREAT_TS, ev.EVENT

A: You can use window functions to put the total sum on each row:
select ev.EVENT, ct.CREAT_TS, sum(ct.TOT_CT),
       sum(sum(ct.TOT_CT)) over ()
from REF_CT ct inner join
     EVENT ev
     on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
where ct.TX = 'SomeText'
group by ev.EVENT, ct.CREAT_TS;

I don't really recommend putting the value on only one row, but you can do that with window functions:
select ev.EVENT, ct.CREAT_TS, sum(ct.TOT_CT),
       (case when 1 = row_number() over (partition by ev.event order by ct.CREAT_TS)
             then sum(sum(ct.TOT_CT)) over ()
        end)
from REF_CT ct inner join
     EVENT ev
     on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
where ct.TX = 'SomeText'
group by ev.EVENT, ct.CREAT_TS
order by ev.EVENT, ct.CREAT_TS;

The order by is very important if you want the grand total on the first row defined by CREAT_TS.


text:
Q: Create animation with css gradient and javascript I am working on an cordova application that allows us to scan rfid tags. Based of the RSSI signal strength I need to display a bar that shows how close or far the rfid tag is. The closer I get to the tag, the higher the bar and the further I go, the smaller the bar becomes. I built the following plunkr, which I thought I could use. Unfortunately the animation is not very smooth and its slow on the mobile application. I think the issue is that I am showing/hiding the divs with a timeout to simulate the animation. I think I may need to change this to use css animations with gradients. But I am not very familiar on how to do this and I have no idea how I would hide part of the gradient if say I want to show just a small part of the bar. Any suggestions on how to do this are greatly appreciated.
Update: I have uploaded a video of what I would like to achieve. Unfortunately I am not able to upload this to SO. The animation would change as I read the tags. So I could be moving the tag back and forth and based off that it should change the bar.
https://www.dropbox.com/s/9bd421fhqvt9v5g/gradient-bar-demo.mov?dl=0

A: You could animate the height with javascript and the gradient with css. I am updating here on mouse over but you could have it update with every scan input and accomplish the same thing. You would just need to set up more css classes for any other gradient variations you want.

var min = 15;
var max = 100
function randPercent(){
  return Math.floor(Math.random()*(max-min+1)+min);
}

$( ".statusBar" ).mouseover(function(){

  var barSize = randPercent();

  if (barSize > 50) {
    $(this).addClass('close');
  } else {
    $(this).removeClass('close');
  }

  $(this).animate({
    height: barSize+'%'
    },300
  );

});
.wrapper {
  height:100px;
  position:relative;
}
.statusBar {
  width:50px;
  min-height:10px;
  border:1px solid black;
  position:absolute;
  bottom:0;
}
.bg {
  -webkit-transition: background 1s ;
  -moz-transition: background 1s ;
  -ms-transition: background 1s ;
  -o-transition: background 1s ;
  transition: background 1s ;

  background: rgb(71,234,46);

}

.bg.close {
  background: rgb(247,247,49);

}

A: For better performance it is best to animate scale rather than height. Source (really good article on animation performance).
Here is an example of how you could do it. It's not perfect but hopefully it should give you a good starting point.

var input = document.querySelector('input');

input.addEventListener('input', function() {
    var value = this.value / 100;
    var bar = document.querySelector('.meter-bar');

    bar.style.transform = 'scaleY(' + value + ')';
    // Adjust background size to account for the scale change, there is probably a better solution
    bar.style.backgroundSize = '200px ' + (300 / value) + 'px';
});
input {
    width: 200px;
}

.meter {
    width: 200px;
    height: 300px;
    margin-top: 20px;
    background-color: #e5e5e5;
}

.meter-bar {
    width: 100%;
    height: 100%;
    background-color: #333;
    background-image: linear-gradient(to top, #64b572 0%, #9fc63d 50%, #f63908 100%);
    background-size: 200px 0;
    background-position: bottom;
    transform-origin: bottom;
    transform: scaleY(0);
    transition: transform 1s ease, background-size 1s ease;
    opacity: 0.8;
}
<input type="range" min="0" max="100" step="1" value="0">


text:
Q: Is Electret Mic a reliable component to measure Sound Intensity Level (Decibel) I am working on a project where I am using a Arduino Nano to count number of Loud Sound (occurring at intervals) with intensity between 65 dB - 100 dB. I want to put a calibration unit and a digital display unit to calibrate the device within the aforesaid range and display the total count.
I am little bit concerned about the heart of the circuit - the sound sensor. I am thinking of a Electret Mic. Is it a good component to measure Loud Sound Level uniformly? I mean if I employ a electret mic to capture sound and place the output to an amplifier to measure the output analog signal, would it produce same analog reading (with minimum tolerance) for similar intensity of sound everytime? To further clarify it - when a sound is heard with 70dB intensity, if my arduino reads 95 from the sound sensor circuit, would it read something close to 95 everytime 75dB sound is produced?

A: It may be repeatable but not very accurate compared to B&K sound pressure monitor in an anechoic chamber.
Electret mics usually have an open back for far field cancellation,,so they are designed for near field sounds. They are not acoustically flat and thus may generate a poor comparison with different frequency sources.
But for your purpose for linearity, it may be ok, if you are not too loud or too close.

A: Electret itself may be fine. But you have to calibrate it. Also you must have very nice circuit around the microphone to provide stable bias. Last, remember that like any microphone, electret, together with your acoustic system has frequency reaponse. So you will have to apply some correction to any reading you have.


text:
Q: What is the topology on $\mathcal{P}(X)$ associated to each filter on $X$ called? I think the following works: let $X$ denote a set equipped with a filter $\Phi$. Then its powerset $Y = \mathcal{P}(X)$ becomes a topological space as follows: for each $y \in Y$ and each $N \subseteq Y$, we assert that $N$ is a neighbourhood of $y$ iff there exists $\varphi \in \Phi$ such that for all $y' \in Y$, if $y \setminus \varphi = y' \setminus \varphi$, then $y' \in N$.

Question. What is this topology called?

For example, in the case where $X=\mathbb{N}$ and $\Phi$ consists of all non-empty uppersets, we obtain a topological space $Y$ that looks a bit like the unit interval $[0,1],$ though it's not dense. We can obtain the unit interval as a quotient of $Y$.


text:
Q: Why can QGIS open MrSid files, but GDAL cannot? I am able to convert MrSid to GeoTiff in the QGIS GUI, but I would like to do this programmatically through gdal-translate. However GDAL won't recognize the data type, MrSid. But it can when using qgis directly.
gdal_translate -of GTiff -if MrSid ortho_1-1_1n_s_pa079_2015_1.sid /private/var/folders/bk/2m7_mv8d7n5cf43lw0m71j3m0000gn/T/processing_171fdbca8a2e478683a3f68eba3f7141/4d384681ae18421c8d9285b74d514945/OUTPUT.tif
Error Message :
Warning 1: MrSid is not a recognized driver ERROR 4: ortho_1-1_1n_s_pa079_2015_1.sid' not recognized as a supported file format.

A: GDAL is not a monolithic software that is exactly same for all users, in all environments. Especially proprietary formats like MrSID which require special licences and perhaps binaries are not compiled by default https://gdal.org/drivers/raster/mrsid.html#raster-mrsid.
If your QGIS can open MrSID files then it has been built with  a GDAL version that has MrSID driver. Your command line GDAL may be some other version. You can check if GDAL has MrSID driver from command line with gdalinfo. If you have the driver you will see this
gdalinfo --format MrSID
Format Details:
  Short Name: MrSID
  Long Name: Multi-resolution Seamless Image Database (MrSID)
  Supports: Raster
  Extension: sid
  Help Topic: drivers/raster/mrsid.html
  Supports: Open() - Open existing dataset.
  Supports: Virtual IO - eg. /vsimem/


text:
Q: Using SqlReaderQuery in Data Pipeline I'm copying data from an Azure SQL DB to blob by the means of a query.
Here is the script of the activity:
{
    "type": "Copy",
    "typeProperties": {
        "source": {
            "type": "SqlSource",
            "sqlReaderQuery": "select distinct a.*, b.Name from [dbo].[Transactxxxxxxx] a join dbo.Anxxxxx b on a.[Clixxxxx] = b.[Fixxxxxx] where b.Name = 'associations'"
        },
        "sink": {
            "type": "BlobSink",
            "writeBatchSize": 0,
            "writeBatchTimeout": "00:00:00"
        }
    },
    "inputs": [
        {
            "name": "Txnsxxxxxxxxxxx"
        }
    ],
    "outputs": [
        {
            "name": "Txnxxxxxxxxxxxx"
        }
    ],
    "policy": {
        "timeout": "01:00:00",
        "concurrency": 1,
        "retry": 3
    },
    "scheduler": {
        "frequency": "Hour",
        "interval": 1
    },
    "name": "Copyxxxxxxxxxx"
}

The activity seems to work but it does not put any file in the sink.
The dataset points to the correct container.

A: Per your provided information, I found successful run logs in our service. I noticed that the target blob is specified like "experimentinput/Inxxx_To_xx_Associations.csv/Inxxx_To_xx.csv". The blob name is static, and multiple slice runs will overwrite the same blob file. You could leverage the partitionBy property to have a dynamic blob name. Refer to this article for more details: https://azure.microsoft.com/en-us/documentation/articles/data-factory-azure-blob-connector/#azure-blob-dataset-type-properties.


text:
Q: python GstRtspServer-How can i get a factory list that i have added to a mount point? I am trying setup a rtsp server by gst,i could add a factory to a mountpoints like this
import gi

gi.require_version('Gst', '1.0')
gi.require_version('GstRtspServer', '1.0')
from gi.repository import Gst, GstRtspServer, GObject

loop = GObject.MainLoop()
GObject.threads_init()
Gst.init(None)

class MyFactory(GstRtspServer.RTSPMediaFactory):
    def __init__(self,desc_str):
        GstRtspServer.RTSPMediaFactory.__init__(self)
        self.desc=desc_str

    def do_create_element(self,url):
        return Gst.parse_launch(self.desc)

class GstServer(object):
    def __init__(self):
        self.server = GstRtspServer.RTSPServer()
        self.server.attach(None)

    def add_source(self,path,desc_str):
        f = MyFactory(desc_str)
        f.set_shared(True)
        m = self.server.get_mount_points()
        m.add_factory(path, f)

if __name__ == '__main__':
    str2 = 'filesrc location=E:/aaa_rtp/my_down_3.mp4 ! qtdemux name=mdemux mdemux.video_0 ! queue ! rtph264pay pt=96 name=pay0 mdemux.audio_0 ! queue ! rtpmp4apay pt=97 name=pay1'
    str3='filesrc location=E:/aaa_rtp/1913973949042281958.mp4 ! qtdemux name=mdemux mdemux.video_0 ! queue ! rtph264pay pt=96 name=pay0 mdemux.audio_0 ! queue ! rtpmp4apay pt=97 name=pay1'
    s = GstServer()
    s.add_source('/t',str2)
    s.add_source('/1913973949042281958',str3)
    loop.run()

But here the question.
Is there a api that i can use to get a factory list that have been mounted to the port in the runtime? I need the list to send the client as a playlist.


text:
Q: WordPress: Where do I view var_dump results being called in functions.php? One thing I've always struggled with in learning PHP is figuring out where to view debug code such as print_r and var_dump.
For example, in my functions.php of my WordPress/WooCommerce site, I have:
function my_function_name($order_id) {
    $order = new WC_Order( $order_id );
    echo var_dump($order);
}

add_action( 'woocommerce_order_status_completed', 'my_function_name', 10, 1 );

I want to view the results of var_dump but after placing an order in WooCommerce (my understanding of when the woocommerce_order_status_completed hook should be called), how I have no idea where/how to view the var_dump results.
(It could also be possible my function is written incorrectly)
I've attempted to research this, but many places just say to put var_dump in functions.php, without specifying how to view those results (of course I could be vastly misunderstanding).

A: If you want to debug a value, you can put it anywhere before you call get_header(); in your template to have a clear view of your var_dump.
For example, at the top of your functions.php, you can call:
// Call the function you've created
my_function_name(1); // Replace 1 with a real order id

You might also want to change your function to exit the script so it stops rendering the other stuffs:
function my_function_name($order_id){

    $order = new WC_Order($order_id);
    var_dump($order); // You do not need the echo
    exit;

}

Then simply load any page of your wordpress:
http://example.com

A: You may want to see here for a similar issue, where killing the flow immediately after var_dump solved the issue.


text:
Q: Django UpdateView Bootstrap Modal - i've got empty form in modal window I've got empty Bootstrap modal form with Django UpdateView(CBV)
The most important question without using js , I will not be able to display data in a modal window? (I only use bootstrap.bundle.min.js in base.html)
Modal window show fields of empty form
view.py
class HistoryPamentsByService(ListView):
    model=Payments
    form_class=PaymentsForm
    template_name ='myflat/history_by_service.html'
    context_object_name='flats'
    slug_url_kwarg = 'slug'

    def get_context_data(self, **kwargs):
        context=super().get_context_data(**kwargs)
        form=PaymentsForm()
        payments=Payments.objects.filter(flats_id=self.kwargs['flats_id'])
        context['form']=form
        return context

    def get_form(self,*args,**kwargs):
        super().get_form(*args, **kwargs)
        form=PaymentsForm()
        return form

    def get_queryset(self):
        return Payments.objects.filter(slug=self.kwargs['slug'],flats_id=self.kwargs['flats_id'])

class UpdatePayments(UpdateView):
    model=Payments
    pk_url_kwarg='pk'
    template_name='myflat/update_modal.html'
    context_object_name='name_flat'
    fields=['name_service','amount_of_bill',
            'amount_of_real',
            'date_of_bill',
            'date_of_payment',
            'status_payment',
            'comments',
            'bill_save_pdf']
    def get_success_url(self):
        return reverse('HistoryPamentsByService',
        kwargs={'slug':self.object.slug,
                'flats_id': self.object.flats_id})

urls.py
urlpatterns = [ path('history_by_service/<slug:slug>/<int:flats_id>/',
                      HistoryPamentsByService.as_view(),name='HistoryPamentsByService'),
                path('UpdatePayments/<int:pk>/',UpdatePayments.as_view(),name='UpdatePayments'),
              ]

template
history_by_service.html (for ListView)
{%extends "base.html"%}
{%block content%}
{% for flat in flats  %}

      {{ forloop.counter }}
      {{flat.name_service}}
      {{flat.amount_of_bill}}
      {{flat.amount_of_real}}
      {{flat.date_of_bill}}
      {{flat.date_of_payment}}
      {{flat.get_status_payment_display}}
      {{flat.comments}}
      {{flat.bill_save_pdf}}

<form method="post" action="{% url 'UpdatePayments' flat.pk  %}" enctype="multipart/form-data">
{% csrf_token %}
<button type='button' class='btn btn-success btn-sm' id="update_modal"
data-bs-toggle="modal"     data-bs-target="#update_modal{{flat.pk}}">
Edit</button>
{% include "myflat/update_modal.html" %}
</form>
{% endfor %}

{% endblock content %}

template
update_modal.html

{{flat.name_flat}}

     <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

<form  method="post" action="{% url 'UpdatePayments' flat.pk %}" enctype="multipart/form-data">

     {% csrf_token %}
     {% for field in form %}
        {{field}}
     {% endfor %}

    <button type="submit" class="btn btn-primary" >
      Save</button>

    <button type="button" class="btn btn-warning"
     data-bs-dismiss="modal">
     Close</button>

</form>

I try add in UpdatePayments(UpdateView) next code:
class UpdatePayments(UpdateView):
    model=Payments
    pk_url_kwarg='pk'
    form_class=PaymentsForm
    template_name='myflat/update_modal.html'
    context_object_name='name_flat'

def get_context_data(self, **kwargs):
        context= super().get_context_data(**kwargs)
        obj=Payments.objects.get(pk=self.kwargs['pk'])
        form=PaymentsForm(self.request.POST or None ,instance=obj)
        context['form']=form
        return context

but still nothing in Modal is empty fields!!!
What's wrong, any helps,please!!!


text:
Q: Get Connection dataSource of Tabular database Using SQL2017 version 14.0.1.439. I need to change dataSource path of Connections in Tabular database with Powershell.
Here is my code:
$ServerName="localhost\tabular"
$loadInfo =
[Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$server = New-Object Microsoft.AnalysisServices.Server
$server.connect($ServerName)
if ($server.name -eq $null) {
 Write-Output ("Server '{0}' not found" -f $ServerName)
 break
}
foreach ($d in $server.Databases )
{
Write-Output ( "Database: {0}; Status: {1}; Size: {2}MB; Data Sources: {3} " -f $d.Name, $d.State, ($d.EstimatedSize/1024/1024).ToString("#,##0"), $d.DataSources.Count )
}

My problem, that $d.DataSources.Count is always 0.
I am looking for some way to edit it with PS.

A: You should be accessing the data sources through Model.Datasources
I can confirm that the following code returns the number of data sources for my Tabular models.
$ServerName="localhost\tabular"
$loadInfo =
[Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")

$server = New-Object Microsoft.AnalysisServices.Server
$server.connect($ServerName)

if ($server.name -eq $null) {
 Write-Output ("Server '{0}' not found" -f $ServerName)
 break
}
foreach ($d in $server.Databases )
{
     Write-output ( "Database: {0}; Status: {1}; Size: {2}MB; Data Sources: {3} " -f $d.Name, $d.State, ($d.EstimatedSize/1024/1024).ToString("#,##0"), $d.Model.DataSources.Count )
}


text:
Q: Add script inheriting from scriptableobject to game object I have a script called Weapon.cs, which is a scriptable object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class Weapon : ScriptableObject {

protected Camera _mainCamera;
protected Transform _weaponTransform;
protected int _damage;
protected int _fireRatePerSecond;
protected bool _isAutomaticWeapon;

protected void FireWeapon()
{
    //if the weapon is automatic
    if (_isAutomaticWeapon)
    {
        ShootRapidFireOnMouseHold();
    }
    //if the weapon is semi automatic
    else
    {
        ShootSingleBulletOnMouseClick();
    }
}

protected void MoveWeaponWithCamera(Transform weaponTransform)
{
    _weaponTransform.rotation = _mainCamera.transform.rotation; //temporary way of making sure the gun moves with the camera
}

protected void ShootSingleBulletOnMouseClick()
{
    if (Input.GetKeyDown(KeyCode.Mouse0)) //if left mouse button is clicked
    {
        CastRay();
    }
}

protected void ShootRapidFireOnMouseHold()
{
    if (Input.GetKey(KeyCode.Mouse0)) //if left mouse button is held down
    {
        CastRay(); //rapid fire
        //PlayShootAnimation();
    }
}

protected void CastRay()
{
    RaycastHit hit;
    if (Physics.Raycast(_mainCamera.transform.position, _mainCamera.transform.forward, out hit, 100))
    {
        Debug.Log(hit.transform.name);
    }
}
//protected abstract void PlayShootAnimation();
}

I have a second script called MachineGun.cs, which inherits from Weapon.cs, and thus indirectly from scriptable object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MachineGun : Weapon{

private GameObject _machineGunBarrel;

//private float _animationVelocity;

// Use this for initialization
void Start () {
    //initialize the basic properties of a weapon
    _damage = 7;
    _fireRatePerSecond = 10;
    _isAutomaticWeapon = true;

    _weaponTransform = GameObject.Find("Weapon_MachineGun").transform;
    _machineGunBarrel = GameObject.Find("machinegun_p1");

    _mainCamera = Camera.main;

}

// Update is called once per frame
void Update () {
    MoveWeaponWithCamera(_weaponTransform);
    FireWeapon();
}

//protected override void Shoot()
//{
//    RaycastHit hit;
//    if(Physics.Raycast(_mainCamera.transform.position, _mainCamera.transform.forward, out hit, 100))
//    {
//        Debug.Log(hit.transform.name);
//    }
//}

void PlayShootAnimation()
{
    _machineGunBarrel.transform.RotateAround(_machineGunBarrel.transform.up, _fireRatePerSecond * Time.deltaTime);
    PlayShootAnimation(); //play the shoot animation of the gun
}
}

It's currently impossible, since MachineGun.cs doesn't inherit from monobehaviour anymore.
I have a weapon gameobject in my scene, and so here's my question:
How do I go about adding the MachineGun.cs script as a component to my weapon gameobject? Or since this is impossible,
How should I build a weapon system with a general Weapon.cs script from which all weapons can inherit basic functions and fields/variables?
EDIT 1: provided code to my post and added the "why I wanna do this".
Thanks in advance!

A: ScriptableObjects should mainly be used in a data oriented way, they are very convenient and quite efficient for the task. Also, plaguing your project of MonoBehaviour is a very bad (and wide-spread) practice.
IMO, you should have a MonoBehaviour with weapon logic management and your ScriptableObjects should be your weapon data (which is interpreted by loading them up in your Weapon MonoBehaviour), such that you have Minigun, Glock, Katana.. Scriptable objects which have data like, attack speed, reload speed, charger size, weapon model/textures, reference to model hitbox, yadayadayada. (You might have a generic Weapon MonoBehaviour, but derive a Gun one, a Blade etc.. for very specific management, but which will still need data from ScriptableObjects)
In short your MonoBehaviours define usage and interaction, while your ScriptableObjects define characteristics

A: ScriptableObject says:

Description
A class you can derive from if you want to create objects that don't
need to be attached to game objects.

So either you should not attach this script to game object or derive your object from "MonoBehaviour" if you want to attach it to game object.
Why did you derive it from ScriptableObject ?


text:
Q: Can we return value which is non pointer to the pointer function  char* xpx(char* src)
 {
      char result[sizeof(src)];

      strcpy(result,src);

      return result;

 }

There are 2 bugs in the above code.
1) strcpy is passing the src as parameters but it is not legal as str
is a pointer.
I could not able to find the another one. Could you help me?

A:
not legal as str is a pointer

Not sure what you mean by that, but passing pointers to functions is perfectly fine.
As for "bugs" in the function, it is hard to say if there are any, given that you have not provided what is the expected behavior of the function. The function is legal C, although quite useless and dangerous to use (and will trigger warnings from common compilers):

*

*Do not return addresses to local variables, since they do not exist anymore after your return, so you shall not access them.

*If you are passing a null-terminated string into a function and you need to get a buffer of its size; then you have to find out its length at runtime using something like strlen() and then allocate the memory on the heap with malloc() (or using VLAs on C99 and later).

A: Look at strcpy docs:

char *strcpy( char *restrict dest, const char *restrict src );

Copies the null-terminated byte string pointed to by src, including
  the null terminator, to the character array whose first element is
  pointed to by dest.  The behavior is undefined if the dest array is
  not large enough. [...] (important but not relevant to the question so
  omitted part)

So strcpy does take 2 pointers. That's fine. It's not a bug.
To find the bug pay attention to (and think about it, it's logical): dest array must be large enough. What does "large enough" mean here? Well since the functions copies the string from src, including null terminator to dest it means dest must be at least the length of the string in src + 1 for the null terminator. That means strlen(src) + 1.
sizeof(src) is the same as sizeof(int*) which is the size of a char pointer on the platform. The size of the pointer. Not what you want.
The next error is that the functions returns the address of an automatic storage object, aka the result array. This means that the array will cease to exist when the function exits and thus the function returns a pointer to an object that is no longer valid. A solution to this would be to use malloc to allocate the array. Another is to change the signature of xpx to something similar to strcpy where the destination array is supplied.
So summing them you need something along this:
char* result = malloc(strlen(src) + 1);

Another bug (yes, technically it's not a bug, but semantically it's a bug in my opinion) is that src should be of const char* type.
Another source of potential problems and bugs is if the input is not well-behaved, e.g. if src is not null-terminated, but it is debatable how much responsibility this function should carry regarding this.


text:
Q: Alter Firefox Back button in the PDF Reader to take you back to previous webpage not first page of the PDF PDF documents have hyperlinks that take you to the different sections of the document. After clicking the hyperlink, the Firefox back button does not take you to the previous webpage, but rather navigates to the previous section of the pdf document.  How do I disable this function, and force Firefox to take me to the previous webpage?

A: Reading through the relevant PDF.js source code I don't see any way to control this: new session history entries are pushed unconditionally.


text:
Q: Using SCSS variables in CSS Modules I've a _color.scss file which consists of 400 colors as variables. And I've like 20 components which needs this color variables in their styles.
I'm using SCSS + CSS Modules to construct my styles. As of now, I'm importing this _color.scss in each and every component's style.scss.
Example:
component1.scss
@import "color.scss";

component2.scss
@import "color.scss";

component3.scss
@import "color.scss";

Previously, when I was using SCSS standalone, I'll import the color.scss to my index.scss and import all the other styles below it. By this, the variables will be available across all the components.
Example:
//index.scss
@import "color.scss";
@import "component1.scss";
@import "component2.scss";
@import "component3.scss";

Now, all the variables under _color.scss will be available under component1.scss, component2.scss and component3.scss.
Is there a way to do something similar to this with CSS Modules + SCSS? A single place to declare global varibales?

A: The way I'm using now looks pretty clean. So, I'm sharing it to all.
Use sass-resources-loader
This will include the @import to all your .scss files making the variables and mixins available across all the scss files while using css modules.
The webpack@2.x.x config
...
    module: {
      rules: [
        {
          test: /\.scss$/,
          loaders: [
            'style-loader',
            'css-loader?modules&importLoaders=1&localIdentName=[path][name]__[local]__[hash:base64:10]',
            'sass-loader',
            'sass-resources-loader',
            'import-glob-loader',
            'postcss-loader',
          ],
        },
     },
     plugins: [
       new webpack.LoaderOptionsPlugin({
        options: {
          postcss: [
            autoprefixer(),
          ],
          sassResources: [
            './app/constants/_style-variables.scss', //include your scss imports here
          ],
          context: path.resolve(__dirname, '../../')
        }
      })
     ]
...


text:
Q: Excel coloured line chart for grouped data? In Excel how do I create a line Chart with each simulator being its own coloured line showing Calculation time (and potentially another colour for its Total time).
Axis X = Rounds
Axix Y = Time (linear from smallest time to largest?)
Thanks
SimulatorName                   Round               TotalTime           CalculationTime
IndexedSimulator                1                   9                   2
ListSimulator                   1                   3998                25
HashSetSimulator                1                   25                  24
IndexedSimulator                2                   1                   0
ListSimulator                   2                   26                  23
HashSetSimulator                2                   29                  27
IndexedSimulator                3                   1                   0
ListSimulator                   3                   41                  38

A: If I understand you correctly, you can first run a pivottable and then run a chart on it:

I used only the calculated time in this screenshot and you can change the settings of the pivottable to remove those grand totals if you don't want to see them. If you don't know how to do a pivot table (even after reading the documentation), leave me a comment and I'll put some explanation.


text:
Q: Bitbucket API read RAW file from branch with Access Code I have an issue accessing a branch on Private Bitbucket Repo using an Access Token.
Works fine using master, but I have no idea how to access a branch.
For example:
Accessing master is OK:
https://api.bitbucket.org/2.0/repositories/user/repo/src/master/template.json?&access_token=gHmDP4e4XeBQUrmFXTGWPC4qVZEfv_JGZnXt61NGfEH2O4OeiYGHeCL0a8rwLVFasjJ0UBHcne-r2myBsGk=

Tried the following to access branch feature/project/code:
https://api.bitbucket.org/2.0/repositories/user/repo/src/master/template.json?at=refs%2Fheads%2Ffeature%2Fproject%2Fcode&access_token=gHmDP4e4XeBQUrmFXTGWPC4qVZEfv_JGZnXt61NGfEH2O4OeiYGHeCL0a8rwLVFasjJ0UBHcne-r2myBsGk=
https://api.bitbucket.org/2.0/repositories/user/repo/src/master/template.json?at=refs/heads/feature/project/code&access_token=gHmDP4e4XeBQUrmFXTGWPC4qVZEfv_JGZnXt61NGfEH2O4OeiYGHeCL0a8rwLVFasjJ0UBHcne-r2myBsGk=
https://api.bitbucket.org/2.0/repositories/user/repo/src/feature/project/code/template.json?access_token=gHmDP4e4XeBQUrmFXTGWPC4qVZEfv_JGZnXt61NGfEH2O4OeiYGHeCL0a8rwLVFasjJ0UBHcne-r2myBsGk=

Any help will be appreciated.
Thanks

A: I guess it's due to your branch naming decisions and the URL parsing regex.
You can use instead a revision code following this URL schema:
https://api.bitbucket.org/2.0/repositories/{accountname}/{repo_slug}/src/{revision}/{path}

As in example:
https://api.bitbucket.org/2.0/repositories/user/repo/src/{commit hash for head in feature/project/code/}/template.json?&access_token=blablabla

Here docs
EDIT
In alternative you could use a branch name without slashes.

A: Have you tried the following?
https://api.bitbucket.org/2.0/repositories/user/repo/src/feature%2Fproject%2Fcode/template.json?access_token=gHmDP4e4XeBQUrmFXTGWPC4qVZEfv_JGZnXt61NGfEH2O4OeiYGHeCL0a8rwLVFasjJ0UBHcne-r2myBsGk=

A: The correct api to use is https://api.bitbucket.org/1.0 using the following uri:
https://api.bitbucket.org/1.0/repositories/user/repo/raw/feature/project/code/template.json?access_token=gHmDP4e4XeBQUrmFXTGWPC4qVZEfv_JGZnXt61NGfEH2O4OeiYGHeCL0a8rwLVFasjJ0UBHcne-r2myBsGk=

Thanks to all you responded.


text:
Q: AVCaptureSession.Preset options Looking over the AVCaptureSession.Preset options, is .photo the only choice for still photos and the rest are all for video capture? What's the difference between .low, .medium and .high and the others like .hd1920x1080? And how do you change the photo size like 4:3 and 16:9? Thanks

A: It is a bit confusing: AVCaptureSession.Preset doesn't tell you what the photo format or quality will be, it merely tells the AVCaptureSession to configure its inputs and outputs for a specified common use case. So you'd use .photo if you are only interested in photo output, and other modes when you are interested in some video output as well. I believe if you choose .photo and try to add a video output, you will get an error.
Photo size, much like in real camera, depends on the hardware, you cannot change directly how it's captured. You can, however, change various photo output options using AVCapturePhotoSettings and further process your photo with either Core Graphics or Metal image filters
I recommend to look at AVCam demo app apple provides, it will answer a lot of these questions.


text:
Q: How to set different page size for first page in Orchard CMS We got the need to display a blog posts page that display X posts - first post is displayed as a header and the rest are in 2 columns. The page has a show more button at the bottom that fetches the next page posts using ajax and adding them at the bottom.
Is it possible to get X+1 items for the subsequent pages?
Any hint, even in code are welcome since we use a sourced version of orchard installation.

A: So before cluttering the comments above this is my proposed solution.
I think there was a slight misunderstanding about changing the controller action which I'd like to clarify (I hope I understood everything correctly now):
Orchard.Blogs | BlogController | Item Action
public ActionResult Item(int blogId, PagerParameters pagerParameters) {
    // This is all original code
    Pager pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);

    var blogPart = _blogService.Get(blogId, VersionOptions.Published).As<BlogPart>();
    if (blogPart == null)
        return HttpNotFound();

    if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.ViewContent, blogPart, T("Cannot view content"))) {
        return new HttpUnauthorizedResult();
    }

    // This is the actual change:
    // Use the pagerParameters provided, otherwise fall back to the blog settings
    pager.PageSize = pagerParameters.PageSize.HasValue ? pager.PageSize : blogPart.PostsPerPage;

    // This is all original code again
    _feedManager.Register(blogPart, _services.ContentManager.GetItemMetadata(blogPart).DisplayText);
    var blogPosts = _blogPostService.Get(blogPart, pager.GetStartIndex(), pager.PageSize) // Your new page size will be used
        .Select(b => _services.ContentManager.BuildDisplay(b, "Summary"));
    dynamic blog = _services.ContentManager.BuildDisplay(blogPart);

    var list = Shape.List();
    list.AddRange(blogPosts);
    blog.Content.Add(Shape.Parts_Blogs_BlogPost_List(ContentItems: list), "5");

    var totalItemCount = _blogPostService.PostCount(blogPart);
    blog.Content.Add(Shape.Pager(pager).TotalItemCount(totalItemCount), "Content:after");

    return new ShapeResult(this, blog);
}

So the change is very subtle, but this way I would configure the blogs default pageSize to 7 items and for every subsequent Ajax-Request I'd provide a "pageSize"-Parameter with the desired size.


text:
Q: trying to save regex in mongo db '\' character gets removed every time I am trying to save list of regex in mongodb.
But while saving the values '\' char present in value automatically gets removed.
e.g; "val":/55\sA\.?B\.?C\.?\s/
after insertion it becomes
"val":/5sA.?B.?C.?s/

A: You need to escape your characters with \. For example, if you're trying to add the ? character, you need to do something like ...\?B.\?c....
I hope my answer was helpful.


text:
Q: How to add new stackpanel when new item added? The problem that I'm facing is I want everytime user enter the item code all related details insert in a new stackpanel. that's means every item added will added a new stackpanel. 1 stackpanel will have 1 item. but I couldn't get how to do it that way.
this is the code behind when user key in barcode and press 'Enter'
private void txtItemCode_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {

            string itemCode = txtItemCode.Text;
            StackPanel spItemDisplay = new StackPanel();
            spItemDisplay.Orientation = Orientation.Horizontal;

            if (e.Key == Key.Return)
            {
              spItemDisplay.Children.Add(spItemDisplay);
                SimpleItem item = cashierViewModel.validateItemOnHandCode(txtItemCode.Text, 1);

                if (item != null)
                {
                        cashierViewModel.AddItemToList(item, PosWindows2.cashier.ShopId);
                        LoadData();
                        dgItemDisplay.ItemsSource = null;
                        dgItemDisplay.ItemsSource = CashierViewModel.itemDisplayList;
                }
                else
                {
                    MessageBox.Show("Item Not Available.", "Alert", MessageBoxButton.OK, MessageBoxImage.Information);
                }

                txtItemCode.Text = null;
            }
        }

this is at .xaml
 <StackPanel x:Name="spItemDisplay" >
                     <ScrollViewer HorizontalAlignment="Right" >
                        <DataGrid CellEditEnding="DgItemDisplay_CellEditEnding" HorizontalAlignment="Center"  Width="1036" Name="dgItemDisplay" AutoGenerateColumns="False" Height="auto" >
                            <DataGrid.Columns>
                                <DataGridTextColumn IsReadOnly="True" x:Name="dgItemCode" Width="200" Header="Barcode" Binding="{Binding ItemCode}" />
                                <DataGridTextColumn IsReadOnly="True" x:Name="dgItemName" Width="350" Header="Item Name" Binding="{Binding ItemName}" />
                                <DataGridTextColumn IsReadOnly="True" x:Name="dgItemPrice" Width="150" Header="Item Price" Binding="{Binding ItemPrice}" />
                                <DataGridTextColumn x:Name="dgQuantity" Width="150" Header="Quantity" Binding="{Binding Quantity, UpdateSourceTrigger=PropertyChanged}" />
                                <DataGridTextColumn x:Name="dgDiscount" Width="150" Header="Discount" Binding="{Binding Discount, UpdateSourceTrigger=PropertyChanged}" />
                            </DataGrid.Columns>
                            <DataGrid.RowDetailsTemplate>
                                <DataTemplate  >
                                    <StackPanel Name="spItem" HorizontalAlignment="Center" >
                                        <Grid Margin="0,10"  >
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="300" />
                                                <ColumnDefinition Width="300" />
                                                <ColumnDefinition Width="100" />
                                                <ColumnDefinition Width="100" />
                                                <ColumnDefinition Width="*" />
                                            </Grid.ColumnDefinitions>
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="Auto" />
                                                <RowDefinition Height="Auto" />
                                            </Grid.RowDefinitions>
                                            <TextBlock Text="Quantity: " FontWeight="Bold" Grid.Column="2" Grid.Row="0"/>
                                            <TextBox x:Name="txtQty" Text="{Binding Quantity, UpdateSourceTrigger=PropertyChanged}" Grid.Column="3" Grid.Row="0"/>
                                            <TextBlock Text="Discount: " FontWeight="Bold" Grid.Column="2" Grid.Row="1"/>
                                            <TextBox x:Name="txtDisc" Text="{Binding Discount, UpdateSourceTrigger=PropertyChanged}" Grid.Column="3" Grid.Row="1"/>
                                        </Grid>
                                    </StackPanel>
                                </DataTemplate>
                            </DataGrid.RowDetailsTemplate>
                        </DataGrid>
                    </ScrollViewer>
                </StackPanel>

can anybody help ? I really need your help. Thank you :)

A: Can't you go for an ItemsControl/ListView, that has an StackPanel(for spItemDisplay) as an ItemsPanelTemplate and specify the DataTemplate as your StackPanel (spItem)?
Something along these lines:
    <ItemsControl ItemsSource="{Binding DisplayItems}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel x:Name="spItem">
                    <Grid Margin="0,10">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>

                        <TextBlock Text="Quantity: "/>
                        <TextBlock Text="{Binding Quantity}"/>
                        <TextBlock/>
                    </Grid>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

UPDATE:
If you're not familiar with DataTemplates please have a look at Andy's link in the comments or have a look at the following example.
Items Control + DataTemplate explained


text:
Q: Why it give the error "initialize variable image"? But when I initialize the app crash This is the second class, that gives the format to the images I`m using
public ViewPagerAdapter(Activity activity, String[] images) {
    this.activity = activity;
    this.images = images;

}

@Override
public int getCount() {
    return images.length;
}

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
    return view==object;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    inflater =(LayoutInflater)activity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView= inflater.inflate(R.layout.viewpager_item,container,false);

    ImageView image;
    DisplayMetrics dis = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(dis);
    int height = dis.heightPixels;
    int width = dis.widthPixels;
    image.setMinimumHeight(height);
    image.setMinimumWidth(width);

    try {
        Picasso.with(activity.getApplicationContext())
                .load(images[position])
                .placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .into(image);

    }
    catch (Exception ex) {
    }
    container.addView(itemView);
    return itemView;

}

@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    ((ViewPager) container).removeView((View)object);
}}`

and this is the primary class
    ViewPager viewPager;
ViewPagerAdapter adapter;
private String [] images = {

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);

    viewPager = (ViewPager)findViewById(R.id.viewpager);
    adapter = new ViewPagerAdapter(Search.this,images);
    viewPager.setAdapter(adapter);

}}

I`m following this youtube tutorial, and I have the same code but mine doesn't work https://www.youtube.com/watch?v=SX8l9vv-N_4
it if forces me to declare the variable as null, but in the video doesn't.

A: You forget findViewById image = findViewById(...);


text:
Q: Ordering interaction levels using fct_relevel I have a 2 by 2 design with a reference level for genotype (gen = "WT") and treatment (treat = "saline").
I am trying to reuse the code and not hardcode my levels (my WT will always be the reference level regardless of what other genotypes I'm using).
Here's a toy example of my dataset.
library(tidyverse)
toy1 <- tidyr::expand_grid(
  gen = c("WT", "QQ"),
  treat = c("saline", "ab")
)

toy1 %>%
  mutate(gen = fct_relevel(gen, reference="WT"),
         treat = fct_relevel(treat, reference="saline"),
         inter = interaction(gen, treat)) %>%
  pull(inter)

Which gives me
[1] WT.saline WT.ab     QQ.saline QQ.ab
Levels: WT.saline QQ.saline WT.ab QQ.ab

This is close, but my desired output would be
[1] WT.saline WT.ab     QQ.saline QQ.ab
Levels: WT.saline WT.ab QQ.saline QQ.ab

In this case, the order of the tibble and the levels is the same, but this cannot be taken for granted, and the levels(inter) is what matter to me.

A: We could use lex.order to be TRUE in interaction
toy1 %>%
  mutate(gen = fct_relevel(gen, reference="WT"),
         treat = fct_relevel(treat, reference="saline"),
         inter = interaction(gen, treat, lex.order = TRUE)) %>%
  pull(inter)

-output
[1] WT.saline WT.ab     QQ.saline QQ.ab
Levels: WT.saline WT.ab QQ.saline QQ.ab

Or we may add a factor at the end with levels specified as unique values
toy1 %>%
  mutate(gen = fct_relevel(gen, reference="WT"),
         treat = fct_relevel(treat, reference="saline"),
          inter = interaction(gen, treat),
          inter = factor(inter, levels = unique(inter))) %>%
  pull(inter)

-output
[1] WT.saline WT.ab     QQ.saline QQ.ab
Levels: WT.saline WT.ab QQ.saline QQ.ab


text:
Q: USB keyboard is ignoring key presses in some very frustrating pattern I booted my laptop docked to a USB keyboard and external monitor.  I've used it in this setup very recently and it was fine.  Today, the USB keyboard is sometimes ignoring a key press.
It happened a couple of times when I hit Home.  But if I test it specifically, the key works fine.
I thought maybe I was hitting it wrong after adjusting from the smaller laptop keyboard.  But then it clearly dropped a few characters when I was starting to type something.

A: The problem is I have powertop.service enabled.  Enabling this means powertop --autotune runs at startup and enables most extra power-saving features.  It's very useful to improve the battery life.
Unfortunately this includes usb autosuspend on all (?) usb devices which are connected at the time.  Linux deliberately defaults to not enabling autosuspend on input devices, due to reports like this, including my report at the time on what was most likely the same keyboard.  (Logitech Internet 350).
Workaround
If you booted with the USB keyboard plugged in, just unplug it and then plug it back in again.  This clears the configuration set by powertop --autotune.
A more "correct" solution would be to go through each command recommended by powertop, and create a boot script which runs all of them except the USB autosuspend one.


text:
Q: C++ unicode strings - the basic_strings know nothing about Unicode? I see here that the C++ standard library now has typedefs of std::basic_string like u8string and u16string, but I don't see any member functions or algorithms that know much of anything about Unicode.
Let's say I want to iterate over the "grapheme clusters" in a string stored as UTF-8. These are the things that humans view as "characters", even though they may be multiple bytes or even multiple 32bit code units (like emoji flags ). Am I right that std::u8string has nothing for that and I need to use a library like ICU?
It appears the substr member function would split a UTF-8 or UTF-16 character in half, so again I need to use ICU or something to make sure I don't do that.
Correct?

A: Unfortunately, yes. C++ unicode support is still very basic.

A:
Am I right that std::u8string has nothing for that and I need to use a library like ICU?
It appears the substr member function would split a UTF-8 or UTF-16 character in half, so again I need to use ICU or something to make sure I don't do that.

Yes, you are correct, on both counts.  The standard C++ library has no concept of Unicode codepoints/graphemes, only of encoded codeunits stored in individual char/wchar_t/char16_t/char32_t elements of strings.


text:
Q: html form methode=post action=URL i make a form and my submit button does not work.

<!DOCTYPE HTML>

        <form id="contact-form" method="post" action="http://www.example.com/?lang=en&p=send" role="form">

                  Firstname *
                  <input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">

                  Lastname *
                  <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">

                  Subject *
                  <input id="form_subject" type="text" name="subject" class="form-control" placeholder="Please enter your Subject *" required="required" data-error="Subject is required.">

                  Message *
                  <textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please,leave us a message."></textarea>

                <input type="submit" class="btn btn-success btn-send" value="Send message">

* These fields are required.

        </form>

when i put the relative address from my send file in the action part than it works.
is it possible on my way?
i include the content part via php in my index.php. I try to open the send.php in my index.php
Thanks!

A: If i got you right you want to handle the action of the form on the same page. So you have to set the action to:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">

And in the PHP part you have to check if the form was submitted. So something like:
<?php
if(isset($_POST['form_message'])){ //check if form was submitted

}
?>


text:
Q: Standart deviation of a hypergeometric distribution So, here is the problem, I have 40 green marbles and 60 red marbles. 20 marbles are taken without replacement. Determine the standard deviation of the number of green marbles taken.
I used the formula for the variance in a hypergeometric distribution:
$$n\left(\frac{K}{N}\right)\left(\frac{N-K}{N}\right)\left(\frac{N-n}{N-1}\right)$$
and got:
$$20\left(\frac{40}{100}\right)\left(\frac{60}{100}\right)\left(\frac{80}{99}\right)= 3.\bar{87} $$
I took the root of this and got $\sigma \approx 1.97$ but there is no such answer for me to mark, did I make a mistake? If yes where?
Answering options:
a)0.2329
b)8
c)10.69
d)59.878787...
e)7.74


text:
Q: iOS YouTube api v3: uploaded video url I want to get the URL of the YouTube uploaded video. It is possible to get the YouTube uploaded video URL in api-v2 using (GDataEntryYouTubeVideo *)videoEntry;.
Can anyone please tell me how to do the same in api-v3

A: Follow the method in this sample:
- (void)uploadPrivateVideoWithTitle:(NSString *)title description:(NSString *)description commaSeperatedTags:(NSString *)tags andPath:(NSString *)path

A: There no direct way of getting url, following is the answer!
self.uploadFileTicket = [service executeQuery:query completionHandler:^(GTLServiceTicket *ticket,GTLYouTubeVideo *uploadedVideo,NSError *error) {
                   NSString *videoURL = [NSString stringWithFormat:@"%@%@", @"http://www.youtube.com/watch?v=", uploadedVideo.identifier];
}


text:
Q: I deleted the partitions on windows disc manager to remove Ubuntu I deleted the partitions on the windows disc manager to remove ubuntu from dual boot. First time I restarted the PC, grub opened on switching on the PC.I typed exit and windows opened. I then did some random stuff like opening the UIFI and BIOS and making windows as first boot priority and tried restarting the PC a few times and now grub is not opening.
My main problem is I am not sure that I have removed Ubuntu and grub entirely from my PC. I want to make sure that they don't exist on my computer without doing any harm to Windows OS. And then I want to install Kali Linux for dual boot. I am just afraid that I wrecked my computer. Please help me here.


text:
Q: Star Rating System label highlighting based on check box I have a star rating system which is built with the help of checkboxes(Hidden).
The rating system has N/A as a first selection option.
Now I can show N/A or No parking sigh as red color when selecting the label.
But I am unable to change the color of this N/A when I select other stars.
because when I rate one star or 3.5 star rating, the red is also highlighted which was part of the previous CSS mechanism which I had just changed the 1st star to N/A option.
How can I keep the red color selection if I select N/A, also when I select any stars I should show the N/A in a different color or gray(unselected) because it's not part of star ratings but just N/A.
.rate {
        display: inline-block;
    }
    .rate>input {
        display: none;
    }
    .rate>label {
        float: right;
        color: #b4b3b3;
    }
    .rate>label:before {
        display: inline-block;
        font-size: 3em;
        padding: .3rem .2rem;
        margin: 0 5px;
        cursor: pointer;
        font-family: FontAwesome;
        content: "\f005 ";
    }
    .rate>label:last-child:before {
        content: "\f05e";
        //color: #cc5858;
        margin-right: 10px;
        padding-right: 20px;
        border-right: .08em solid #4a90e2;
    }
    .rate .half:before {
        content: "\f089 ";
        position: absolute;
        padding-right: 0;
    }
    input:checked~label,
    label:hover,
    label:hover~label {
        color: #ffcd00;
    }
    input:checked+label:hover,
    input:checked~label:hover,
    input:checked~label:hover~label,
    label:hover~input:checked~label {
        color: rgb(255, 224, 85);
    }
    input:checked~label:last-child:before {
        color: #cc5858;
    }
    input:checked+input:last-child:not(:checked)~label:last-child {
        color: #14ff4e !important;
    }

Angular Code below
<fieldset class="rate" id="rate-{{controlIndex}}" [class.readonly]="readonly">
    <ng-container *ngFor="let star of ratings; let i = index">
        <input type="radio" id="rating-{{ratings.length-i-1}}-{{controlIndex}}" name="rating-{{controlIndex}}" [checked]="(star.id == rating)" />
        <label [class.half]="(i%2)==1" for="rating-{{ratings.length-i-1}}-{{controlIndex}}" (click)="updateRating(star.id)"></label>
    </ng-container> </fieldset>

*

*The image is for illustration purpose only


text:
Q: Using recursive CTE in SQL I have to find all the Countries that are 3 borders away from Germany

Country 1
Country 2
Border Length

Germany
France
10000

Spain
France
10000

Portugal
Spain
10000

Austria
Germany
10000

From the above table we can see that France and Austria are 1 Border away from Germany. Spain is 2 borders away from Germany (because German and Spain have France as their neighbor, hence we have to cross 2 borders to reach Spain). And Portugal is 3 borders away from Germany (here we have to cross France and Spain to reach Portugal).
Using recursive CTE in SQL how can I find all the countries which are 3 borders away from Germany ?
Note: A single country can be in any Column (Either Country1 column or in Country2 column).
WITH RECURSIVE THREE_BORDERS_AWAY AS (
    SELECT Country1, Country2, 1 AS BORDERS_AWAY
    FROM borders
    WHERE Country1 = "D" OR Country2 = "D"

    UNION ALL

    SELECT Country1, Country2, TBA.BORDERS_AWAY + 1
    FROM THREE_BORDERS_AWAY AS TBA
    WHERE BORDERS_AWAY < 3
)
SELECT * FROM THREE_BORDERS_AWAY

This is all I could come up with.

A: with cte_borders as (
select country1 as from_country, country2 as to_country from borders
union all
select country2 as from_country, country1 as to_country from borders),
cte_germany_neighboors (from_country, to_country, hops) as (
select from_country, to_country, 0
  from cte_borders
 where from_country = 'Germany'
union all
select b.from_country, b.to_country, c.hops+1
  from cte_borders b
  join cte_germany_neighboors c
    on c.to_country = b.from_country
 where c.hops < 4
   and b.from_country <> 'Germany')
select distinct
       from_country as country,
       min(hops) as hops
  from cte_germany_neighboors
 group by from_country
 order by 2;

country |hops|
--------+----+
Germany |   0|
Austria |   1|
France  |   1|
Spain   |   2|
Portugal|   3|


text:
Q: NodeJS WriteStream I am learning the NodeJS WriteStream. I cannot understand the effect of the res.end() function call bellow. What would happen if the res.end() call did not exists in the following example? I removed that, but did not any change and in both case the result returned to the client.
const fs = require("fs");
const server = require("http").createServer();

server.on("request", (req, res) => {
  const readable = fs.createReadStream("test-file.txt");
  readable.on("data", (chunk) => {
    res.write(chunk);
  });

  // Is the following piece of code really needed?
  readable.on("end", () => {
    res.end();
  });
});

server.listen(8000, "127.0.0.1", () => {
  console.log("Listening...");
});

A: In some scenarios the res.end is used to end the response , as it says , otherwise it would never stop.
And it may be used if the data being read is large , with async functions that need time to be executed , or with shell scripts with exports etc ..


text:
Q: Class hierarchy design, avoiding downcasts from base to derived class I am designing a DNS parsing library in C++. A DNS Packet has a set of standard fields followed by a list of Resource Records that again has a set of standard fields followed by a RData field. The RData field is parsed based on the type field. Now, I specify a hierarchy for DNSRData, to handle various types. The code looks like something like this:
class DNSRData {
  virtual void ToString() = 0;
  virtual void Parse() = 0;
}

class DNSRData_A : public DNSRData {
  void ToString();
  void Parse();
  uint32_t GetIP();
}

class DNSRData_CNAME : public DNSRData {
  void ToString();
  void Parse();
   const char* GetAlias();
}

class DNSResourceRecord {
  /* Standard Fields
   ..... */
  int      type_; // Specifies the format for rdata_
  DNSRData *rdata_;
}

class DNSPacket {
  /* Standard Fields
  ....*/
  vector<DNSResourceRecord *> rr_list_;
}

Now this is the issue I have, each DNSRData record might have different fields. I do not want to add accessors for all the fields in the Base class, as they are present in some derived class and not in others e.g. IP address is present only in DNSRData_A and not in any other.
So, when I want to perform any operations on the DNSRData, I lookup the type and perform a downcast from DNSRData* to DNSRData_A*.
DNSRData *rdata = packet->GetResourceRecord().front(); //not really necessary for this example
if(resource_record.type == RR_CNAME) {
  DNSRData_CNAME *cname = (DNSRData_CNAME*)rdata;
}

This can cause tons of issues later on, and as we add more types it is quickly becoming an unholy mess. Any ideas on how to solve this problem without adding all accessors to the Base class ?
EDIT:
Some more context, this is part of a high performance DNS trace parse library. A lot of the operations are done as we see packets on the wire. So, what would be an operation that messes up the design, lets say we get a DNSPacket and we parse it now we want to decide how to process it further based on the type.
if(type == RR_CNAME) {
  DNSRData_CNAME *cname = dynamic_cast<DNSRData_CNAME*>(&rdata);
  char *alias = cname->GetAlias();
}else if (type = RR_A) {
  DNSRData_A *a = dynamic_cast<DNSRData_A*>(&rdata);
  uint32_t ip = a->GetIP();
}

As you see there is a downcast involved, from the base type RData to a more specific RData type. I want to avoid this downcast and use maybe a design pattern to solve this problem.

A: if i understand you correctly i think that the Visitor pattern is what you are looking for
Visitor pattern.
class GetInfoVisitor
  {
    void visit(DNSRData_A* a)
    {
        uint32_t ip = a->GetIP();
    }
    void visit(DNSRData_CNAME * cname)
    {
        char *alias = cname->GetAlias();
    }
  }

class DNSRData
{

    void action(Visitor& visitor)
    {
        visitor.visit(this);
    }
}

int main()
{
 ...
 GetInfoVisitor getInfoVisitor;
 DNSRData *rdata = packet->GetResourceRecord().front();
 rdata->action(getInfoVisitor);
}

A: First off, you might want to consider dynamic_cast, rather than the c style cast you employed in the example. This will allow you to check whether the cast was successful, which can avoid potentially serious errors.
Second, I think more context might be needed to answer your question. Almost invariably, good use of a design pattern can allow you to avoid this situation to start with. Given the information at hand though, I'd suggest perhaps even creating an abstract virtual function called operate in the parent class that can then be overridden to implement the special logic of interest. This would allow you to consider the problem anytime someone overrides the base class, so the code is more maintainable, and would save time because of avoiding looking up the type.


text:
Q: Wordpress erro: "Sem permissão suficiente para acessar essa página" Meu site Wordpress com WooCommerce mostra a seguinte mensagem quando informo o login de acesso:

.. "Sem permissão suficiente para acessar essa página".

O que eu já tentei, sem sucesso:

*

*Deletar aquele arquivo de tradução na pasta languages como informa alguns fóruns.

*Colocar no root o arquivo force-upgrade.php.

Se puderem me ajudar agradeço muito!

A: Consegui resolver! Segue a solução encontrada para o meu problema.

*

*Entrar no phpMyadmin/, entrar no banco de dados usado.

*Encontrar a tabela wp_usermeta e deixar as seguintes linhas exatamente com esse código:

*

*wp_capabilities deverá ser:
a:1:{s:13:"administrator";s:1:"1";}

*wp_user_level deverá ser:
10

A: Isto tem a ver com o código gerado por:  http://api.wordpress.org/secret-key/1.1/
Para corrigir o erro basta gerar outra chave e colocar no wp-config.php, pronto tudo volta a funcionar normalmente da forma mais fácil e simples possível.


text:
Q: Is every function that is continuous and bounded on a certain interval, is integrable in that interval? Maybe its a stupid question, sorry.
The question i ask my self is if every integral of a function, where the function is bounded and continuous on the interval of the integral than i can conclude that the function is integrable in that interval?

*

*The question is asked from the point of view of improper integrals.

Divide it to two:

*

*Intervals of the form $[a,b)$

*Intevals of the form $[a,\infty)$ - This is the part where i think i have a problem, see below.
*For intevals of the form $[a,b]$ its by definition integrable at that interval -  for continuous functions

What i think:
For the first case: $[a,b)$ we can expand the interval to $[a,b]$, in that interval the function is continuous and bounded except, maybe, to finite number of points, therefore we can conclude its integrable.
For the second case and more problematic, $[a,\infty)$ namely: $\int_{a}^{\infty}f(x)dx$  can i prove it or is it even a false claim?
Thanks for the help.

A: In the case of intervals of the type $[a,b)$, you are right: extende $f$ to $[a,b]$ putting, say, $f(b)=0$. The this new function is bounded and it has a single point at which it is discontinuous, at most. So, yes, it will be integrable.
But for intervals of the type $[a,\infty)$ this doesn't work: the integral $\int_a^\infty1\,\mathrm dt$ doesn't converge.


text:
Q: Reading filenames as part of a loop in C++ I am attempting to prompt for, and read, one file after another. The following code does not wait for the second file name to be entered and I'm not sure why.
do
  {
        cout << "Please enter a filename: ";
        getline(cin, fileName);

        fileStream.open(fileName);

        if (fileStream.fail())
          cout << "File Not Found!" << endl;
        while (fileStream.get(ch))
        {
          ch = convertToLowerCase(ch);
          index = ch - 'a';
          counter[index]++;
        }

        for (int i = 0; i < 26; i++)
        {
            cout << char(i + 'a') << " occurs " << setw(5) << counter[i] << " times." << endl;
        }

      cout << "Would you like to read another file: ";
      cin >> ans;
  }  while (ans != 'q' || ans != 'Q');

Ideally, it would process one file, then prompt for another, process it, prompt, etc. until the user chose to quit.

A: The line while (ans != 'q' || ans != 'Q'); will always evaluate to true, regardless of the char value. Even if ans = 'q', ans != 'Q', so the expression evaluates to true.
Change the line to:
while (ans != 'q' && ans != 'Q');


text:
Q: AbstractHttpMessage getParams().setParameter construct depcrcated ~ How to modernize? I am working to modernize old legacy code, and while doing that ran into some deprecated constructs that I can't figure out how to handle. They all look somewhat like this:
        HttpPost oauthVerificationRequest = new HttpPost(authURL);
        oauthVerificationRequest.getParams().setParameter(OAUTH_TOKEN_KEY, oauthToken);
        HttpResponse oauthVerificationRequestResponse = client.getHttpClient().execute(oauthVerificationRequest);

There, my IDE complains that both getParams() as well as setParameter is deprecated.
The thing is, written as it is like this, I understand exactly what is happening. The deprecated line sets the value of the parameter with the key OAUTH_TOKEN_KEY of the request to the value of oauthToken, and probably creates it if it doesn't exist.
However, even knowing that this is what is supposed to happen in this line, I have been unable to find a way to write this line in a modern way. I've tried to figure it out, but the new way of constructing a AbstractHttpMessage simply confuses me.
Since I learn best by examples, could someone please provide me with a "translation" of the above code to the new logic?

A: Okay, once again it seems that writing down my thoughts as a question helped get my mind down on the right track to find the solution. So to answer my own question, the correct way to write above statement in the new logic would be:
URIBuilder oauthVerificationRequestBuilder = new URIBuilder(authUrl);
oauthVerificationRequestBuilder.setParameter(OAUTH_TOKEN_KEY, oauthToken);
HttpPost oauthVerificationRequest = new HttpPost(oauthVerificationRequestBuilder.build());
HttpResponse oauthVerificationRequestResponse = client.getHttpClient().execute(oauthVerificationRequest);

So basically, you first create a builder, then set the parameters inside the builder, and then create the request using builder.build() as its parameter.
Bonus Question:
Is there also a way to get the addHeader() modification into the builder? Because right now, the entire construct looks like this for me, and it feels kinda inconsistent to use the builder for the parameters, and then slapping the header on top of the request the "old fashioned" way:
        URIBuilder oauthVerificationRequestBuilder = new URIBuilder(authUrl);
        oauthVerificationRequestBuilder.setParameter(OAUTH_TOKEN_KEY, oauthToken);
        oauthVerificationRequestBuilder.setParameter(OAUTH_VERIFIER_KEY, oauthVerifier);
        oauthVerificationRequestBuilder.setParameter(AUTHORIZE_KEY, VALUE_STRING_TRUE);
        HttpPost oauthVerificationRequest = new HttpPost(oauthVerificationRequestBuilder.build());
        oauthVerificationRequest.addHeader(CONTENT_TYPE_KEY, CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED_UTF_8);

A: Googling "java httppost" gives a link to the documentation. Looking for getParams() in the docs, shows that it is inherited from AbstractHttpMessage and another google search found the docs for that class. That docs explains what to do instead of using the deprecated method:

Deprecated. (4.3) use constructor parameters of configuration API provided by HttpClient

I hope this helps some future reader. Good libraries will document what the suggested replacement is for deprecated methods. It's always a good idea to consult the documentation for these suggestions.

A: It's very simple by http-request built on apache http API.
HttpRequest httpRequest = HttpRequestBuilder.create(
  ClientBuilder.create().build();
)
.build();

Response response = httpRequest.target(authURL)
.addParameter(OAUTH_TOKEN_KEY, oauthToken)
.addParameter(ANOTHER_PARAM, "VALUE")
.addHeader(ANY_HEADER, "VALUE")
.post();

Dependency
<dependency>
  <groupId>com.jsunsoft.http</groupId>
  <artifactId>http-request</artifactId>
  <version>2.2.2</version>
</dependency>


text:
Q: Installing an npm module globally...and then node not being able to find it I install this module called zmq with npm install -g zmq
Say I am in a new directory and I create a simple node.js file:
//test.js
var zmq = require('zmq');
console.log(zmq);

...if I run this, it will not be able to find the zmq package, even though I installed it globally. In order for the script to work, I have to run npm install zmq without the -g flag, which creates a node_modules folder in the same directory. I don't want that node_modules folder there.
I am failing to see the purpose of the -g flag, since none of my node programs seem to run without a node_modules folder.
I am on a Mac, but I have had the same problem on Windows and Linux.
What am I missing?

A: From npm's website:

*

*Local install (default): puts stuff in ./node_modules of the current package root.

*Global install (with -g): puts stuff in /usr/local or wherever node is installed.

*Install it locally if you're going to require() it.

*Install it globally if you're going to run it on the command line.

It's built this way so that each project can maintain separate dependencies and you don't have any issues trying to figure out which version goes with which project at a global level.
I'm not sure there's a way to do what you want it to do, and I don't think it would be recommended, even if there was.
Hope this helps!


text:
Q: Get the message from Azure Service Bus whenever needed Is it possible to retrieve message whenever needed in my application?
All I need is to not declare any handle who accept messages when there is a message in Queue (this I can implement using QueueClient) because I want to process one message at a time. Once successfully processed single message then only I need another message from Queue.
Is this possible with Service Bus?
Thanks in advance!

A: Service bus has this property of "Message Deferral", Would you be OK to defer message till you complete processing current one ?
Message deferral
When a queue or subscription client receives a message that it is willing to process, but for which processing is not currently possible due to special circumstances within the application, the entity has the option to defer retrieval of the message to a later point. The message remains in the queue or subscription, but it is set aside.

A: RegisterSessionHandler has a property  MessageWaitTimeout which allows you to wait to receive a message.
In your case if are sure about the time to process a message, then you can specify this property which will give you enough time process it. Next message will only received after the specified time.
Using this you can delay the retrieval of next message using RegisterSessionHandler.


text:
Q: How to change the request header limitation I launched the node express on my localhost:3000..
**curl -H 'samlresponse:12323' -v http://localhost:3000 , returns data correctly.
but if I tried following...
curl -H 'samlresponse:{here is the entire samlresponse, it's very long..almost 20k..}' -v http://localhost:3000
The server always return "Empty reply from server", is there a way to passby or fix this issue?

A: Source Code of node at github says:
/* Maximium header size allowed. If the macro is not defined
 * before including this header then the default is used. To
 * change the maximum header size, define the macro in the build
 * environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
 * the effective limit on the size of the header, define the macro
 * to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
 */
#ifndef HTTP_MAX_HEADER_SIZE
# define HTTP_MAX_HEADER_SIZE (80*1024)
#endif

So, you probably need to rebuild node from source to surpass the limit of 80*1024. But, personally I think that, it is large enough for a header, and you should re-evaulate whether your statergy is correct.


text:
Q: How to re-sync AWS RDS read replica Is there a way to fix a read replica that has stopped syncing with the master database?  I am already in the process of deleting it and creating a new one since I could not find this answer, but it would be nice to know if it happens again.
The database(s) is a MySQL database with Innodb tables.

A: The principle behind MySQL replication is simple: if you start with two identical data sets, and every time you change one, you change the other, then the two data sets will remain identical.  That's how MySQL replication works -- you start with two identical servers, either completely blank or with one being an exact snapshot of the other, and replication just executes the same thing on both servers.
Replication is done via the binary log ("binlog"), which captures all changes to the master.  In standard MySQL asynchronous replication -- as used in RDS -- the replica has two purpose-specific threads, the I/O thread that connects to the master and captures the replication events from the master's binlog and writes them to a temporary holding area called the relay log, and the SQL thread that reads from the relay log and applies the changes to the replica.
On the replica, the query SHOW SLAVE STATUS; will tell you whether these two threads are running, or not.  If they are running, the replica is healthy, though it might be behind the master, as evidenced by the value Seconds_Behind_Master that you'll also find in the output from that query.  Otherwise, you'll find the error that has been encountered, causing one or the other threads to stop.
In theory, a MySQL replica will never go out of sync unless one of three things happens:

*

*you do something you shouldn't, to make the replica inconsistent with the master -- such as making the replica writable, and writing to it.

*there's a bug in the MySQL source code that causes inconsistency

*the replica is disconnected from the master for a sufficiently long period of time such that the master has already discarded some of the replication events that the replica has never seen.

The first issue will cause the SQL thread to halt because it tries to apply a nonsense change -- typically deleting a row that doesn't exist, updating a row that doesn't exist or doesn't match, inserting a row that's already present, etc.
The second issue could cause a problem with either the IO thread or the SQL thread but these should be rare.
The last issue will cause the IO thread to halt because it remembers where it left off on the master, and if no binary log file is available on the master at that point, it is at an impasse.  RDS is supposed to prevent this by holding logs on the master until all managed replicas have captured them.
So, the general answer is that you can fix a MySQL read replica by bringing all of its data into exactly the state that it should be in, based on the state of the master at the point in time where the replication SQL thread is currently pointing, in the relay logs.
That's a little bit trickier in RDS because you don't have the SUPER privilege, but it's still possible.  Still...
tl;dr: broken replication is only a symptom -- you have to figure out what the actual problem is.
You need to be able to identify what's gone wrong, and take steps to correct it.  The problem is, when replication stops, unless you have a very clear understanding of exactly what happened, you don't actually know just how bad things might be on the replica.
Thinking back to the principle mentioned above -- start with two identical data sets, and every time you change one, change the other -- the next thing to note is that MySQL does not have any built-in mechanisms for ensuring consistency in the absence of actual replication errors.  Two servers can be dramatically divergent but replication will happily continue until the SQL thread encounters something that it cannot replicate.  You need a third party utility that can compare the data on the two servers and call out any discrepancies.
If you clearly understand what went wrong, you can temporarily make the replica writable (using the parameter group setting for the read_only system variable), make the corrective changes, and restart replication.  On RDS, you can only restart at the current event pointer by rebooting the replica, since you don't have the SUPER privilege, or you can bring the replica to the state it should have been in after the problematic event replicated, and then use the workaround they provide for that, using CALL mysql.rds_skip_repl_error();.  Do not use this without understanding what it does -- specifically, it ignores the failure and moves on to the next event, absolutely leaving your replica in an inconsistent state unless you have manually brought the replica consistent.  It should be reserved for emergencies only, when keeping the replica current is more important than keeping the replica correct, because skipping an error essentially guarantees more errors in the future.
Repairing a replica is not a trivial exercise.  It's a task for an experienced DBA.  In RDS, the best option is typically to discard the replica and create a new one, but since replication errors should never happen -- this is not something you should ever have to do.  If you do, you need to discover why.