text:
Q: Array Processing logic correction I have an array [1,2,4,5,1,7,8,9,2,3]
and i would like it to generate all subset which sum of values are less than 10
current result  [[1,2,4],[5,1],[7],[8],[9],[2,3]]
expected result [[4,5,1],[9,1],[8,2],[3,7],[1,2]]
that is what i did
var a = [1,2,4,5,1,7,8,9,2,3], tempArr = []; tempSum = 0, result = [];
for (var i = 0;i< a.length; i += 1 ) {
  tempSum+=a[i];
  tempArr.push(a[i]);
  if((tempSum+a[i+1])>10) {
     result.push(tempArr);
     tempSum = 0;
     tempArr = [];
  } else if (i == a.length-1 && tempArr.length > 0) { // if array is [1,2,3]
    result.push(tempArr);
  }
}

but it gives me [[1,2,4],[5,1],[7],[8],[9],[2,3]]  and it has 6 subset, but i expect to get [[4,5,1],[9,1],[8,2],[3,7],[1,2]] which has 5 subset.

A: Below logic is in JavaScript :-
var limit = 10;
var  arr = [1,2,4,5,1,7,8,9,2,3];
arr.sort();
var ans = new Array ( );
while(arr.length >0){
    var ts = arr[arr.length-1];
    arr.splice(arr.length-1 , 1);
    var ta= new Array ( );
    ta.push(ts);
    var x = arr.length-1;
    while(x>=0){
        if(ts + arr[x] <= limit){
            ts = ts + arr[x];
            ta.push(arr[x]);
            arr.splice(x , 1);
        }
        x= x-1;
    }
        ans.push(JSON.stringify(ta));
}
alert(ans);

It is Giving Output as required .

[9,1],[8,2],[7,3],[5,4,1],[2]

A: I have removed duplicates then added maxSum parameter to combine function to generate all subset which have those conditions and then sorted subsets by sum of the values and sliced them.
You could change parameters to fit it for your problem.

var arr = [1,2,4,5,1,7,8,9,2,3]
MAX_SUM = 10,
MIN_SUBSET_LEN = 2,
RESULT_LEN = 5;

//remove duplicates
var uniqeSet = arr.filter(function(value, index){
  return this.indexOf(value) == index
},arr);

// a function to get all subset which
// their length are greater than minLength and
// sum of values are little than maxSum
var combine = function(sourceArr, minLength, maxSum) {
    var fn = function(n, src, got, all, sum) {
        if(sum <= maxSum){
          if (n == 0) {
            if (got.length > 0) {
                all.push({arr:got,sum:sum});
            }
            return;
          }
          for (var j = 0; j < src.length; j++) {
            var tempSum = sum
            fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all, sum + src[j]);
          }
        }
        return;
    }

    var all = [];
    for (var i = minLength; i < sourceArr.length; i++) {
        fn(i, sourceArr, [], all, 0);
    }
    return all;
}

var result = combine(uniqeSet, MIN_SUBSET_LEN, MAX_SUM);

var sortedSliced = result.sort(function(a1, a2){
  return a2.sum - a1.sum;
}).slice(0, RESULT_LEN).map(function(m){return m.arr;});

console.log(JSON.stringify(sortedSliced));


text:
Q: Add NavigationController in class not in appdelegate how to add the navigationcontroller in viewDidLoad method of any class for their next class, i have not added it in the starting in appdelegate .

A: YourViewController *report = [[YourViewController alloc]  init]; // create Object of YourViewController

UINavigationController *navigationController = [[UINavigationController alloc]initWithRootViewController:report]; // add YourViewController as root view controller of UINavigationController

[self presentModalViewController:navigationController animated:YES];

redpajama_set_name: RedPajamaStackExchange


text:
Q: javascript syntax for parameters in the context of rails 6 packs Action: a javascript action attempting to retrieve data based on two parameters, a user-input one and an issuing page parameter.
whereas in the past something like the following would work:
<%= javascript_tag do %> chart.data = data_<%=j params[:nation_id] %>; <% end %>

now with the javascript being 'packed', the compilation of syntax like <%=j params[:nation_id] %> does not work and returns :
/search.json?nation_id=%22%3C%=j%20params[:nation_id]%20%%3E%22&q=mi

modifying the packs/muni.js file as follows, also does not generate a proper url for the search function
  var options = {
    url: function(phrase) {
      return '/search.json?nation_id="#{params[:nation_id]}"&q=' + phrase;
    },
    getValue: "name",
  };

returning
/search.json?nation_id=%22

the page is set with  /new?top%5Bnation_id%5D=1&commit=Set
How does the javascript pack need to be written?

A: Javascript pack is not rendered for each request/visitor - whole point is that it is packed once per deploy and is the same for all (except for when you have several packs, dynamic module loading and other advanced techniques, but still code is not changed per request). In fact, older method with asset pipeline is very similar in this aspect.
Do not try using ruby inside the pack, but instead think of a way to pass the parameter to the js code.
For example, you can pass it via a adding some html tag an querying it from javascript:
In view:
<meta name="nation_id" content="<%= params[:nation_id] %>" />

in js:
nation_id = document.querySelector('meta[name="nation_id"]').content;
return `/search.json?nation_id=${nation_id}&q=${phrase}`;

PS. also you might need to escape your phrase with encodeURIComponent


text:
Q: OpenCV triangulatePoints varying distance I am using OpenCV's triangulatePoints function to determine 3D coordinates of a point imaged by a stereo camera.
I am experiencing that this function gives me different distance to the same point depending on angle of camera to that point.
Here is a video:
https://www.youtube.com/watch?v=FrYBhLJGiE4
In this video, we are tracking the 'X' mark. In the upper left corner info is displayed about the point that is being tracked. (Youtube dropped the quality, the video is normally much sharper. (2x1280) x 720)
In the video, left camera is the origin of 3D coordinate system and it's looking in positive Z direction. Left camera is undergoing some translation, but not nearly as much as the triangulatePoints function leads to believe. (More info is in the video description.)
Metric unit is mm, so the point is initially triangulated at ~1.94m distance from the left camera.
I am aware that insufficiently precise calibration can cause this behaviour. I have ran three independent calibrations using chessboard pattern. The resulting parameters vary too much for my taste. ( Approx +-10% for focal length estimation).
As you can see, the video is not highly distorted. Straight lines appear pretty straight everywhere. So the optimimum camera parameters must be close to the ones I am already using.
My question is, is there anything else that can cause this?
Can a convergence angle between the two stereo cameras can have this effect? Or wrong baseline length?
Of course, there is always a matter of errors in feature detection. Since I am using optical flow to track the 'X' mark, I get subpixel precision which can be mistaken by... I don't know... +-0.2 px?
I am using the Stereolabs ZED stereo camera. I am not accessing the video frames using directly OpenCV. Instead, I have to use the special SDK I acquired when purchasing the camera. It has occured to me that this SDK I am using might be doing some undistortion of its own.
So, now I wonder... If the SDK undistorts an image using incorrect distortion coefficients, can that create an image that is neither barrel-distorted nor pincushion-distorted but something different altogether?

A: The SDK provided with the ZED Camera performs undistortion and rectification of images. The geometry model is based on the same as openCV :

*

*intrinsic parameters and distortion parameters for both Left and Right cameras.

*extrinsic parameters for rotation/translation between Right and Left.

Through one of the tool of the ZED ( ZED Settings App), you can enter your own intrinsic matrix for Left/Right and distortion coeff, and Baseline/Convergence.
To get a precise 3D triangulation, you may need to adjust those parameters since they have a high impact on the disparity you will estimate before converting to depth.
OpenCV gives a good module to calibrate 3D cameras. It does :
-Mono calibration (calibrateCamera) for Left and Right , followed by a stereo calibration (cv::StereoCalibrate()). It will output Intrinsic parameters (focale, optical center (very important)), and extrinsic (Baseline = T[0], Convergence = R[1] if R is a 3x1 matrix). the RMS (return value of stereoCalibrate()) is a good way to see if the calibration has been done correctly.
The important thing is that you need to do this calibration on raw images, not by using images provided with the ZED SDK. Since the ZED is a standard UVC Camera, you can use opencv to get the side by side raw images (cv::videoCapture with the correct device number) and extract Left and RIght native images.
You can then enter those calibration parameters in the tool. The ZED SDK will then perform the undistortion/rectification and provide the corrected images. The new camera matrix is provided in the getParameters(). You need to take those values when you triangulate, since images are corrected as if they were taken from this "ideal" camera.
hope this helps.
/OB/

A: There are 3 points I can think of and probably can help you.

*

*Probably the least important, but from your description you have separately calibrated the cameras and then the stereo system. Running an overall optimization should improve the reconstruction accuracy, as some "less accurate" parameters compensate for the other "less accurate" parameters.

*If the accuracy of reconstruction is important to you, you need to have a systematic approach to reducing it. Building an uncertainty model, thanks to the mathematical model, is easy and can write a few lines of code to build that for you. Say you want to see if the 3d point is 2 meters away, at a particular angle to the camera system, and you have a specific uncertainty on the 2d projections of the 3d point, it's easy to backproject the uncertainty to the 3d space around your 3d point. By adding uncertainty to the other parameters of the system then you can see which ones are more important and need to have lower uncertainty.

*This inaccuracy is inherent in the problem and the method you're using.

*

*First if you model the uncertainty you will see the reconstructed 3d points further away from the center of cameras have a much higher uncertainty. The reason is that the angle <left-camera, 3d-point, right-camera> is narrower. I remember the MVG book had a good description of this with a figure.

*Second, if you look at the implementation of triangulatePoints you see that the pseudo-inverse method is implemented using SVD to construct the 3d point. That can lead to many issues, which you probably remember from linear algebra.

Update:

But I consistently get larger distance near edges and several times
  the magnitude of the uncertainty caused by the angle.

That's the result of using pseudo-inverse, a numerical method. You can replace that with a geometrical method. One easy method is to back-project the 2d-projections to get 2 rays in 3d space. Then you want to find where the intersect, which doesn't happen due to the inaccuracies. Instead you want to find the point where the 2 rays have the least distance. Without considering the uncertainty you will consistently favor a point from the set of feasible solutions. That's why with pseudo inverse you don't see any fluctuation but a gross error.
Regarding the general optimization, yes, you can run an iterative LM optimization on all the parameters. This is the method used in applications like SLAM for autonomous vehicles where accuracy is very important. You can find some papers by googling bundle adjustment slam.


text:
Q: how to use Jsoup in site that has lazyload scrollLoader.js I have a problem about jsoup because of lazyload scrollLoader.js
I reach site with java code, i have listed only 50 image name by jsoup.But when scroll down on site ,lots of image loads continously. My question is that, is it possible to post image amount into url that uses with Jsoup.connect()  to get all image from the site?
here is site : http://www.logowik.com
And this is the usege of script in the site :
<script type="text/javascript">

            $(document).ready(function(e) {
                CalculateColumns();
                recordCount = 50;
                groupID = "0";
                catID = "0";
                query = "";
                userEntry = "";
                groupInterval = "0";
                AddEvent(window, "resize", CalculateColumns);
                document["scrollLoader"] = new scrollLoader({evn : getGrids, seize : 1});
                document["scrollLoader"].DoScroll();
                addLogoClickEvent();
            });

    </script>

I post this parameters with url like :
http://www.logowik.com/index.php?g=1&groupID=1&catID=0
with this url I get 50 image,because of recordCount = 50 in script. but i cannot post this parameter to url.
For getting 100 images, I try this url:  http://www.logowik.com/index.php?recordCount=100&g=1&groupID=1&catID=0
but it doesn't effect.
Thanks

A: Use firebug or chrome dev tools network panel to see all the requests generated when loading the images, then just recreate them in jsoup.


text:
Q: Combining duplicate rows in Crystal Reports I posted this question already on another forum, but have not got any responses yet and requiring a solution quickly: https://answers.sap.com/questions/384242/combining-duplicate-lines-in-crystal.html
For various reasons to do with product numbering customization on our SAP B1 system, we can have no more than two of our standard items on a row in a sales order or invoice. All other items, such as accessories and non-numbered items we can put as many on a row as we want. To save any questions, this process cannot be avoided.
The issue is that this means we get some very strange looking invoices. For example if I sell 15 of our standard item 'A' and 15 of our standard item 'B' with 30 accessories to match, I can either bill out 15 lines each containing one 'A' and 15 lines each containing one 'B' then one line containing all the 30 accessories. Otherwise, I can bill out 7 lines each containing two of 'A', then one line containing the 15th A, then 7 lines each containing two of 'B', then one line containing the 15th B, and finally one line containing 30 accessories.
Is there any way that, in the case that an invoice contains rows with identical length, width, height and colour (or any other fields if it makes it easier), crystal can be configured to combine the rows into one and return the sum of the quantities and the sum of the prices in the relevant columns?
Added images below:


text:
Q: C - Missing .dll library when .exe is copied to another computer I used MySQL Connector C 6.1 api in C.
I linked all the header files, libraries etc in the Code blocks IDE and when I try to compile the program,it works and I am able to run the program. But when I copy the .exe file to another computer, a warning comes saying that libmysql.dll is missing. When I copy that libmysql.dll file along with the program,it works fine. But how to avoid that? Is there a way to make it run without copying .dll file?

A: If your program depends on a .dll (which stands for dynamic link library) then there is no way to run without that .dll being present on the system.  This is because there is code in the library that your program depends on.  An alternative would be to build your program with a static version of the library, a .lib file.


text:
Q: MS Access - Time Series Aggregation / Analysis Query MS ACCESS2010 - Trying to Count the number of trades made before certain intervals during the day (1pm, 2pm, 3pm, etc.) I have a table of all trades with their times but cannot figure out how to aggregate the data by the desired intervals on one sheet. I can create a query for each interval but there has to be something more efficient?

A: You can use the hour:
Select Hour([DateTimeField]), Sum([TradeField])
From YourTable
Group By Hour([DateTimeField])


text:
Q: ion-select showing three dots I am using ion-select in my app. But when i run it on the device, ion-select shows three dots in spite of having sufficient space.

My Code is
<ion-row *ngIf="item.type=='variable'">
  <ion-col>

Add

  </ion-col>
  <ion-col>
    <ion-item class="item">
      <ion-select placeholder="Size" interface="popover">
        <ion-option *ngFor="let items of item.attributes[0].options">
        {{items}}
        </ion-option>
      </ion-select>
    </ion-item>
  </ion-col>
</ion-row>

I have already tried using max-width:100% . ion-select works perfectly when i use it in new row. But i want to display it with other item in the same row.
Please help, i have been searching the net for the last 5-6 hours but no help.

A: Use text-wrap in ion-item or ion-select,it will wrap your select text.
<ion-row *ngIf="item.type=='variable'">
  <ion-col>

Add

  </ion-col>
  <ion-col>
    <ion-item class="item" text-wrap>
      <ion-select placeholder="Size" interface="popover" text-wrap>
        <ion-option *ngFor="let items of item.attributes[0].options">
        {{items}}
        </ion-option>
      </ion-select>
    </ion-item>
  </ion-col>
</ion-row>

Then if it is not working then give min-width to ion-select in css


text:
Q: MacBook Air problems after upgrading from Yosemite to High Sierra Today I installed macOS High Sierra after doing some research. Obviously it was a big mistake. I used it successfully for about an hour, then when I was online I unplugged my laptop and everything went kablooey. Like a blue screen for Macs. Staticky horizontal lines with constant flashing  - that was all I saw.
Made a little progress when I restarted holding down commandR. But the screen was split horizontally across the middle, always moving, so I could see the top choice in utilities which was recover but I couldn't choose it because I couldn't get to the button on the bottom. It was in the bottom half of the screen that was just lines.
Eventually the Utilities screen would just slowly fade out so I couldn't see it anymore. So I turned the machine off again. Also tried restarting my router because I read that errors were sometimes with Wi-Fi. No luck.
I WAS FINALLY ABLE TO FIX THIS!  I FOUND A KEYSTROKE COMBO ONLINE THAT ALLOWED ME TO HAVE THE BACKUP DRIVE (WHICH I'D USED JUST BEFORE THE FATAL UPGRADE) DO A RECOVERY.  I'M BACK TO YOSEMITE, AND VERY HAPPY!


text:
Q: Twitter Queries I'm trying to write a URL for Twitter's Search API.
The page says you can search for love or hate:
https://dev.twitter.com/docs/using-search
love OR hate    containing either "love" or "hate" (or both)

But I'm not seeing a way to do this.
It should be fairly simple:
http://search.twitter.com/search.json?q=%40twitterapi

is an example of a URL that searches for twitterapi. But how would I search for two terms? What's the operand for OR in this context?

A: Nevermind, it appears that %20OR%20 works in this context.


text:
Q: AngularJS service to store SEO metadata I'm followed this tutorial and tried to use the service for dynamic seo metadata.
https://weluse.de/blog/angularjs-seo-finally-a-piece-of-cake.html
However, run into an issue - Seems like the service is not accessable outside of controller's view.

Here is the service i'm trying to implement:
app.service('SeoMetaService', function() {

        var metaDescription = '';
        var metaKeywords = '';
        var title = '';
        return {
            metaDescription: function() { return metaDescription; },
            metaKeywords: function() { return metaKeywords; },
            title: function() { return title; },

            reset: function() {
                metaDescription = '';
                metaKeywords = '';
                title = '';
            },
            setMetaDescription: function(newMetaDescription) {
                metaDescription = newMetaDescription;
            },
            appendMetaKeywords: function(newKeywords) {
                for(var i=0;i<newKeywords.length;i++){
                        if (metaKeywords === '') {
                            metaKeywords += newKeywords[i];
                        } else {
                            metaKeywords += ', ' + newKeywords[i];
                        }
                }
            },
            setTitle: function(newTitle) { title = newTitle; }
        };
    });

usage in controller:
app.controller('WelcomeController',['$scope', 'SeoMetaService', function($scope, SeoMetaService) {
$(document).ready(function() {
    var keywords = ["bla bla","bla bla blah"];
    SeoMetaService.setTitle("title bla bla bla");
    SeoMetaService.setMetaDescription("description bla bla bla");
    SeoMetaService.appendMetaKeywords(keywords);

    console.log(SeoMetaService.metaDescription());
    console.log(SeoMetaService.metaKeywords());
});
}]);

on the main page (one-page-app), simplified:

    <title>{{SeoMetaService.title()}}</title>

    <meta name="description" content="{{ SeoMetaService.metaDescription() }}">
    <meta name="keywords" content="{{ SeoMetaService.metaKeywords() }}">
    <base href="/">

So the problem is - i thought that angular services are singletons.
But, after running the controller and setting the data, it doesn't appear in HTML.
How to fix/what to do?

A: I imagine that you defined the WelcomeController at level of View.
So SeoMetaService is visible only in the inner html present in the

.
You need to define the controller WelcomeController at level of  or , because SeoMetaService is accessible only inside the tag defining the controller WelcomeController.
Additionally you need to remove the reference to JQuery and expose the SeoMetaService in the $scope.
The code should be something like that.
The HTML:

<title>{{SeoMetaService.title()}}</title>

    <meta name="description" content="{{ SeoMetaService.metaDescription() }}">
    <meta name="keywords" content="{{ SeoMetaService.metaKeywords() }}">
    <base href="/">

The controller updated:
app.controller('WelcomeController',['$scope', 'SeoMetaService', function($scope, SeoMetaService) {

    var keywords = ["bla bla","bla bla blah"];
    SeoMetaService.setTitle("title bla bla bla");
    SeoMetaService.setMetaDescription("description bla bla bla");
    SeoMetaService.appendMetaKeywords(keywords);

    console.log(SeoMetaService.metaDescription());
    console.log(SeoMetaService.metaKeywords());

    // Added to the scope SeoMetaService
    $scope.SeoMetaService = SeoMetaService;

}]);

Note that you can change the content of SeoMetaService also in another controller, so for example changing a view you can update title, meta description and meta keywords reflecting the content of the new view.
Here is a possible example for the controller MyViewController
app.controller('MyViewController',['$scope', 'SeoMetaService', function($scope, SeoMetaService) {

    var keywords = ["xxx","yyy"];
    SeoMetaService.setTitle("title my view");
    SeoMetaService.setMetaDescription("description my view");
    SeoMetaService.appendMetaKeywords(keywords);

}]);

When you enter the view using the controller MyViewController the keywords, title, meta description and meta keywords will be updated.


text:
Q: How to animate a cube with images on their faces? From this code, how could I animate (speed given by the user) this cube at random so that each face shows me a different image.
EDIT(The idea is that the cube rotates at random and shows different images on each face, it is understood now :(
 $Graphics3D[
 GraphicsComplex[
 Tuples[{0, 1}, 3],
 MapThread[
 {Texture[
 Graphics[ImportString[ExportString[#1, "PDF"], "PDF"][[1, 1]],       Background -> #3]],
 Polygon[#2, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]} &,
{Characters["ABCDEF"],
 {{1, 2, 4, 3}, {1, 5, 6, 2}, {1, 3, 7, 5}, {8, 6, 5, 7}, {8, 7,
   3, 4}, {8, 4, 2, 6}},
 Table[Hue[i/6], {i, 6}]}
]
   ],
 Lighting -> "Neutral"]$

here some example image to put on the faces

enter link description here
enter link description here
enter link description here
enter link description here
enter link description here
enter link description here

A: Update 4: Rotations around x axis followed by rotations around y axis followed by rotations around z axis:
faces = Polygon[#, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0,  1}}] & /@
  {{1, 2, 4, 3}, {1, 5, 6, 2}, {1, 3, 7, 5}, {8, 6, 5, 7}, {8, 7, 3, 4}, {8, 4, 2, 6}};

images = Import /@
 {"https://images-na.ssl-images-amazon.com/images/I/51ZQiVNDYPL._SX425_.jpg",
  "https://images-na.ssl-images-amazon.com/images/I/51S7cvjbrqL._SX425_.jpg",
  "https://images-na.ssl-images-amazon.com/images/I/61acUMNLNvL._SX425_.jpg",
  "https://images-na.ssl-images-amazon.com/images/I/51xRMocaTKL._SX425_.jpg"};

{one, six} = Texture[Graphics[
      ImportString[ExportString[#1, "PDF"], "PDF"][[1, 1]],
      Background -> #2]] & @@@ Transpose[{{"1", "6"}, {Red, Yellow}}];
textures2 = Join[Texture /@ images, {one, six}];

Animate[Graphics3D[
  Rotate[GraphicsComplex[Tuples[{0, 1}, 3],Transpose[{textures2, faces}]], t,
   IdentityMatrix[3][[1 + Quotient[t, 2 Pi]]], {1, 1, 1}/2],
  Lighting -> "Neutral", SphericalRegion -> True,
  PlotRange -> {{-1/2, 3/2}, {-1/2, 3/2}, {-1/2, 3/2}},
  Boxed -> False], {t, Range[0, 6 Pi - Pi/120, Pi/120]}]

Update 3: Rotations by a random angle around a randomly selected axis:
Animate[Graphics3D[Rotate[GraphicsComplex[Tuples[{0, 1}, 3],
     Transpose[{textures, faces}]], t, RandomChoice[IdentityMatrix[3]]],
   Lighting -> "Neutral",  SphericalRegion -> True,  Boxed -> False],
 {t, RandomSample[Range[0, 2 Pi, Pi/60]]}]

frames2 = Table[Graphics3D[
    Rotate[GraphicsComplex[Tuples[{0, 1}, 3], Transpose[{textures, faces}]], t,
     RandomChoice[IdentityMatrix[3]]], Lighting -> "Neutral",
     SphericalRegion -> True,  Boxed -> False],
  {t, RandomSample[Range[0, 2 Pi, Pi/60]]}];

Export["cube2.gif", frames2]

Update 2: Rotating a cube with images on its faces:
faces = Polygon[#, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}] & /@
  {{1, 2, 4, 3}, {1, 5, 6, 2}, {1, 3, 7, 5}, {8, 6, 5, 7}, {8, 7, 3, 4}, {8, 4, 2, 6}};

images = Import /@
  {"https://images-na.ssl-images-amazon.com/images/I/51ZQiVNDYPL._SX425_.jpg",
 "https://images-na.ssl-images-amazon.com/images/I/51S7cvjbrqL._SX425_.jpg",
 "https://images-na.ssl-images-amazon.com/images/I/61acUMNLNvL._SX425_.jpg",
 "https://images-na.ssl-images-amazon.com/images/I/51xRMocaTKL._SX425_.jpg"};

{one, six} = Texture[Graphics[
      ImportString[ExportString[#1, "PDF"], "PDF"][[1, 1]],
      Background -> #2]] & @@@ Transpose[{{"1", "6"}, {Red, Yellow}}];
textures2 = Join[Texture /@ images, {one, six}];

Animate[Graphics3D[
  GraphicsComplex[Tuples[{0, 1}, 3], Transpose[{textures2, faces}]],
  Lighting -> "Neutral",
  ViewVector -> 6 { Cos[t], Sin[t], 3 Sin[t]/6 + 1/12},
  SphericalRegion -> True], {t, 0, 2 Pi, Pi/60}]

You can control the speed using the second and third buttons.
See also: this answer by halirutan to a related question
Update: Using some of the images from the links in OP:
images = Import /@
  {"https://images-na.ssl-images-amazon.com/images/I/51ZQiVNDYPL._SX425_.jpg",
 "https://images-na.ssl-images-amazon.com/images/I/51S7cvjbrqL._SX425_.jpg",
 "https://images-na.ssl-images-amazon.com/images/I/61acUMNLNvL._SX425_.jpg",
 "https://images-na.ssl-images-amazon.com/images/I/51xRMocaTKL._SX425_.jpg"};

{one, six} = Texture[Graphics[
      ImportString[ExportString[#1, "PDF"], "PDF"][[1, 1]],
      Background -> #2]] & @@@ Transpose[{{"1", "6"}, {Red, Yellow}}];

Just wrap your images with Texture (and add the missing 1 and 6):
textures2 = Join[Texture /@ images, {one, six}];

frames = Table[Graphics3D[GraphicsComplex[Tuples[{0, 1}, 3],
     Transpose[{RandomSample[textures2, 6], faces}]], Lighting -> "Neutral"], {30}];
ListAnimate[frames]

Original answer:
textures = Texture[Graphics[ImportString[ExportString[#1, "PDF"], "PDF"][[1, 1]],
      Background -> #2]] & @@@
   Transpose[{CharacterRange["A", "Z"], Hue[#/26] & /@ Range[26]}];

faces = Polygon[#, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}] & /@
  {{1, 2, 4, 3}, {1, 5, 6, 2}, {1, 3, 7, 5}, {8, 6, 5, 7}, {8, 7, 3, 4}, {8, 4, 2, 6}};

frames = Table[Graphics3D[GraphicsComplex[Tuples[{0, 1}, 3],
    Transpose[{RandomSample[textures, 6], faces}]], Lighting -> "Neutral"], {30}]

ListAnimate[frames]

Export["cube.gif", frames]


text:
Q: Interleaved sort keys in AWS Redshift Have a few questions related to the interleaved key.

*

*Is the order in which we specify the columns of interleaved sort keys important? I understand that Redshift gives equal importance to each key mentioned in the interleaved keys but does the order in which they are specified matter?

*I also see that the sortkeys are given numbers (and also negative numbers) like below. what do the negative numbers indicate below?

*does the query performance get affected if there are around 8 keys configured as interleaved sort keys compared to if there were 4, does Redshift have to scan lesser blocks because of the number of columns configured as the interleaved sort keys?

Thanks.

A: I can give you my quick answers to these questions but first let's understand what is trying to be achieved with sort keys.  While many benefits can be achieved with sort keys (like merge joins) there is one dominating benefit that will make the biggest change (for large tables) and that is table scan optimization.  If the table metadata indicates that the block is not needed for the query then this block will not be scanned (read) from disk.  If a large percentage of the blocks can be eliminated from the scan the query may be significantly sped up.
This can only happen if the table metadata is valid for the blocks in question AND if the metadata shows that the data is not needed.  A WHERE clause needs to be included in the query and the comparison has to be against the raw column value and a literal (like WHERE A = 1).  To provide any benefit there needs to be blocks for column A where the metadata indicates that A does not the value 1 for this block.  To provide significant value the metadata for all the blocks of column A need to have a fair percentage of these to not possibly contain the value 1.
The sorting of the table by its sortkeys will determine which rows are in which blocks and therefore what max and min values for the block will be represented in the blocks metadata.  If A has values 1 through 10 and A is the only sort key then the first blocks for column A will have 1, then set set 2, and so on.  Assuming that the table has enough rows to fill up many more than 10 blocks (per slice) then the WHERE A = 1 clause can prevent the scanning of most of the table's data from disk.  A big performance win.
The complexity comes in when you have multiple sort keys (interleaved or not).  If you sort by A and then by B (also having the values 1 through 10) you may or may not get good "block rejection" on a query with the where clause "WHERE B = 1".  This will depend on how many rows are in your table and how big your cluster is (number of slices) (as well as the table distribution but let's not get overly complicated as this is complex enough).  If you have enough rows with A = 1 that the rows with B = 1 can fill up many blocks of data then there can still be good "block rejection".  However, the size of the table needs to be much much larger than in the A = 1 where clause to achieve the performance boost.  Similarly a 3rd sort key will need an even greater size of table (as compared to the number of slices in the cluster) to achieve the same benefit.
Whether the sort key are compound or interleaved doesn't matter a whole lot in this analysis.  Interleaved sort keys have a window of table size where they will out perform compound.  Also this benefit is only worth the time of selecting on A and B independently are of equal importance to you.
#1: So to answer your first question the number of sort keys definitely matters.  The more sort keys you have the harder it is to gain any benefit from "block rejection".  This is true for compound keys and especially for interleaved keys.  Here's why - if I have 5 compound sort keys I may only get "block rejection" benefit from the first 2 and the others don't hurt me by screwing up the sorting of the higher keys.  However for interleaved all keys are treated with equal importance so by adding the 4th and 5th key to the list I've significantly hurt the "block rejection" benefit of the first 3 keys.  Bottom line - number of interleaved keys matters but the order doesn't (at least not much).  With 7 interleaved keys you are very likely getting near zero value.
#2: The negative values on the "odd" sort keys just indicates that these keys are part of an interleaved sort key list.  If the keys were compound then they would all be positive numbers.  It is just a flag.
#3: I've already hit on this but yes, 8 keys will likely give no benefit at all.  I highly recommend that you don't use interleaved sort keys as they cause more performance issue than they solve.  The tag line sounds good - "equal weight to all sort keys" - but the reality is that for most people the value they are getting from each interleaved sort key is equal - zero.
I've worked on Redshift for many years and with many clients, I've never gotten more than 3 sort keys to truly matter in the performance of queries.  Doing this took a lot of analysis and that was for just 3 keys.  These were compound keys in then end as there was some value to prioritizing one of the sort keys over the others.  Interleaved would have given these keys a balanced but poor boost in performance but the better solution was compound.
The other benefit with compound sort keys is that if you try to get performance from 3 keys but miss you are still likely getting benefit from 2. With interleaved you will likely get benefit from none.  Also, you can have more (later) compound sort keys that can provide benefit to a common downstream ORDER BY clause AND NOT mess up the scan benefit of the other sort keys.
I cannot stress this enough - don't use interleaved sort keys on Redshift unless you know what you are doing and have done the supporting performance analysis.
I do this analysis for clients and it is involved.  Even optimizing for a couple of compound sort keys can get tricky.  Most are far better off making a quick assessment of their most common WHERE clause values, putting the top one first in a compound sort key list, the second one second, and then add whatever other columns seem important to the end of the list.  You can do the analysis in 20 minutes and will get the majority of the possible benefit.


text:
Q: Model field types for Django 1.8.2 models that will work with MySQL database tables Let's say I have the following table showing how the columns would be declared for a MySQL table: (I can't think of a very realistic example, so here's something that's so silly. This table is created with the help of Excel)

I want to create a model in Django that is compatible with the MySQL table I'll have with the columns declared this way. However, from looking at the Django documentation, I can't find any model field types that in SQL are the same format as those in the picture except for the primary key field.
I did see before that by default, Django handles a database that uses the SQLite Engine, but I want to see if it's possible to handle a database of MySQL tables.
Is there a way to create Django model field types, like MEDIUMINT, TINYTEXT, and SMALLINT, (in MySQL) that are compatible with tables created through MySQL? It's simply a way for me to use the tables that I created myself, not the tables that Django generates automatically once all the models are defined.

A: In Django you normally create the models and let the framework generate the tables for you. If you have a legacy database you can use python manage.py inspectdb to generate the models from the database (see the documentation). But if it isn't a legacy database and you've created it just now, you are fighting against the framework and making your life more complicated.


text:
Q: Selecting one  from a table I have a table which consist of user added data. All the 's added are added with a equal button. Like this:

  <form action="newBet.jsp" method="get">
    <fieldset>
        <input class="button betButton1" id="Won" type="submit" name="W" value="✔"/>

            <input class="form-control" name="update1" type="number"/>
            <input class="button betButton1" type="submit" name="update" value="Close early"/>

       <input class="closeEarlyLink" type="button" value="✎ Close early?"/>
    </fieldset>
 </form>

This wokrs fine. Now, I want to add some jquery which toggle the hidden div element. This is where I run into troubles. I can't seem show the div element only on the clicked element. Instead it shows the hidden div element on all the td's.
$(document).ready(function(){
  $(".closeEarlyLink").click(function(e){
    e.preventDefault();
    $(".closeEarlyForm").fadeToggle();
  });
});

I know that my problem is that I select all the elements with the class, but I cant figure out how to only toggle/select the hidden element on the specific td.

A: You can try using this keyword with parent() and find():
$(this).parent().find(".closeEarlyForm").fadeToggle();

Demo:

$(document).ready(function(){
  $(".closeEarlyLink").click(function(e){
    e.preventDefault();
    $(this).parent().find(".closeEarlyForm").fadeToggle();
  });
});

  <form action="newBet.jsp" method="get">
    <fieldset>
        <input class="button betButton1" id="Won" type="submit" name="W" value="✔"/>

            <input class="form-control" name="update1" type="number"/>
            <input class="button betButton1" type="submit" name="update" value="Close early"/>

       <input class="closeEarlyLink" type="button" value="✎ Close early?"/>
    </fieldset>
 </form>


text:
Q: AngularJS tags doesn't work in innerHTML In my code i've a table which is populated by ng-repeat tag., and that's ok. By clicking a button, a row is added to this table by innerHTML. This new row should contain 2 cells:

*

*select

*input-field + a confirm button
I want to populate the select with ng-option tag, and this is not going to happend.
The angularJS tags (and whatever script or function i try to insert) grafted with innerHTML do not work.
methods is a JSON containing 3 payment methods (PayPal, Postepay, Skrill).
payment_methods contains the user payment methods (method + notes).
If i try to add the innerHTML code simply in the html page, it all works, so there's no bug in http requests or angularJS tags.
Any solution? Thanks.
$http.get('/api/v1/getUserPaymentMethods', {params: {"idUser": myService.get()}}).success(function (data) {
    $scope.payment_methods = data;
});

document.getElementById('insert-btn').onclick = function () {
        var table = document.getElementById('table');
        var row = table.insertRow(table.length);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);

        cell1.innerHTML =
            "<select ng-model=\"selectedMethod\" " +
                "ng-options=\"method.method for method in methods\">" +
                    "<option value=\"\" disabled selected>Method</option>" +
            "</select>";

        cell2.innerHTML =
            "
" +
                "<input type=\"text\" ng-model=\"notes\" id=\"notes\">" +
            "
" +
            "
 " +
                "<button id=\"confirm-btn\">done</button>" +
            "
";

        $http.get('/api/v1/getMethods').success(function (data) {
            $scope.methods = data;
        });
    }
}

document.getElementById('confirm-btn').onclick = function () {
    // save data
}

HTML:

    Method
    Notes

    {{payment_method.id_payment_method}}
    {{payment_method.notes}}

    <button id="insert-btn">add payment method</button>

A: With Angular you don't have to build html manually, but do something like this:

    Method
    Notes

    {{payment_method.id_payment_method}}
    {{payment_method.notes}}

        <select ng-model="selectedMethod" ng-options="method.method for method in methods" >
         </select>

        <input type="text" ng-model="notes" id="notes"/>


text:
Q: Synfusion : Image from url not showing in html to pdf conversion I'm trying to generate pdf from html which is working fine but the issue I am having is that my images are not showing: the images are from a url <img src="https://image.shutterstock.com/image-photo/large-beautiful-drops-transparent-rain-260nw-668593321.jpg" /> I think the images have not been loaded before the conversion. Please how can I delay the conversion or achieve this i.e ensure the image is rendered with the pdf.

            WebKitConverterSettings settings = new WebKitConverterSettings();

            var baseUrl = url;
            settings.PdfHeader = HeaderHTMLtoPDF(url");
            settings.PdfFooter = FooterHTMLtoPDF({url});

            //Set WebKit path
            var contentRoot = _configuration.GetValue<string>(WebHostDefaults.ContentRootKey);
            settings.WebKitPath = Path.Combine(contentRoot, "QtBinariesWindows");
            settings.Margin.Top = 30;
            //Assign WebKit settings to HTML converter
            htmlConverter.ConverterSettings = settings;

            var pdfViewUrl = $"{baseUrl}/api/pdf";
            Task<PdfDocument> convertPdfTask = Task<PdfDocument>.Factory.StartNew(() => htmlConverter.Convert(pdfViewUrl));
            PdfDocument document = convertPdfTask.Result;

            MemoryStream stream = new MemoryStream();
            document.Save(stream);
            document.Close(true);```

A: We have checked the conversion with provided details, its working properly. We have creates a simple html with provided image and it is properly converted to PDF document.
The reported image missing issue may occurs due to missing of OPENSSL assemblies. To access the resource from HTTPS site, the HTML converter requires OPENSSL assemblies. So, please make sure the OPENSSL assemblies are available in the machine where the conversion takes place. Please refer below links for more details,
Prerequisites - https://help.syncfusion.com/file-formats/pdf/convert-html-to-pdf/webkit#openssl
Troubleshooting - https://help.syncfusion.com/file-formats/pdf/converting-html-to-pdf#troubleshooting
However, the below mentioned OPENSSL assemblies can be placed in the Windows system folder of the machine. (for 64-bit machine, it should be place in $SystemDrive\Windows\SysWOW64 and for 32-bit machine, it should be place in $SystemDrive\Windows\System32).

*

*libeay32.dll

*libssl32.dll

*ssleay32.dll

Note : I work for Syncfusion.

A: An alternative solution is to convert your image to base64 so the image is inline in the html.


text:
Q: ExtJs grid not refreshing after adding a new record I am using ExtJS API for CRUD operations in grid. All of my code works fine except one small thing. When I add a record first time(when the page is loaded) the new record is not shown on the grid but it is added in the database. When I refreshes the page and insert a record it is shown as soon as it is added. This is a very strange behavior and I don't even have a clue what's going on here. Here is the code I am using to insert a record:
insertUser: function (button) {
        var grid = Ext.ComponentQuery.query('#userlist');
        var win = button.up('window');
        form = win.down('form');
        record = form.getRecord();
        values = form.getValues();
        this.getUsersStore().add(values);
        this.getUsersStore().reload();//tried this.getUsersStore().load(); also
        win.close();
    }

Can any one point out what's wrong going on here? Thanks.

A: When adding a data to store it needs to be in the format of the store record.
For example
this.getUsersStore().add({username:'Sample User', userid: 210, userphone: '999-999-9000'});

In your code it seems that you are directly passing the values.
If you add the record correctly store does't need to do reload() or refreshed, if you reload() the store gets refreshed and the data you added will not be present.


text:
Q: Changing user group with post_user_register event I don't really understand how events work in PyroCMS. I want to update a user role based on the type of user a person selects during registration. It's quite similar to this post. Because I don't understand how events work, I don't know how to proceed. This my events class I added in the user module folder:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Events_Users{
protected $ci;

public function __construct()
{
    $this->ci =& get_instance();

    Events::register('post_user_register', array($this, 'update_user_group'));
}

public function update_user_group($user_id)
{
    //loading the user model class
    $this->ci->load->model(array('users/user_m'));
    //getting the users details
    $user = $this->ci->user_m->get(array('id' => $user_id));
    //assigning the user type variable
    $user_type = $user->tell_us_who_you_are;
    $set =  array('group_id' => $user_type);
    if($user_type == 'spectator')
    {
        //do nothing
    }else{
        //update user group
        $this->db->update('users',$set, array('id'=>$user_id));
    }
}

}

A: Events::register('post_user_register', array($id, 'update_user_group'));
This line registers your custom function to an event, When an event ( here post_user_register ) is called then your function ( here update_user_group ) will be triggered.
You just need to change your function name and pass the user_id which will be passed to it by the event trigger.
public function update_user_group($user_id)
    {
        // your logic
        //dump($user_id);die();
    }

So try this code for your events.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Events_Users{

    protected $ci;

    public function __construct()
    {
        $this->ci =& get_instance();

        Events::register('post_user_register', array($this, 'update_user_group'));
    }

    public function update_user_group($user_id)
    {
        $this->db->update('users', array('group_id' => $this->input->post('user_type')), array('user_id'=>$user_id));
    }
}


text:
Q: ASP.NET MVC 4 FileResult - In error I have a simple Action on a controller which returns a PDF.
Works fine.
public FileResult GetReport(string id)
{
    byte[] fileBytes = _manager.GetReport(id);
    string fileName = id+ ".pdf";
    return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}

When the manager fails to get the report I get back null or an empty byte[].
How can I communicate to the browser that there was a problem, when the result is set to a FileResult?

A: If you want to "communicate to the browser" that there was an error, the standard "HTTP way" is to return status code 500, especially if your request is invoked using Ajax, so that you can gracefully handle the exception.
I would suggest to simply throw an Exception when no report found for the provided id:
public FileResult GetReport(string id)
{
    // could internally throw the Exception inside 'GetReport' method
    byte[] fileBytes = _manager.GetReport(id);

    // or...
    if (fileBytes == null || !fileBytes.Any())
          throw new Exception(String.Format("No report found with id {0}", id));

    return File(fileBytes, MediaTypeNames.Application.Octet, fileName = id+ ".pdf");
}

Explicitly redirecting to an error page or returning a ViewResult is not the best approach in ASP.NET MVC as this is usually the role of the HandleError filter (which is applied by default) that can be easily configured to either redirect or render some View with the Exception details (while still maintaining HTTP status 500).
This is all true assuming that a failure to fetch a report is indeed considered an exception. If it's not (for example, if we expect some report to not have an available file to dump), explicitly returning a Redirect/View result is totally acceptable.

A: I would change the return type of your method to ActionResult.
public ActionResult GetReport(string id)
{
    byte[] fileBytes = _manager.GetReport(id);
    if (fileBytes != null && fileBytes.Any()){
        string fileName = id+ ".pdf";
        return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
    }
    else {
        //do whatever you want here
        return RedirectToAction("GetReportError");
    }
}

A: Another workaround for handling prerequisites is to split download process into two stages. First is to check preconditions in server side method which is executed as ajax/post method.
Then if these preconditions are fulfilled you can start download request (e.g. in onSuccess callback where it is checked the return value indicating fulfillment) in which (on server side) you will handle potential exceptions in a way as it was described in above posts.

A: The FileResult class inherits from ActionResult. So, you can define your Action like this:
public ActionResult GetReport(string id)
{
    byte[] fileBytes = _manager.GetReport(id);
    string fileName = id + ".pdf";

    if(fileBytes == null || fileBytes.Length == 0)
       return View("Error");

    return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}


text:
Q: How do you implement SASTokenProvider for per-container SAS token access? According to the documentation, you can use SAS tokens to access Azure Data Lake Storage Gen2, by implementing the org.apache.hadoop.fs.azurebfs.extensions.SASTokenProvider interface.
See the documentation here: https://learn.microsoft.com/en-us/azure/databricks/data/data-sources/azure/adls-gen2/azure-datalake-gen2-sas-access
However, only a mock implementation is provided, that uses direct access to the master account key to generate the SAS token:
    try {
      AbfsConfiguration abfsConfig = new AbfsConfiguration(configuration, accountName);
      accountKey = Base64.decode(abfsConfig.getStorageAccountKey());
    } catch (Exception ex) {
      throw new IOException(ex);
    }
    generator = new ServiceSASGenerator(accountKey);

It is completely meaningless to restrict access by providing a SAS token when the code is running in a context that has access to the master account key, and obviously this is a mock implementation used for testing purposes only.
So, a correct implementation of this class would:

*

*be run in a package-cell so it has access to the secret scopes

*be implemented in scala, because java is not supported

*fetch the SAS token from the secret scope

*return the SAS token

How can such an implementation be written?
Here is the most basic and trivial version of the solution that proves that this is possible to do:
%scala
package com.foo

class CustomTokenProvider extends org.apache.hadoop.fs.azurebfs.extensions.SASTokenProvider {
  def getSASToken(accountName: String,fileSystem: String,path: String,operation: String): String = {
    return "sp=...etc etc"
  }
  def initialize(configuration: org.apache.hadoop.conf.Configuration, accountName: String): Unit = {
  }
}

...

spark.conf.set("fs.azure.account.auth.type.STORAGE_ACC.dfs.core.windows.net", "SAS")
spark.conf.set("fs.azure.sas.token.provider.type.STORAGE_ACC.dfs.core.windows.net", "com.foo.CustomTokenProvider")

dbutils.fs.ls("abfss://sandbox@STORAGE_ACC.dfs.core.windows.net/")
> [FileInfo(path='abfss://sandbox@STORAGE_ACC.dfs.core.windows.net/t.py', name='t.py', size=112)]

dbutils.fs.ls("abfss://restricted@STORAGE_ACC.dfs.core.windows.net/")
> Operation failed: "Server failed to authenticate the request.

However, how can this implementation to changed to pull the key from the secret store instead of being hard-coded?
Note specifically that:

*

*this refers to the abfss driver, not the legacy wasb driver.

*the question is specifically with regard to getting the SAS token from the secret store which can be restricted at a group / user level; assigning the token at a cluster level (eg. env variable) is not a valid solution because it means all cluster users are granted the same permissions.

*...and yes, I know, databricks has it's own custom identity provider system (Unity), but that only applies to datasets in the hive metastore. This question is specifically regarding the lower level storage account access.

A: %scala
package com.foo

import org.apache.hadoop.fs.FileSystem
import org.apache.spark.sql.catalyst.DefinedByConstructorParams

import scala.util.Try

import scala.language.implicitConversions
import scala.language.reflectiveCalls

trait DBUtilsApi {
    type SecretUtils
    type SecretMetadata
    type SecretScope
    val secrets: SecretUtils
}

object ReflectiveDBUtils extends DBUtilsApi {

    private lazy val dbutils: DBUtils =
        Class.forName("com.databricks.service.DBUtils$").getField("MODULE$").get().asInstanceOf[DBUtils]

    override lazy val secrets: SecretUtils = dbutils.secrets

    type DBUtils = AnyRef {
        val secrets: SecretUtils
    }

    type SecretUtils = AnyRef {
        def get(scope: String, key: String): String
        def getBytes(scope: String, key: String): Array[Byte]
        def list(scope: String): Seq[SecretMetadata]
        def listScopes(): Seq[SecretScope]
    }

    type SecretMetadata = DefinedByConstructorParams { val key: String }

    type SecretScope = DefinedByConstructorParams { val name: String }
}

class VaultTokenProvider extends org.apache.hadoop.fs.azurebfs.extensions.SASTokenProvider {
  def getSASToken(accountName: String,fileSystem: String,path: String,operation: String): String = {
    return ReflectiveDBUtils.secrets.get("scope", "SECRET")
  }
  def initialize(configuration: org.apache.hadoop.conf.Configuration, accountName: String): Unit = {
  }
}

...
spark.conf.set("fs.azure.account.auth.type.bidbtests.dfs.core.windows.net", "SAS")
spark.conf.set("fs.azure.sas.token.provider.type.bidbtests.dfs.core.windows.net", "com.foo.VaultTokenProvider")

This is basic example only; the real solution will select the correct secret based on account and file system.


text:
Q: Does .htaccess Rules Increases Load Time? Does rules in .htaccess file increase load time on server? I am confused. I tried to search about it but results shows benefits of caching, etc. Does redirection of rewritten URLs to index.php helpful or it increases server load time?
Is it better to have a PHP routing library rather than redirection through .htaccess?

A: Yes, .htaccess rules increase the response time.
But don't worry about a single redirection rule, unless you have to deliver a high performance system.
.htaccess files are read on every request.
If you have a complex directory hierarchie, all .htaccess files are included and parsed (top-down) on each request. A redirection is a new request, so the files are parsed again.
Things to avoid: big files, many files, really complex regexp rules, multiple redirections.
Keep your .htaccess compact, small and simple.

A: Yes for every rule you use regex and need the FSM-Mashine or the Apache rewrite module to parse the rules. If you have a lot auf rewrite rules its possible that your request will be a bit slower. But the rewrite module is very fast. So normally you will not recognize it.

A: Yes, .htaccess rules directly take actions with server responce. So that's why it will effect on server load time. But It will consume normal time, but you should have to write correct rule in it, then it will not do so ;)


text:
Q: controller inside vs outside of directive First code is working fine when I declare controller outside of my directive but when i put same directive inside(in second code) it stopped showing any result, i might be missing very silly thing, please help me out.
First code:

    <student name="Mahesh"></student>

Second code:

    <student name="Mahesh"></student>

A: var mainApp = angular.module("mainApp", []);

mainApp.directive('student', function() {
  return{
    restrict : 'E',
    template : "Student: {{student.name}}",
    scope : {
     student : "=name",
    },
    controller: function($scope) {
      $scope.student = {};
      $scope.student.name = "Mahesh Parashar";
   }
};

});

  <student name="Mahesh"></student>

Try ,it will work
Pluner


text:
Q: Sonar analysis abort because 'No files nor directories matching 'target/classes' I'm performing an analysis with Sonar but I get the following error:
Error during SonarQube Scanner execution
java.lang.IllegalStateException: No files nor directories matching 'target/classes'

In my project I've the target directory but no classes directory or files, what should be in there for the analysis to work?

A: Sometimes some modules could not generate sources, for example, working with Maven, those modules packaging as 'pom'.
To avoid sonar analysing them, specify in your sonar.properties the property sonar.modules with the ones are generating sources.

A: One of the reasons might be that Sonar cannot find that directory if you do analysis before building your project.
The target/classes directory does not exist before you started building the project using maven.
Try this value to workaround:
sonar.java.binaries=target

or
sonar.java.binaries=.

A: I'm sure that you figured this out already.  However, here's what you need to do for Java projects built using Maven.
If you're using the path "**/target/classes" then let's assume that you're using Maven for your builds.  You would perform a "mvn clean package" for your Sonarqube Scanner to work.
Once you have used maven to compile and package into the standard directory ("./target/classes") then just pass the appropriate setting to the scanner (either through a configuration file or the command line).  An example of passing through the command line is below.
        ${scanner_home}/bin/sonar-scanner
            -Dsonar.login=<SONAR KEY>
            -Dsonar.projectKey=<PROJECT KEY>
            -Dsonar.branch.name=<BRANCH_NAME>
            -Dsonar.branch.target=<RELEASABLE BRANCH>
            -Dsonar.sources=./src
            -Dsonar.java.binaries=./target/classes

Notice that I'm using a relative path for the sonar.sources and sonar.java.binaries settings.  I do this in a Jenkins build pipeline and made this configurable since I also build PHP and use Composer, Gulp, npm, and other tool in my build process.  (If you're using the SonarQube Scanner for Maven, then you would put this into a property file.)

A: for the poor lost soul who finds themselves on this thread, you may encounter this error when migrating from gradle 4.x to 5.x as the classes folder is renamed from classes to app_classes and it's no longer variant/flavor it's variantFlavor - you can verify by building your app and looking in the build folder
I had to change this sonarqube property in my build.gradle
property "sonar.java.binaries", "build/intermediates/app_classes/betaDebug,build/tmp/kotlin-classes/betaDebug"

A: The Answer from @bsaunter works.
I have to add that you may encounter this error also when migrating from gradle 5.x to 6.x,
got to your build/intermediate/javac/debug folder and look what is generating sonarqube, the name of the folder could be "classes"
Look for this property "sonar.java.binaries" on wherever file in your project folder and replace the value for the correct generated folder by sonarqube.


text:
Q: Proper date -d "next monday" I'm trying to write a quick script that figures out the date of the next Monday that isn't today.  Although the date command accepts this expression, it appears to interpret it as equivalent to "this monday".  That is, if today is Monday, it emits today's date, otherwise it emits next week's Monday.
Any ideas how to do this with the date command (or really any command available to bash) without resorting to doing the date arithmetic myself?
Update: This appears to be something strange with my environment, as several folks have shown the command working as expected on their systems.  This is what I see:
$ date
Tue Jul 31 23:38:28 UTC 2012
$ date -d 'next tuesday'
Tue Jul 31 00:00:00 UTC 2012
$ date --version
date (GNU coreutils) 5.97

It would appear I have an ancient version of date, perhaps that's my issue...

A: Are you sure there isn't a problem with how you are executing the command within the script, maybe missing quotes or something of that nature? I cannot reproduce your problem.
$ date
Tue Jul 31 19:08:50 EDT 2012
$ date -d "next tuesday"
Tue Aug  7 00:00:00 EDT 2012
$ date -d "this tuesday"
Tue Jul 31 00:00:00 EDT 2012
$ date --version
date (GNU coreutils) 8.5

A: GNU date seems to be working correctly.
error@underground ~/Downloads $ date -d "next monday"
Mon Aug  6 00:00:00 EDT 2012
error@underground ~/Downloads $ date -d "next tuesday"
Tue Aug  7 00:00:00 EDT 2012
error@underground ~/Downloads $ date -d "next wednesday"
Wed Aug  1 00:00:00 EDT 2012
error@underground ~/Downloads $ date --version
date (GNU coreutils) 8.15

Check to ensure that your system actually has the correct date, time and time zone.
Also check to make sure you're running a relatively recent version of GNU coreutils. The behavior you describe was a bug in old versions of coreutils that was fixed in version 6.0.

date: a command like date -d '2006-04-23 21 days ago' would print the
  wrong date in some time zones.  (see the test for an example)


text:
Q: Python и DirectInput Стоит задача - выполнить парочку простых "тасков" а-ля "вывод названий устройств на экран, использующих DirectInput".
Возможна ли сия реализация на Python?
Ибо пытался почитать про DirectInput python (он же directpy), но документации не очень много и сам directpy показался сырым.
И вообще, стоит ли идти этим путём?


text:
Q: "500: Unknown web method" when i send data using $.ajax and WebMethod I'm trying to send data via Ajax to my database, using the JQuery Ajax function and
and WebMethod in my C# code.  But it's not working.  Any ideas?
$(function() {
    $('#Add').click(function() {
        var $dialog = $('<div id="MyDialog"></div').appendTo('body')
            .load("../Pop-up.aspx #pop-up", createDatePicker)
            .dialog({
                position: 'center',
                width: 550,
                buttons: {
                    "OK": function() {
                        var jname = $('#name').val();
                        var jbirthday = $('#datepicker').val();
                        var jgender = $('input:radio[name=Gender]:checked').val();
                        var jcourseId = $('#DropDownList1').val();
                        var myjson = {
                            name: jname,
                            birthday: jbirthday,
                            gender: jgender,
                            courseId: jcourseId
                        };

                        $.ajax({
                            type: "post",
                            contentType: "application/json;charset=utf-8",
                            dataType: "json",
                            url: "Manage.aspx/AddStudent",
                            data: $.toJSON(myjson)
                        });
                    },
                    "Cancel": function() {
                        $(this).dialog('close');
                    }
                }
            });
        return false;
    });

});

and this is my web method
      [WebMethod]
      public static void AddStudent(string birthday,string name,string gender,string courseId)
      {
        var repository = new StudentRepository();
        var student = new Student
                            {
                                Birthday = Convert.ToDateTime(birthday),
                                Name = name,
                                Gender = gender,
                                Course_ID = Convert.ToInt32(courseId)
                            };
        repository.InsertStudent(student);
            repository.Save();
      }

A: Try changing the order of the properties on your JSON object so they match the parameters in your Webmethod.
    var myjson = {
       birthday: jbirthday, //now the properties match the parameters
       name: jname,
       gender: jgender,
       courseId: jcourseId
    };

    public static void AddStudent(string birthday, string name, string gender,
        string courseId)
    { ... }

I think you're seeing the 500 error because ASP.NET can't find a method signature that matches your deserialized JSON object, even though all the parameters are of type string.
Update
I've had a chance to test out what I originally suggested, and the ordering of properties didn't matter.
Not sure if any of this helps but, I saw 500 errors when:

*

*The properties on my JSON object didn't match all the parameters in my WebMethod
var myjson = {b: 'test1', c: 'test' };

[System.Web.Services.WebMethod]
public static void TestMethod(string a, string b)
{
    //does nothing.
}

*One of the parameters I was passing in was undefined.
var myjson = {a: undefined, b: 'test' };

[System.Web.Services.WebMethod]
public static void TestMethod(string a, string b)
{
    //does nothing.
}

A: try this:
data: JSON.stringify(myjson)

instead of:
data: $.toJSON(myjson)


text:
Q: Why do I need to create an object for EditText.getText()? I'm currently playing around with Java in Android-Studio.
I stumbled upon a phenomenon I don't understand. When I try to call getText() of a EditText class I first need to create an instance of the EditText class. Could someone please explain why this is?
This works:
EditText editText = findViewById(R.id.editText);
editText.getText();

This doesn't:
findViewById(R.id.editText).getText();

A: That's because the type of the object returned by View#findViewById is generic and will typically be cast automatically to the reference type (in your case, EditText) if one is given.
To quote the docs:

Note: In most cases -- depending on compiler support -- the resulting view is automatically cast to the target class type. If the target class type is unconstrained, an explicit cast may be necessary.

If your compiler doesn't know that findViewById(R.id.editText) is of type EditText, it will not allow you to invoke getText (i.e. android.view.View does not feature a getText method).

A: In continuation of @mena 's answer , try casting it to edit text. It will work
((EditText) findViewById(R.id.editText)).getText();

A: Because we are writing the EditText in XML file and do the functionality in the java class.
Due to that reason these two should macth with the id such as below
EditText editText = findViewById(R.id.editText);

Then java class know that there is a EditText with a specific id.
If you directly use as below
findViewById(R.id.editText).getText();

you will get NullPointer Exception.
And also from the getText() function it return a object.
So we cannot set it to a string variable


text:
Q: Compiz Window Previews stay for too long after my mouse has long moved away. (Gnome Classic and Xubuntu) Fix? Whenever I use Window Previews Compiz plugin, the previews stay even once I have moved my mouse elsewhere, this happens in Gnome Classic and XFCE too. Any ideas how to solve this?

A: Compiz requires good hardware acceleration to work well, which generally means that you'll have to have a relatively recent graphics card. If your graphics card is an old Intel's accelerator, a VIA, or even an old Nvidia 4000/5000, consider either staying away from Compiz or upgrading to more modern hardware.
If you have a decent card, then something is probably misconfigured.


text:
Q: Uncaught TypeError: Cannot set property 'innerHTML' of null [VueJs] I see previous questions about the same problem faced me, but I try to solve it based on the solution of the questions! but it does not work
In my <template>:
<modal name="MyModal" >
  visible
</modal>

In my


text:
Q: Google sheet cannot see my app script I've created my own google app script with one function. However, when I type "=" in sheet cell I can't see this function in suggestions. Also I don't see "Loading..." label which indicates external functions loading. Moreover, I cannot reach this function by name directly.
What do I miss in using google app script function with google sheets? Is it bug or should I make some additional configurations?
Thanks for your help.

A: It sounds like your script was not linked with the Sheet.
From the Google App Scripts doc,

A script is bound to a Google Sheets, Docs, or Forms file if it was
  created from that document rather than as a standalone script.

This means if you do not use Tools -> Script editor... in the Sheet for creating the script, it will not link to the Sheet.
From what I understand, a Standalone Script is treated as its own entity on Google Drive. This allows you to import the script if you were making a web application, for example, with the Drive REST API.
If you don't create a standalone script, then you will create the script in a project. I don't see an option to move scripts in the Script Projects Doc at the bottom under Managing files in a project.
Therefore, if you didn't make the script in the Sheets project, you will need to copy the contents into the project. There might also be an option for setting the project associated with the Sheet.


text:
Q: How to make Ecto interpret/write local time instead of UTC for `timestamps` macro This is about integrating a database from a legacy app.
The legacy app is reading and writing timestamps (i.e. created_at, updated_at in local time of the host).
And while I'm fully aware that this should be highly avoided this behaviour cannot be changed.
Therefore the Elixir application that uses the same database must be configured to use local time as well.
Ecto provides the timestamps macro but it seems that I cannot make it work with local timestamps.
While it's possible to provide a type (i.e. :naive_datetime or :utc_datetime) both types seem to use the utc_now() function.
Also reading the fields might cause difficulties, since the date fields are defined as timestamp without time zone in the database.
Hence the database fields also should be interpreted as local time and not as UTC.

A: Per @AlekseiMatiushkin, you should be able to use the :autogenerate for this, something like:
defmodule MyThing do

  use Ecto.Schema

  schema "things" do
    field(:something, :string, null: false)
    # ...
    timestamps(autogenerate: {MyThing, :local_time, []})
  end

  def local_time do
    DateTime.now!("Europe/Vienna") |> DateTime.to_naive()
  end

  # ...
end

If relying on the macro is too constrained for your use-case, you can manually write values to the fields (some languages call these mutations, virtual fields, or calculated fields). Something like:

defmodule MyThing do

  use Ecto.Schema

  import Ecto.Changeset

  schema "things" do
    field(:something, :string, null: false)
    field(:my_timestamp_col, :map) # <-- or integer, or ???
    # ...
  end

  def changeset(thing, attrs) do
    thing
    |> cast(
         attrs,
         [
           :something,
           # ...
         ]
       )
    # validate, constraints, etc.
    |> calc_local_time()
  end

  defp calc_local_time(changeset) do
    case changeset do
      %Ecto.Changeset{
        valid?: true,
        changes: thing
      } ->
        put_change(thing, :my_timestamp_col, local_time())
      _ ->
        changeset
    end
  end

  def local_time do
    # add custom date/time calcs here
    DateTime.now!("Europe/Vienna") |> DateTime.to_naive()
  end
end

Hopefully you can find a solution leveraging the above patterns.


text:
Q: What is the better way to spread my locationUpdate through all application? I want to broadcast my locationUpdate from GoogleApi (which is inside Service) to 3 different activities.
I can implement a simple callback, but this way I can send my location only to one place.
@Override
    public void onLocationChanged(Location location) {
        mLocationCallback.handleNewLocation(location);
    }

On another hand I can create BroadCastReceiver:
private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            notifyListDataChanged();

        }
    };

but it looks ugly and takes a lot of time to code and maintain. Is there any other simple way to broadcast location updates from Service

A: There are several message bus implementations for Android, including Otto, EventBus, and others. Any one of them should work for this.


text:
Q: Does a multicolumn unique index support my query? Using PostgreSQL-13, I need advice about key index. I have a table named "employee" and I manage my DB using DBeaver Community Edition (latest).
Fieldname      Type
----------     ----
pid            bigint -  nextval('employee_pid_seq'::regclass) --
Primary Key
company_id     varchar(10)
employee_id    varchar(10)
employee_name  varchar(50)

I'm learning to fine-tune this simple table. company_id and employee_id is a unique index.
When running:
select * from employee order by company_id

... to enhance the performance, do I also need to have company_id as non-unique index?

A: Once you have a unique index (or constraint, same effect) on (company_id, employee_id), you typically don't need another index on just (company_id).
The multicolumn index with leading company_id supports your ORDER BY. See:

*

*Is a composite index also good for queries on the first field?


text:
Q: Custom Wifi hotspot with Facebook or Twitter login I would like to install a custom Wi-fi hotspot which needs login to enable Internet access with this requirements and I would like to know if someone has installed.
Requirements:

*

*Login server: I have my own OAuth server built with Java/Spring to
enable user login with Twitter and Facebook via REST API.

*Wi-fi access point: allows user Internet access when login success.

*When the user selects the Wi-Fi network, the landing page must appear with the login button.

I' ve got the login module, but I don' t know how to install some kind of Wi-fi hotspot with a custom landing page that could link with this login server. I've searched for some kind of tool or software, but I found nothing. Any ideas or suggestions, please?
Thank you very much!

A: I just stumbled over a google code project which achieves what you want for routers running openwrt.
The basic setup is this: You run a router with openwrt (a list of supported Hardware can be found on their wiki). Then you install wifidog to provide your portal page and run the project (which now seeems to have moved here and has been renamed to KikiAuth) as the auth provider for wifidog.
Since KikiAuth is opensource it should be easy to adopt the method it uses to provide the auth information for wifidog into your existing software and use it as the provider instead if you want to manage the login process yourself.
More details about the setup can be found on the page of the google code project.


text:
Q: Salesforce Commerce Cloud Shop API Order status update fails I have a question about the update of the status of an order.
I create the basket using OCAPI and then I can successfully create an order with
https://mydomain/dw/shop/v21_10/orders (POST)
Order is fine. All data are there.
Now the order has status CREATED and I want to change it to OPEN using the Shop API again.
https://mydomain/dw/shop/v21_10/orders/MyOrderNumber (PATCH)
This is the message I receive
{"_v":"21.10","fault":{"arguments":{"statusFrom":"CREATED","statusTo":"OPEN"},"type":"StatusTransitionNotPossibleException","message":"The status transition from 'CREATED' to 'OPEN' isn't possible."}}
While if I try to make the same transition in Business Manager it works perfectly.
Anyone knows why?

A: The reason you can't transition the order from CREATED to OPEN is because there is a step in between.
Unfortunately, this is poorly documented in OCAPI docs, but we can see a clearer picture if we look at the DW API docs which explain in more detail.
A bit of background
First, notice the description of the PATCH /orders/{order_no} endpoint:

same status transitions are possible as for dw.order.Order.setStatus(int status) plus CREATED to FAILED)

Okay, so it follows the DW API rules. Let's take a look at the Order.setStatus() method (emphasis mine):

This method does not support order statuses ORDER_STATUS_CREATED or ORDER_STATUS_FAILED. Please use OrderMgr.placeOrder(Order) or OrderMgr.failOrder(Order).

So this is telling us that we can't move an order out of CREATED status except by either placing it or failing it. If we take a look at the documentation for OrderMgr.placeOrder(order), it corroborates this:

This method places an order and is usually called after payment has been authorized. The specified order must be in status CREATED, and will be set to status NEW.

Now back to OCAPI
Now we know that OCAPI generally follows the same rules as the DW API when it comes to transitioning order statuses. (with the exception of CREATED -> FAILED)
So how do we go about placing an order with OCAPI?
With OCAPI, you can place an order by calling POST orders/{order_no}/payment_instruments which will trigger the following hooks:

*

*Authorize the payment with either dw.order.hooks.PaymentHooks.authorizeCreditCard or dw.order.hooks.PaymentHooks.authorize, depending on the payment type

*Place the order with dw.ocapi.shop.order.afterPostPaymentInstrument
On success of both those hooks, your order will now be in NEW status, and ready to be transitioned into OPEN.
This discussion is on the same topic, although talking about the controller context, not OCAPI.
So, even though business manager lets you get away with stuff (I assume so that admins can override things where necessary), in the context of OCAPI or a controller, the order has to follow the regular placement steps.


text:
Q: How can I display image from byte data in Flutter I have two sides for my projects. One is a camera, with which we use OpenCV, to capture frames, in 8 bit 3 channel (R,G,B), format and write it to socket to be streamed. Image is 640 x 480 resolution, so 640x480x3 bytes are written to the socket.
On the other end, I have a Flutter app which is listening to this socket. I am able to successfully gather the bytes, but I am not able to restructure an image using them. How can I do this? I am sharing what I have so far, but I am not able to display any visual.
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:ferenova_flutter_app/plan_display_page/plan_display_page.dart';
import 'package:ferenova_flutter_app/vars.dart' as vars;

import 'dart:io';

// ignore: must_be_immutable
class CameraStreamPage extends StatefulWidget {
  PlanDisplayPageState pdps;
  Socket socket;
  String title;

  CameraStreamPage(
    String title,
    PlanDisplayPageState pdps,
  ) {
    this.title = title;
    this.pdps = pdps;
  }

  @override
  _CameraStreamPage createState() => _CameraStreamPage();
}

class _CameraStreamPage extends State<CameraStreamPage> {
  // VlcPlayerController _vlcViewController;
  PlanDisplayPageState pdps;
  Socket socket;
  Image img;
  Uint8List bytes;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    pdps = widget.pdps;
    this.socket = widget.socket;

    img = Image.network(
        'https://am23.mediaite.com/tms/cnt/uploads/2020/01/babyyoda.jpg');
    Socket.connect(vars.streamIP, int.parse(vars.streamPORT))
        .then((Socket sock) {
      socket = sock;
      socket.listen(dataHandler,
          onError: errorHandler, onDone: doneHandler, cancelOnError: false);
    }).catchError((Object e) {
      print("Unable to connect: $e");
    });
  }

  void dataHandler(data) {
    String str = new String.fromCharCodes(data).trim();
    print(str);

    vars.picture += str;
    int lim = 640 * 480 * 3;
    if (vars.picture.length >= (640 * 480 * 3)) {
      bytes = Uint8List.fromList(vars.picture.codeUnits);
      print('BBBBBBBBBBBBBBBBB: ' + bytes.length.toString());
      setState(() {
        img = new Image.memory(
          bytes,
          width: 640,
          height: 480,
          scale: 1,
          fit: BoxFit.contain,
        );
        vars.picture = vars.picture.substring(lim);
      });
    }
  }

  void errorHandler(error, StackTrace trace) {
    img = Image.network(
        'https://am23.mediaite.com/tms/cnt/uploads/2020/01/babyyoda.jpg');
    print('ERRORORORORORORORROROROR');

    print(error);
  }

  void doneHandler() {
    img = Image.network(
        'https://am23.mediaite.com/tms/cnt/uploads/2020/01/babyyoda.jpg');
    print('DONEDONEDONEDONEDONEDONE');
    vars.picture = '';
    socket.destroy();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      // child: SingleChildScrollView(
      child: Container(
        width: 1000,
        height: 600,
        color: Colors.green[400],
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          // mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Container(
              width: 900,
              height: 550,
              color: Colors.purple,
              child: img,
            ),
          ],
        ),
      ),
    );
  }
}

Also Following is a piece of what I receive:
P]rP]rT\rU^sX^tY_uYcvXbuVcsTaqP^lP^lR_mP^lR_mR_mU^jU^jS]iR\hQYjS[lR\oT]pT]pT]pR]mR]mR]mR]mU_pU_pU`nU`nYar[ctZd{]hYiaqhzw¤¡ §«©ª¨ ¬£ ¬£ ª¢ ª¢¡©¡© ¨§§§¢¥¢¥££¡¤¡¤¢¢¢¢¢¢  ¢¢¢¢¢¢         ¢¢¢¢¢¢   ¢¢£¢¡  ¡¡¡ ¡¢¢¢¢£¢£££££¤¤£¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¥¦¦ § § §¦¦ § §¡¨¢ §¡ §¡ §¡ §¡ §¡ §¡¡¨¢¡¨¢¡¨¢¡¨¢¡¨¢¡¨¢¡¨¢¢©£¢©£¤ª¤¤ª¤¤ª¤¤ª¤¢©£¡¨¢¢©£¢©£¢©£¤ª¤¥«¦¥«¦¤ª¤¤ª¤¤«£¤«£¤«£¤«£¨ª£¨ª£¨ª£¨ª£¨©¤¨©¤¨©

 ¡¡¡ ¡¡    .'/,$,-&..'/0(33+5MGM`Z_OFE&)!,$!*#$+$%.&)/'*/&,.%+*!'*!',$*+"(*!'*!'("')#()#('!&/).7164.13-0.(+,&),%+)#()"*(!)' ()"**#+.'/3.65085166288286054-31+1.'--&,/&,.%+.%+/&,2)/5,26-38/5:28:28:28=4:=4:<398045-02*.0(+,$(,$(+#'+#'+#'( #'"( #+#'+#')#()#(*$*,%+-)..*/,(-*&+,(-,(-,(--).-(0+&.*%,*%,'"*($+'"*'"**%,+&.+',,(-.'-.'-.'-.'-/).-&,-&,.'-.'-.'-/).-&,,%+,%+.'-.'-/'*+#'*

A: You can try this
Image.memory(Uint8List.fromList(YOUR_BYTES));


text:
Q: curl: can't fetch rss from website because of CloudFlare I'm notable to connect this site http://www.youm7.com/newtkarirrss.asp using curl on the server
But i can access it from localhost with out any problem
Here is the test
http://www.tjreb.com/xml_grabber.php?feed=http://www.youm7.com/newtkarirrss.asp&stack=1
Try The CNN rss feed
http://www.tjreb.com/xml_grabber.php?feed=http://rss.cnn.com/rss/edition_meast.rss&stack=0
How can i bypass this error
Here is my source code
<?php
  class xml_grabber
        {
            private $xml_file       = '' ;
            private $xml_link       = '' ;
            private $xml_dom        = '' ;
            private $xml_type       = '' ;
            private $xml_content    = '' ;
            private $xml_errors     = array() ;
            public  $xml_stack      = 0  ;

            public function __construct($link_file_com = '')
                   {
                       if(!$link_file_com)
                            {
                              $this->xml_errors['construct'] = 'No Xml In Construct' ;
                              return false;
                            }
                       elseif(!function_exists('simplexml_load_file') || !function_exists('simplexml_load_string') || !function_exists('simplexml_import_dom'))
                            {
                              $this->xml_errors['functions'] = 'simple xml function not exists' ;
                              return false;
                            }
                       else
                            {
                             $this->set_xml($link_file_com) ;
                            }
                      // ini_set('memory_limit', '100M');
                   }

             public function set_xml($xml)
                   {
                      if(isset($xml{3}))
                        {
                           if(file_exists($xml))
                              {
                                $this->xml_type = 1 ;
                                $this->xml_file = $xml ;
                              }
                          elseif(filter_var($xml, FILTER_VALIDATE_URL))
                              {
                                $this->xml_type = 2 ;
                                $this->xml_link = $xml ;
                              }
                          else
                              {
                                $this->xml_type = 3 ;
                                $this->xml_dom  = $xml ;
                              }
                        }
                      else
                        {
                          $this->xml_type = '' ;
                        }
                   }

             public function get_xml()
                   {
                      if($this->xml_type == '')
                            {
                              return false ;
                            }
                      elseif($this->xml_type == 1)
                            {
                              return $this->xml_file ;
                            }
                      elseif($this->xml_type == 2)
                            {
                              return $this->xml_link ;
                            }
                      elseif($this->xml_type == 3)
                            {
                              return $this->xml_dom ;
                            }
                   }

             public function set_columns($new_columns= array())
                   {
                      return $this->xml_columns = $new_columns ;
                   }
             public function get_columns()
                   {
                     return $this->xml_columns ;
                   }

             public function load()
                   {
                     if($this->xml_type == '')
                            {
                              $this->xml_errors['loader'] = 'Unknown XML type' ;
                              return false;
                            }
                      elseif($this->xml_type == 1)
                            {
                              $dom = simplexml_load_file($this->xml_file,null, LIBXML_NOCDATA) ;
                              $this->xml_content = $dom ;
                            }
                      elseif($this->xml_type == 2)
                            {
                               $con = $this->connect($this->xml_link);
                               if($this->xml_stack == 1)
                                    {
                                       echo $con; die();
                                    }
                               $this->xml_content = simplexml_load_string($con,null, LIBXML_NOCDATA) ;
                            }
                      elseif($this->xml_type == 3)
                            {
                              return $this->xml_dom ;
                            }
                   }

             public function fetch($return = 'array')
                    {
                        if($this->xml_content != '')
                            {
                               $rss_feed = $this->xml_content ;

                               $rss_title = (string) $rss_feed->channel->title ;
                               $rss_link  = (string) $rss_feed->channel->link  ;
                               $rss_cat   = (string) $rss_feed->channel->category  ;
                               $rss_image = (string) $rss_feed->channel->image->url  ;

                               $rss_summary =
                                            array
                                            (
                                              'info' =>
                                                        array(
                                                                'title'=>$rss_title ,
                                                                'link'=>$rss_link ,
                                                                'cat'=>$rss_cat ,
                                                                'image'=>$rss_image
                                                                ) ,
                                              'item' =>  array()

                                            ) ;

                               foreach($rss_feed->channel->item as $item)
                                       {

                                           if($item->enclosure && $item->enclosure->attributes())
                                                {
                                                    $image0 = $item->enclosure->attributes() ;
                                                    $image_url = $image0 ['url'] ;
                                                }

                                          $rss_summary['item'][] =
                                                                    array(
                                                                        'title' => (string) $item->title ,
                                                                        'description' => (string) $item->description ,
                                                                        'link' => (string) $item->link ,
                                                                        'date' => (string) $item->pubDate ,
                                                                        'image' => (string) $item->image ,
                                                                        'image2' =>  (string) $image0
                                                                    ) ;
                                       }

                                if($return == 'json')
                                       {
                                         return json_encode($rss_summary) ;
                                       }
                                elseif($return == 'serialize')
                                       {
                                         return serialize($rss_summary) ;
                                       }
                                elseif($return == 'xml')
                                       {
                                         return xml_encode($rss_summary) ;
                                       }
                                else
                                       {
                                         return $rss_summary ;
                                       }

                            }
                        else
                            {
                              $this->xml_errors['fetch'] = 'No Xml Content' ;
                            }
                    }

             protected function connect($link)
                    {
                      if(!filter_var($link, FILTER_VALIDATE_URL))
                              {
                                $this->xml_errors['connect'] = 'Not Vaild Link To Get data' ;
                                return false ;
                              }
                      if(function_exists('curl_init'))
                           {
                             $cu = curl_init();
                             curl_setopt($cu, CURLOPT_URL, $link);
                             curl_setopt($cu, CURLOPT_SSL_VERIFYPEER, false);
                             curl_setopt($cu, CURLOPT_SSL_VERIFYHOST, false);
                             //curl_setopt($cu, CURLOPT_REFERER, "http://www.tjreb.com");
                             //curl_setopt($cu, CURLOPT_HEADER, true);
                 //curl_setopt($cu, CURLOPT_FOLLOWLOCATION, false);
                 curl_setopt($cu, CURLOPT_RETURNTRANSFER, TRUE);
                             $co = curl_exec($cu) ;
                               if($co)
                                    {
                                        $con = $co ;
                                    }
                               else
                                    {
                                      $this->xml_errors['connect'] = 'No Result From Curl' ;
                                      $this->xml_errors['curl']  = curl_error($cu);
                                    }
                              curl_close($cu) ;
                              return $con ;
                           }

                    if(!$con and function_exists('ini_get'))
                        {

                             $url_fopen = ini_get('allow_url_fopen') ;

                             if($url_fopen == 0)
                                {
                                   if(function_exists('ini_set'))
                                        {
                                          ini_set('allow_url_fopen', 1) ;
                                        }
                                   $check_fopen = 1 ;
                                }
                             else
                                {
                                   $check_fopen = 0 ;
                                }

                             if($check_fopen == 1)
                                {
                                  $url_fopen = ini_get('allow_url_fopen') ;
                                }

                             if($url_fopen == 1)
                                {

                                  if(function_exists('file_get_contents') and !$con)
                                   {
                                        $con = @file_get_contents($link) ;
                                        if($con)
                                            {
                                              return $con ;
                                            }
                                       else
                                            {
                                              $this->xml_errors['connect'] = 'No Result From file_get_contents' ;
                                            }
                                   }

                              elseif(function_exists('readfile') and !$con)
                                   {
                                        $con = @readfile($link);
                                        if($con)
                                            {
                                              return $con ;
                                            }
                                       else
                                            {
                                              $this->xml_errors['connect'] = 'No Result From readfile' ;
                                            }
                                   }

                              elseif(function_exists('file') and !$con)
                                   {
                                        $con = @file($link)  ;
                                        if($con)
                                            {
                                              return  $con ;
                                            }
                                       else
                                            {
                                              $this->xml_errors['connect'] = 'No Result From file' ;
                                            }
                                   }

                                }
                        }

                      if(!$con)
                           {
                             $this->xml_errors['connect'] = 'Curl And Allow Url Fopen Disabled On Server' ;
                             return false ;
                           }
                    }

             public function get_error()
                    {
                       return $this->xml_errors ;
                    }

        }

if(isset($_GET['feed']))
    {
       $url = addslashes($_GET['feed']) ;
    }
else
    {
       $url = 'http://rss.cnn.com/rss/edition_meast.rss' ;
    }

$fetch = $_GET['fetch'] ;
$stack = $_GET['stack'] ;

$xml = new xml_grabber($url) ;

/*
 http://www.youm7.com/new3agelrss.asp
 http://www.youm7.com/newtkarirrss.asp
 http://www.almasryalyoum.com/rss_feed_term/223241/rss.xml
 http://gdata.youtube.com/feeds/api/playlists/18A7E36C33EF4B5D?v=2
 http://rss.cnn.com/rss/edition_meast.rss
 https://www.facebook.com/feeds/page.php?format=atom10&id=40796308305
 https://www.facebook.com/feeds/page.php?format=rss20&id=40796308305
 http://www.fwasl.com/feed
 https://www.facebook.com/feeds/page.php?format=atom10&id=378156838895039
 */

if(isset($stack))
{
  $xml -> xml_stack = intval($stack) ;
}

$res    = $xml -> load()    ;

$result = $xml -> fetch($fetch)   ;

if($result)
    {
      print_r ( $result ) ;
    }
else
    {
      print_r ( $xml->get_error() ) ;
    }

?>

A: You can't easily bypass Cloudflare. However you can hack the protection system. :)
First, parse the page (Cloudflare protection page) and calculate 3+13*7 (most probably this will be different for each request.) in
$(function(){setTimeout(
            function(){
                $('#jschl_answer').val(3+13*7);
                $('#ChallengeForm').submit();
            },
            5850
)});

Then send post request the same page with "jschl_vc" value from #ChallengeForm which you got from parsed data and "jschl_answer" value as 3+13*7. And then try to fetch the page again with the cookie value that Cloudflare added. When you're added Cloudflare whitelist, you won't see that page anymore.

A: You can pass cloudflare protection with PhantomJS http://phantomjs.org/
which can execute the cloudflare JS outside a browser with following little script "delay.js":
"use strict";
var page = require('webpage').create(),
    system = require('system'),
    address, delay;

if (system.args.length < 3 || system.args.length > 5) {
    console.log('Usage: delay.js URL delay');
    phantom.exit(1);
} else {
    address = system.args[1];
    delay = system.args[2];
    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit(1);
        } else {
            window.setTimeout(function () {
                var content = page.content;
                console.log(content);
                phantom.exit();
            }, delay);
        }
    });
}

run it as
phantomjs delay.js http://protected.url 5000
This will get "protected.url" and wait 5000ms for the cloudflare code to load the real page and dumps it to stdout.

A: You need to tell their site what browser your using.
curl_setopt ($cu, CURLOPT_USERAGENT, $user_agent);

e.g. Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)
or use the current users own browser agent using $_SERVER['HTTP_USER_AGENT']


text:
Q: Displaying Loading Indicator in JQuery Mobile How can we programmatically display the page loading indicator in JQuery Mobile?

A: $.mobile.loading("show");
$.mobile.loading("hide");

http://jquerymobile.com/demos/1.2.0/docs/api/methods.html