text:
Q: Processing Mandrill Inbound emails I am having trouble processing inbound emails from mandrill with Meteorjs. I am a bit of a newbie when it comes to writing server side routes / API routes, so I hope I am not overlooking something insanely basic.
This is the iron-router route i have defined:
It gets the post call, creates a message object and inputs the object into my collection.
Router.route('/api/message/insert', function () {
  // NodeJS request object
  var request = this.request;

  request = JSON.parse(request.body.mandrill_events);
  console.log(request);
  var firstEmail = request[0];

  if(firstEmail.event == "inbound"){ // == used on purpose
    var email = firstEmail.msg.from_email;
    var user = Meteor.users.findOne({"emails[0].address":email });
    var chatRoom = chatRooms.findOne({name:user_.id});
    var message = {
      content:firstEmail.msg.text,
      links:[],
      chatRoom:chatRoom._id,
      owner:user._id,
      ownerName:user.profile.name,
      ownerEmail:email,
      createdAt: new Date(),
    };
    chatMessages.insert(message);
  }
  // NodeJS  response object
  var response = this.response;

  this.response.end("chat message implemented");
}, {where: 'server'});

When I send test emails from the mandrill dashboard I get a positive response. Actually sending an email to the address that I registered with mandrill does nothing. I am having a hard time debugging this because I get no error code in my Modulus logs (also the console.log does nothing).
I have found this guide
http://dev-blog.cloud-spinners.com/2014/03/sending-and-receiving-email-using.html
but i can't seem to see what I am doing fundamentally wrong here. I am aware that I need to process the email body further, but this is simply to get a "hello world" message into my database.

A: iron-router doesn´t support multipart/form-data. I´ve used the following code with sendgrid.
var Busboy = Meteor.npmRequire("Busboy"),
    fs = Npm.require("fs"),
    os = Npm.require("os"),
    path = Npm.require("path");

Router.onBeforeAction(function (req, res, next) {
   var filenames = []; // Store filenames and then pass them to  request.
   req.body   = req.body  || {};

if (req.method === "POST") {
    var busboy = new Busboy({ headers: req.headers });
    busboy.on("file", function (fieldname, file, filename, encoding, mimetype) {
    var saveTo = path.join(os.tmpDir(), filename);
    file.pipe(fs.createWriteStream(saveTo));
    filenames.push(saveTo);
    });

    busboy.on("field", function(fieldname, value) {

    req.body[fieldname] = value;

    });

   busboy.on("finish", function () {
  // Pass filenames to request
    req.filenames = filenames;
    next();
   });
}
  // Pass request to busboy
  req.pipe(busboy);
});

You can then get it in your route:
Router.route('inbound', {
 path: '/inbound/',
 where: 'server',
 action: function () {

 var body = this.request.body;
 console.log(body);
 ...

You will have to add the following package to use npm packages:meteor add meteorhacks:npm and add a packages.json file to the root of your project and add the following:
{ "busboy": "0.2.9"}


text:
Q: k8s - Why we need ReplicaSet when we have Deployments I am new to kubernetes and microservices, there are 2 objects, Deployments and ReplicaSet.
I can't wrap my head around even after reading its documentations and other articles.
If we have Deployments, why do we need a ReplicaSet because you can specify the replicaset in the Deployment. And when i delete the pods, new pods will be spawned based on the replicaset, just like the deployments.
Like what is the actual use-case where we only need ReplicaSet but not Deployments

A: deployment is for stateless application and we can update our application by it.
by replicaset we can not update our application easily and it has a lot of work to do to update our application.

A: Deployment works one level above ReplicaSet object. Deployment is recommended for application services.
With deployment you should be able to do rolling upgrade or rollback. You can update image from v1 to v2.
With ReplicaSet you define number of replicas you want to run. For a particular service. You would have those many replicas running.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to debug ruby code I want to debug my Ruby code using the Ruby Mine IDE. In the drop down list Select Run/Debug Configuration, I chose My Project - development, then pressed Shift + F9. The Debugger started well, but did not stop at my break points. Why?

A: Ensure your Gemfile contains this:
gem 'linecache19', '>= 0.5.13', :git => 'https://github.com/robmathews/linecache19 0.5.13.git'
gem 'ruby-debug-base19x', '>= 0.11.30.pre12'
gem 'ruby-debug-ide', '>= 0.4.17.beta17'

maybe for details see that answer

A: Try using command line debugger: https://github.com/cldwalker/debugger
See also

*

*http://railscasts.com/episodes/54-debugging-with-ruby-debug

*http://railscasts.com/episodes/54-debugging-ruby-revised

A: pry is an interactive Ruby shell (or "REPL"), which can be used as a debugger (best combined with the pry-nav and pry-stack_explorer gems). It has a lot of features which make it much nicer to use than the debugger gem. For general exploration and experimentation with Ruby code, it's also nicer to use than irb.
For more info:
http://pryrepl.org/
https://github.com/pry/pry
After adding pry to your Gemfile and bundling, you can add a "breakpoint" with the following  Ruby code: binding.pry


text:
Q: Git on Windows 8: "git-pull is broken?" error When I run 'git pull' from TortoiseGit on my Windows 8 machine, I get the following error:
fatal: 'pull' appears to be a git command, but we were not
able to execute it. Maybe git-pull is broken?
I have found someone else who had this error. They resolved it by uninstalling/reinstalling Git. I tried that and it did not work. I also uninstalled/reinstalled TortoiseGit. Nothing helps. Any ideas? Thanks.

A: Do you have Cygwin installed on your machine? If so try selecting "Use Git bash only" in "Adjusting your ENV. Path" windows


text:
Q: Rectangle till the end of the page Sometext that occupies one third of the page. After this a rectangle needs to be drawn that will carry on till the end of the current page. Basically its a question paper and I am providing spaces for the students to write their answers in the empty box.
\begin{tikzpicture}
\node (rect) at (0,0) [draw, text width=16.6 cm, minimum height=7cm]{};
\node[below right, text width=16.6 cm] at (rect.north west) {};
\end{tikzpicture}

\pagebreak

Some text with one line. After this the rectangle should be drawn till the end of the page.
\begin{tikzpicture}
\node (rect) at (0,0) [draw, text width=16.6 cm, minimum height=7cm]{};
\node[below right, text width=16.6 cm] at (rect.north west) {};
\end{tikzpicture}

As you see, I am explicitly writing the text width and minimum height. I would like to do it automatically, with the page width and height so that the rectangle is made automatically depending on the space left after the last line. The beginning of the rectangle, however, could be from anywhere in the page. ( EDIT: The beginning of the rectangle starts after the end of the previous line )

A: You can calculate the remaining height of a page with the help of \pagegoal and \pagetotal. The latter contains the height of the text so far and the first the height available for text (not \textheight, because there may be floats and/or footnotes on the page). \baselineskip must be substracted, because the picture starts in a new line. And \parskip is substracted, so the box gets set further below the text in case a non-zero \parskip is used.
I also took the freedom to adjust the width to \textwidth. The -0.4pt is an adjustment for the width of the lines. Edit: Otherwise there will be an overfull \hbox warning.
Edit: I changed the code, so it works for pages with no text. Again, the -0.4pt adjusts for the line width and prevents an overfull \vbox warning.
This needs a \newpage before the rectangle on a page with no text.
Edit 2: the rectangle didn't go all the way to the bottom of the page.
I replaced -\baselineskip by -\lineskip-0.4pt to correct this (again, -0.4pt to adjust for the lines).
Note: if another line width is used for the frames, all occurrences of -0.4pt must be replaced by -<new line width>. Otherwise overfull boxes may occur or the rectangle on a page with text may be moved to the next page.
Edit 3: removed -parskip. This wasn't necessary.
\documentclass[a4paper]{article}
\usepackage{tikz}
\usepackage{lipsum}

\newdimen\remainingheight
\newcommand*{\calcremainingheight}{%
    \ifdim\pagegoal=\maxdimen
        \remainingheight\dimexpr\textheight-0.4pt\relax
    \else
        % edit 2: replaced -\baselineskip by -\lineskip-0.4pt
        % edit 3: removed -\parskip
        \remainingheight\dimexpr\pagegoal-\pagetotal-\lineskip-0.4pt\relax
    \fi
}

\parskip2ex
\parindent0pt

\begin{document}
\lipsum[1]

\noindent
\begin{tikzpicture}
\calcremainingheight
\node (rect) at (0,0) [draw, minimum width=\textwidth-0.4pt, minimum height=\remainingheight]{};
%\node[below right, text width=16.6 cm] at (rect.north west) {};
\end{tikzpicture}

\lipsum[1-2]

\noindent
\begin{tikzpicture}
\calcremainingheight
\node (rect) at (0,0) [draw, minimum width=\textwidth-0.4pt, minimum height=\remainingheight]{};
%\node[below right, text width=16.6 cm] at (rect.north west) {};
\end{tikzpicture}

% needed for a page with no text before the rectangle
\newpage
\noindent
\begin{tikzpicture}
\calcremainingheight
\node (rect) at (0,0) [draw, minimum width=\textwidth-0.4pt, minimum height=\remainingheight]{};
%\node[below right, text width=16.6 cm] at (rect.north west) {};
\end{tikzpicture}
\end{document}

A: Here are two solutions.  One is intended to be placed at the end of the previous line of text.  The other is intended to be placed at the start of a new line of text.  It ignores indentation or centering.
Note that in overlay mode, the origin will be located on the baseline, so some offset is needed.  \strutbox is the same size as \strut.
Don't forget to run it twice.
\documentclass{article}
\usepackage{tikzpagenodes}
\usepackage{lipsum}% MWE only

\begin{document}
Some text on one line.
\begin{tikzpicture}[remember picture,overlay]% still on same line as text
  \path (0pt,-\dp\strutbox) -| (current page text area.west) coordinate[midway] (start);
  \draw (start) rectangle (current page text area.south east);
\end{tikzpicture}

\lipsum[1-6]

\begin{tikzpicture}[remember picture,overlay]% start of new paragraph
  \path (0pt,\ht\strutbox) -| (current page text area.west) coordinate[midway] (start);
  \draw (start) rectangle (current page text area.south east);
\end{tikzpicture}
\lipsum[7-11]
\end{document}

A: tcolorbox offers height fill option to solve this kind of problems:
\documentclass{article}
\usepackage[most]{tcolorbox}
\usepackage{lipsum}

\begin{document}
\lipsum[1]
\begin{tcolorbox}[height fill, title=Your solution]
\end{tcolorbox}

\lipsum[2]
\begin{tcolorbox}[height fill, sharp corners, colback=white]
\end{tcolorbox}
\end{document}


text:
Q: NodeJs expressjs estructure The idea is to develop a nodejs server for a web (js, css and html) and mobile app (with nativescript core).
The server will connect to MySQL, but the idea is make it reusable. I have to do many projects (any ones with MySQL, others with sql server, json database). I have the idea to develop a modular server, but I have not mucha idea about this.
I found examples with MVC pattern (a folder with alll views, another one for all controllers...) I think that could't be the best opcion in my case.
Are there any (easy to learn) documentation about doing it like components? All I found is min four yearls old. Is recomendable to use expressjs? Could be better to use MVC?


text:
Q: How can I unregister a handler set to jQuery.ajaxStart() function? I tried doing $.ajaxStart(function(){}), but it does not replace it, but appended.

A: Set global option to false

$.ajaxSetup({ global: false });

http://api.jquery.com/jQuery.ajaxSetup/

A: Worth to note that since jQuery 1.9, the .ajaxStart() must be attached to the document, hence you can't attach it to an element, or unbind from an element other than document for that matter:

As of jQuery 1.9, all the handlers for the jQuery global Ajax events, including those added with the .ajaxStart() method, must be attached to document.

A: If I understand, you want to remove the ajaxStart handler from the element.
If so, just use jQuery's unbind() since the handler is attached as an event.
$('selector').unbind('ajaxStart');

*

*http://api.jquery.com/unbind/

*http://api.jquery.com/ajaxStart/

A: This worked for me.
$(document).ready(function () {
   $(document).unbind('ajaxStart');
   $(document).unbind('ajaxStop');
 });


text:
Q: searchBox Google Maps with pagination So what I am trying to do is implement Google Maps with a search box. Currently, the search box retrieves 20 of the top places based on the search result.
What I noticed is there is no pagination with this. Such as if I type in "pizza", it will give me the top 20 results in the current location bounds. But when I use the google.maps.places.PlacesService(map) textSearch function to obtain a list of pizza searches, I get more than 20 results with pagination.
Is there a way to get pagination on your searchBox or use the textSearch function to provide pagination after you used searchBox?
What I have here is a snippet:
var canvas = element.find('div')[0];
var mapOptions = {
    zoom: 5,
    minZoom: 2,
};
var searchBox = new google.maps.places.SearchBox('pizza');
var placeService = new google.maps.places.PlacesService(map);

google.maps.event.addListener(searchBox, 'places_changed', locationChange);

function locationChange() {
    var places = searchBox.getPlaces();
    //Determine if there are additional places not provided by searchbox. Using text
    var request = {
        query: input.value,
    };
    var textSearchPlaces = placeService.textSearch(request, callback);
    function callback(results, status, pagination) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            var hi = places;
            for (var i = 0; i < results.length; i++) {
                var place = results[i];
            }
        }
    }
    if (places.length === 0) {
        return;
    }
};

As you can see this is not the most ideal solution to looking using a pagination as I would have to filter through the textSearchPlaces to see if those places are not duplicates of the searchBox results.
I also thought about just removing the searchBox and just going with the textSearch function but I realized I wouldn't have the autoComplete function that provides suggestions that searchBox provides.

A: Most likely you are getting  OVER_QUERY_LIMIT.
if (status == google.maps.places.PlacesServiceStatus.OK) {
Try queuing the  details requests for after you have all the list completed, adding the same timeout logic to check for google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT on this line.
if (pagination.hasNextPage) {
//add all places to the list
setTimeout('pagination.nextPage()',2000);
}  else {
createMarkers(placesList);
}

You should use google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT when using Places.


text:
Q: Bug or feature: no focusOwner if control added to scene directly? Just noticed that a scene with a "bare" control as root (in the example below the control is a TableView) doesn't have a focusOwner initially. In fact, there is no focusOwner at all (scene's property doesn't fire). Without focusOwner, the control is not reachable via keyboard. Not a very realistic real-world scenario, concededly, but anyway ...
Adding the control to any Parent and then setting that parent as root transfers focus to the control - which is what I expect always.
What's wrong - my expectation or the behaviour?
/**
 * Table doesn't have focus initially if not wrapped into a Parent.
 * jdk 8u60b5 (didn't try others)
 */
public class TableInitialCellEdit extends Application {

    ObservableList<MenuItem> data = FXCollections.observableArrayList(
            new MenuItem("some"),
            new MenuItem("dummy"),
            new MenuItem("data")
            );

    private Parent getContent() {
        TableView<MenuItem> table = new TableView<>(data);
        table.setEditable(true);
        TableColumn<MenuItem, String> text = new TableColumn<>("Text");
        text.setCellValueFactory(new PropertyValueFactory<>("text"));
        text.setCellFactory(TextFieldTableCell.forTableColumn());
        table.getColumns().addAll(text);
        // focus transfered to table if contained in a pane
        // return new Pane(table);
        // focus not transfered to table if contained directly in the scene
        return table;
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Scene scene = new Scene(getContent());
        scene.focusOwnerProperty().addListener((s, old, value) -> System.out.println(value));
        primaryStage.setScene(scene);
        primaryStage.setTitle(VersionInfo.getRuntimeVersion());
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

A: Judging from the documentation of Node.requestFocus(), I would consider this behaviour a bug.
My guess is the bug lies in the method .com.sun.javafx.scene.traversal.TabOrderHelper#getFirstTargetNode(Parent)
public static Node getFirstTargetNode(Parent p) {
    if (p == null || isDisabledOrInvisible(p)) return null;
    final ParentTraversalEngine impl_traversalEngine = p.getImpl_traversalEngine();
    if (impl_traversalEngine!= null && impl_traversalEngine.canTraverse()) {
        Node selected = impl_traversalEngine.selectFirst();
        if (selected != null) {
            return selected;
        }
    }
    List<Node> parentsNodes = p.getChildrenUnmodifiable();
    for (Node n : parentsNodes) {
        if (isDisabledOrInvisible(n)) continue;
        final ParentTraversalEngine parentEngine = n instanceof Parent ? ((Parent)n).getImpl_traversalEngine() : null;
        if (parentEngine != null ? parentEngine.isParentTraversable() : n.isFocusTraversable()) {
            return n;
        }
        if (n instanceof Parent) {
            Node result = getFirstTargetNode((Parent)n);
            if (result != null) return result;
        }
    }
    return null;
}

If I read this correctly, it recurses down the hierarchy of p to find a suitable Node to focus. p in this case is the table. It recurses through its childrens children but never finds a Node to focus until it return null. The problem might be, that this method never considers to return p itself.


text:
Q: How do I rotate a SCNNode around a point? I have a SCNNode - sceneNode - which is a child of rootNode and contains all of my child nodes. Upon the user tapping a button, I want to rotate the scene around a certain point on the y-axis. For example, the camera's point of view is known, and I want to rotate everything by 90º around the camera. The camera is no longer at 0, 0, 0.
I've tried playing around with the SCNMatrix4MakeTranslation function, and then changing the y value on the euler angles, but I've not been able to get it to work expectedly.

A: Your question is rather ambiguous, if you were to rotate the entire scene 90degrees "around the camera" the scene would end up next to the camera and you wouldn't see it.
To rotate a SCNNode around a point other than its own pivot, as the question in the title, create a translation matrix that moves it to that point, multiply with a rotation matrix to the SCNNode, and then multiply with the inverse of the translation matrix.
However, what you probably want to do instead is do basically the same process with the camera node instead of the sceneNode. That will make the camera move around the sceneNode, giving the appearance the scene is rotating in place.
For example:
//get the current camera's transform and store it in cammat
GLKMatrix4 cammat = SCNMatrix4ToGLKMatrix4(self.myView.pointOfView.transform);

//create a rotation matrix of 90 degrees over axis Y
GLKQuaternion quaty = GLKQuaternionMakeWithAngleAndAxis(M_PI/2, 0, 1, 0);
GLKMatrix4 rotMat = GLKMatrix4MakeWithQuaternion(quaty);

//set the camera transform to rotMat * cammat, which basically rotates the camera first, and then moves it back to the same offset it was.
self.myView.pointOfView.transform = SCNMatrix4FromGLKMatrix4(GLKMatrix4Multiply(rotMat, cammat));


text:
Q: is there a way to have full control over a browser in a native iOS app? I have a chrome plugin I've written that does stuff like:

*

*sets cookies on the user's behalf

*visits a certain sequence of urls, posting form data, and reading returned HTML and cookies
(this has to be from a real browser, not a series of programmed http connections.)

*opens tabs to specific urls

Basically in the chrome plugin world I have complete control to do almost anything (once the user agrees and installs the plugin.)
In there any way to do this in a native iOS app?  I realize there is no plugin system for either safari or chrome on iOS.  Do I stand a chance using UIWebView?  Or is UIWebView way too limited?  Is there a complete webkit or mozilla browser code in Objective-C I can use and modify for my needs?  Thanks!

A: This is most definitely possible if you are building a native iOS application.
1) You can communicate with cookies with the NSHTTPCookieStorage APIs.
2) You can send network requests and process their data on a background queue, after which you can then set the HTML content of the UIWebView (on the main queue.)
3) Your "tabs" can simply be sibling view controllers which each contain a UIWebView.


text:
Q: how much effect does number of function calls have on performance? Does calling more functions have any kind of noticeable effect of performance, or is trying to cut down on number of function calls a pointless premature optimization?
Simplified Example: Is there any real performance example between this:
function foo($var) {
    echo $var;
}
foo();

And This:
function foo($var) {
   bar($var);
}

function bar($var) {
  baz($var);
}

function baz($var) {
  echo $var;
}

foo();

A: It's premature optimization.  You should have functions that make sense based on your domain and the logical separation of tasks in your code.  The only time I would ever consider replacing a function with inline code is if it was in a tight loop and a profiler showed it was a problem.
To more directly answer your question, the effect on performance hinges on quite a few things:

*

*How often is the function called?

*Is it in a critical section of the code?

*How large is/are the function(s)?

Deciding on whether something should be in a function should be driven by logical separation, clarity, maintainability, etc. and not performance.

A: Always do profiling first, then bother with optimizations.
On the other hand, function calls do have some overhead, but you should really profile your code before you decide to optimize out function calls.

A: To answer your question in the simplest way No.
Now for the longer answer, function overhead is so small that you won't begin to notice it until you've made at least several million calls on a particular function.  In most UI programs that very rarely happens having millions of calls to a method.  What's inside your function is going to contribute vastly more to your performance than the overhead associated with calling the function.
To further illustrate my point.  Computers operate on the nanosecond timeframe.  Humans can detect about 10 milliseconds (from UI testing).  1ms = 1.0 × 10^6 ns.  So if it takes 1ns to call your function you'd need to call it between 1 million to 10 million times before a human could tell the difference.
If an function's contents is expensive to call then reducing when you call it can help performance, but again that has everything to do with what's inside the function and NOT the act of calling the function.
Never try and optimize before you've measured it.  I'll say it again never never try and predict what will be performant in your application.  Always measure performance with a profiler.  It's like trying to predict the bugs in your program before you've written it.

A: The overhead of a function call is pretty stiff actually.  But it's still low in the grand scheme of things.  If you're only calling the chain a handful of times in the execution, don't worry about it.  If you're going to be looping a lot, then you may want to consider optimizing it a little bit.
But remember, the biggest performance gain is the transition from a non-working state to a working one.  Only then start tackling the actual bottlenecks...  And never forget: Premature optimization is the root of all evil...

A: I wouldn't worry about speed so much as about memory, since each function call costs stack. Again, worrying about this in examples like yours would be premature optimization, but it's good to have it in mind if you're planning for a recursive algorithm in a language that's not optimized to handle recursive function calls.


text:
Q: How to join two ArrayLists with the same index in Java I have the following ArrayLists:
ArrayList <String> restricciones_numeros = new ArrayList();
ArrayList <String> restricciones_signos = new ArrayList();

And they contain:
restricciones_numeros: [, , , , , , , , 230, 230, 230, 5000, 4000, 4000, , 17000, ]
restricciones_signos : [, , , , , , , , -, -, -, +, +, +, , , ]
They have the same size and how you can realize there are empty items, but it dosen't matter.
I need to join each ArrayList with the same index, the result must be:
[, , , , , , , , 230-, 230-, 230-, 5000+, 4000+, 4000+, , 17000, ]
I tried this:
for(int i = 0; i < restricciones_signos.size(); i ++){
    numeros_signos.add(restricciones_numeros.get(i));
    numeros_signos.add(restricciones_signos.get(i));
}
System.out.println("numero y signo de cada restriccion: "+numeros_signos);

But this for loop returns me:
[, , , , , , , , , , , , , , , , 230, -, 230, -, 230, -, 5000, +, 4000, +, 4000, +, , , 17000, , , ]
This is only an example, but the program must to be generic, the arraylists can have other numbers, other sizes and other empty items. But always both of them have the same size.

A: You can transform your algorithm like this :
for(int i = 0; i < restricciones_signos.size(); i++) {
    numeros_signos.add(restricciones_numeros.get(i) + restricciones_signos.get(i));
}


text:
Q: Linux driver: example scatterlist usage for DMA/PCIe Has anyone found an example driver that uses the new-ish scatterlist API (dma_map_sg, etc, for 2.6.26+)?
I have lots of disjoint documentation but no example code. I'd rather not have to download the entire kernel tree and search for drivers which may, or may not, use the API correctly.
After several hours searching for PCIe drivers I've got the Altera Avalon code, which doesn't do anything complicated and which is a great example of keep-your-code-propietary-by-not-commenting-it, and the Opencores pexdrv, which doesn't use scatterlists. I couldn't find anything useful at Xilinx. Thanks.
EDIT
Before I get any more close votes, "how to use an API" is a perfectly legitimate programming question, and if the only concrete example is code which is out there somewhere, then surely "where is that example code" is also a legitimate question.


text:
Q: Access violation when trying to populate an array of struct Original code comment specifying the core question:

The error I am getting is while iterating through the while loop,
  memory out of range or something... resizing to 300 ... Access
  violation writing location that's the exact Fraze...

I'm trying to implement a faster .Net List<T> equivalent in C.
I'm using blittable data types in C#.
In the code below I've moved a function body to the main function just for testing  after I have failed to understand where am I wrong.
The problem seems to be that inside the while loop UntArr does not increment.
What am I doing wrong?
typedef struct {
    int Id;
    char *StrVal;
}Unit; // a data unit as element of an array

unsigned int startTimer(unsigned int start);
unsigned int stopTimer(unsigned int start);

int main(){

Unit *UntArr= {NULL};
//Unit test[30000];

//decelerations comes first..
char *dummyStringDataObject;
int adummyNum,requestedMasterArrLength,requestedStringSize,MasterDataArrObjectMemorySize,elmsz;
int TestsTotalRounds, TestRoundsCounter,ccountr;
unsigned int start, stop, mar;

//Data Settings (manually for now)
requestedMasterArrLength=300;
requestedStringSize = 15;

//timings
start=0;stop=0;
//data sizes varies (x86/x64) compilation according to fastest results
MasterDataArrObjectMemorySize = sizeof(UntArr);
elmsz= sizeof(UntArr[0]);

TestRoundsCounter=-1;
start = startTimer(start);

while(++TestRoundsCounter<requestedMasterArrLength){
    int count;
    count=-1;
    //allocate memory for the "Master Arr"
    UntArr = (Unit *)malloc(sizeof(Unit)*requestedMasterArrLength);
    dummyStringDataObject = (char*)malloc(sizeof(char)*requestedStringSize);
    dummyStringDataObject = "abcdefgHijkLmNo";
    while (++count<requestedMasterArrLength)
    {
        dummyStringDataObject[requestedStringSize-1]=count+'0';
        puts(dummyStringDataObject);

        ccountr=-1;
        // tried
        UntArr[count].Id = count;
        UntArr[count].StrVal = (char*)malloc(sizeof(char)*requestedStringSize);
        UntArr[count].StrVal = dummyStringDataObject;// as a whole
        //while(++ccountr<15)// one by one cause a whole won't work ?
        //UntArr[count].StrVal[ccountr] = dummyStringDataObject[ccountr];

    }

free(UntArr);free(dummyStringDataObject);

}
stop = startTimer(start);
mar = stop - start;

MasterDataArrObjectMemorySize = sizeof(UntArr)/1024;
printf("Time taken in millisecond: %d ( %d sec)\r\n size: %d kb\r\n", mar,(mar/1000),MasterDataArrObjectMemorySize);
printf("UntArr.StrVal: %s",UntArr[7].StrVal);

getchar();

return 0;
}

 unsigned int startTimer(unsigned int start){
     start = clock();
     return start;
 }
 unsigned int stopTimer(unsigned int start){
     start = clock()-start;
     return start;
 }

testing the code one by one instead of within a while loop work as expected
//allocate memory for the "Master Arr"
UntArr = (Unit *)malloc(sizeof(Unit)*requestedMasterArrLength);
UntArr[0].Id = 0;
dummyStringDataObject = (char*)malloc(sizeof(char)*requestedStringSize);

dummyStringDataObject = "abcdefgHijkLmNo";

////allocate memory for the string object
UntArr[0].StrVal = (char*)malloc(sizeof(char)*requestedStringSize);
////test string manipulation
adummyNum=5;
UntArr[0].StrVal= dummyStringDataObject;
//
UntArr[0].StrVal[14] = adummyNum+'0';
////test is fine

A: as it happens and as i am new to pointers i have not realize that when debugging
i will not see the elements of given pointer to an array as i am used to
with normal Array[] but looping through result which i did not even try as when i was hovering  above the Array*  within the while loop expecting to see the elements as in a normal array:
Data[]  DataArr = new Data[1000] <- i have expected to actually see the body of the array while looping and populating the Data* and did not realize it is not an actual array but a pointer to one so you can not see the elements/body.
the solution is via a function now as planed originally :
void dodata(int requestedMasterArrLength,int requestedStringSize){

    int ccountr,count;
    count=0;
    UntArr=NULL;
    UntArr = (Unit *)malloc(sizeof(Unit)*requestedMasterArrLength);

        while(count!=requestedMasterArrLength)
        {
                char dummyStringDataObject[]= "abcdefgHi";

                UntArr[count].StrVal=NULL;

                dummyStringDataObject[requestedStringSize-1] = count+'0';
                UntArr[count].Id= count;
                ccountr=0;
                UntArr[count].StrVal= (char*)malloc(sizeof(char)*requestedStringSize);
                    while(ccountr!=requestedStringSize){
                        UntArr[count].StrVal[ccountr] = dummyStringDataObject[ccountr];
                        ++ccountr;
                    }
            ++count;
        }

}

generaly speaking, x86 compilation would get better performance for this current task , populating an array of a struct.
so i have compiled it also in c++ and c#.
executing similar code in C#  and C++
minimum time measured in c# ~ 3,100 ms.
minimum time measured in this code - C ~ 1700 ms.
minimum time measured in C++ ~ 900 ms.
i was surprised to see this last result c++ is the winner but why.
i thought c is closer to the system level, CPU, Memory...


text:
Q: Returning *this with non-reference return type changes value in calling object I am attempting to implement a linked list class in c++ to better understand them but I have run into something I find weird. I debugged with Visual Studio to see the results described below.
My problem was that before my function appendNode returned *this with a non-reference return type:
list<T> list<T>::appendNode(T value) {}

the values in the calling object's head node were set to the correct values, but after the function returned, the values in the calling object's head node had garbage, or at least definitely not what I set them as. My head->node pointer is always set to 0xddddddd and my program crashes on the second call to appendNode.
My solution is to make it return a reference:
list<T> &list<T>::appendNode(T value) {}

the solution works, all values are correct and the program runs fine.
The address of liOne isn't getting changed after each iteration so it still has the same head value, and head is still pointing to the same node. I've checked everything in the debugger.
My question is, why are the values in the calling object's head member being set to garbage with a non-reference return type?
My code with the non-reference return type:
#ifndef LIST_H
#define LIST_H

#include <iostream>

template<class T>
class list
{
private:
    class ListNode
    {
    public:
        T value;
        ListNode * node;
    };
    ListNode * head;
public:
    list();
    list(T value);
    ~list();
    list<T> appendNode(T value);
    list<T> insertNode(T value);
    list<T> deleteNode(T value);
    void displayList() const;
};

/*
    Constructor list() creates an empty list with the head pointed to null
 */
template <class T>
list<T>::list()
{
    head = nullptr;
}

/*
    Constructor list(T value) creates a list and creates the first node with
        the value value.
    Parameters:
        T value : the value of the first node created is initialized with
 */
template <class T>
list<T>::list(T value)
{
    head = new ListNode();
    head->value = value;
    head->node = nullptr;
}

/*
    appendNode adds a new node to the end of the list
    Parameters:
        T value - the value to place in the new node
    Return:
        returns this for chain calling
 */
template <class T>
list<T> list<T>::appendNode(T value)
{
    ListNode * newNode = new ListNode();
    newNode->value = value;
    newNode->node = nullptr;

    ListNode * nextNode = nullptr;

    if (!head)
    {
        head = newNode;
    }
    else
    {
        nextNode = head;
        while (nextNode->node)
        {
            nextNode = nextNode->node;
        }
        nextNode->node = newNode;
    }

    return *this;
}

/*
    displayList displays the list contents
 */
template <class T>
void list<T>::displayList() const
{
    ListNode * currNode = head;

    while (currNode)
    {
        std::cout << currNode->value << " ";
        currNode = currNode->node;
    }
}

template <class T>
list<T>::~list()
{
    ListNode * currNode = head;
    ListNode * nextNode = nullptr;

    while (currNode)
    {
        nextNode = currNode->node;

        delete currNode;

        currNode = nextNode;
    }
}

#endif

Driver:
    #include <iostream>

#include "list.h"

int main(int argc, char * argv[])
{
    list<int> liOne;
    list<int> liTwo(0);

    liOne.appendNode(3);
    liOne.appendNode(4);

    liTwo.appendNode(1);
    liTwo.appendNode(2);

    liOne.displayList();
    std::cout << std::endl;

    liTwo.displayList();
    std::cout << std::endl;

    std::cout << "Press <ENTER> to exit...";
    std::cin.get();
    return 0;
}


text:
Q: How to send request to soap webservice in ios? hi i want to send request to the soap webservice. I tried in AFnetworking and getting internal server error 500 and now iam trying in nsurlconnection but it also showing status code 400. Please any one help me. Thank you Advance hear is My code.
NSString *soapString = [NSString stringWithFormat:
                                    @"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"><soap12:Body><addBusOrder xmlns=\"http://tempuri.org/\"><UserUniqueID>ok//8FjcvEKWMeeJJZHKYA</UserUniqueID><PlatFormID>4</PlatFormID><DeviceID>E3D2FCF6-F41B-4275-BD34-FAA31307EFFE</DeviceID><RouteScheduleId>532875503</RouteScheduleId><JourneyDate>2016-03-25</JourneyDate><FromCityid>734</FromCityid><ToCityid>202</ToCityid><TyPickUpID>22860424</TyPickUpID><Contactinfo><Name>vinod</Name><Email>katragadda.vinod@gmail.com</Email><Phoneno>7842768497</Phoneno><mobile>8801720427</mobile></Contactinfo><pass><passenger><passengerName>kumar</passengerName><Age>23</Age><Fare>1072</Fare><Gender>M</Gender><Seatno>D3</Seatno></passenger></pass></addBusOrder></soap:Body></soap:Envelope></addBusOrder></soap12:Body></soap12:Envelope>"];
            NSLog(@"soapString %@",soapString);

    NSString *msgLength = [NSString stringWithFormat:@"%li", [soapString length]];

    NSString *queryString = [NSString stringWithFormat: @"https://asprel.in/Service/AppServices.asmx/addBusOrder"];

    NSURL *url = [NSURL URLWithString:queryString];

    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];

    [req addValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [req addValue:@"http://tempuri.org/addBusOrder" forHTTPHeaderField:@"SOAPAction"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [soapString dataUsingEncoding:NSUTF8StringEncoding]];

    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            NSLog(@"error %@",connectionError);
        }else{
            NSLog(@"data %@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        }

        NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];
        [parser parse];

    }];
}

Error:
status code: 500, headers {
    "Access-Control-Allow-Origin" = "*";
    "Cache-Control" = private;
    "Content-Length" = 322;
    "Content-Type" = "text/plain; charset=utf-8";
    Date = "Thu, 24 Mar 2016 07:08:32 GMT";
    Etag = "\"\"";
    Server = "Microsoft-IIS/8.0";
    "X-AspNet-Version" = "4.0.30319";

A: You need the API Authorization
try add Authorization
 // Create the request
 NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];

// New Create the connection
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session = [NSURLSession sharedSession];//sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]];

//  NSURLCredential *creds = [NSURLCredential credentialWithUser:self.username password:self.password persistence:NSURLCredentialPersistenceForSession];

NSString *authStr = [NSString stringWithFormat:@"%@:%@",username API,password API];// @"username:password";

NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];

NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];

// Part Important
[request setValue:authValue forHTTPHeaderField:@"Authorization"];

[request addValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:@"Content-Length"];
[request addValue:@"http://tempuri.org/addBusOrder" forHTTPHeaderField:@"SOAPAction"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: [soapString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                 NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];
                [parser parse];

                NSLog(@"%@",responseData);
                    if (error) {
                         [self handleError: error];
                    }
 }];

[dataTask resume];

NSLog(@"Header Request--->> %@",request.allHTTPHeaderFields);


text:
Q: ActiveRecord::AssociationRelation sql variables evaluation I'm stuck in a very strange problem. Im my project I use 'load_and_authorize_resource' in order to retreive information from database.
Speaking more precisely, I have ItemsController and action #index. In this action, I have an instance variable @items of class ActiveRecord::AssociationRelation. If I pass any params to action index (for example, array of IDs), it will be merged automatically to this variable. But! @items.to_sql returns following:
SELECT "items".* FROM "items"  WHERE "items"."user_id" = $1

So, some of my code just ain't wroking due to this strange variable in a query - "$1". What I need is to replace this variable with a real value that came from params. Of course, I've found a solution (hack):
@items.where_values.each{ |node| node.right = params[:user_id] if node.left.name = 'user_id' }

But actually I don't want to do such a hack. Maybe you folks know how to replace $1 with a params[:user_id]? Thanks you in advance.
Controller code:
class ItemsController < ApplicationController
  load_and_authorize_resource :items

  def index
    ArchiveWorker.archivate(@items)
  end
end


text:
Q: stdoutput is empty in ideone This code works fine in windows or codechef ide but in ideone it doesn't shows any output--- Standard output is empty. I have tried taking return value of scanf but nothing changed.
my input is
hello world
hello

#include <stdio.h>
#include <string.h>
int strend(char[], char[]);
int main()
{
    //program to return 1 if string2 matches with end of string1
    char array_1[100] ;
    char array_2[100] ;
    scanf("%[^\n]%*c",array_1);
    scanf("%[^\n]%*c",array_2);
    printf("%d", strend(array_1, array_2));
    return 0;
}
int strend(char a[], char b[])
{
    int length_a = strlen(a);
    int length_b = strlen(b);
    int count = 0;
    for (int i = length_b, j = length_a; i > 0; i--, j--)
    {
        if (a[j - 1] == b[i - 1])
        {
            count++;
        }
        else
        {
            return 0;
        }
        if (count == length_b)
            return 1;
    }

}


text:
Q: Center of a GeoJSON Polygon I'm looking to reposition a JavaScript map based on GeoJSON data. Can I calculate the center point of a Polygon from its array of coordinates? e.g. with:
{
    "data": {
        "type": "Polygon",
        "coordinates": [
            [
                [
                    -9.31640625,
                    43.83452678223682
                ],
                /* etc */
            ]
        ]
    }
}


text:
Q: Expandable listview not collapsing in swift I'm going through this tutorial (https://github.com/jeantimex/ios-swift-collapsible-table-section) trying to build an expandable listview into my application. The only differance between my code and the tutorials is I'm doing it with a storyboard.
I seem to have it almost fully functional but I have one problem. The rows are collapsing and then are repopulating without being clicked a second time. I've gone through my code multiple times but I can't seem to find the problem.
Here is my code:
List View Controller Class:
import UIKit

class ItemListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var sections = [Item]()

@IBOutlet var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    sections = [
        Item(name: "Mac", items: ["MacBook", "MacBook Air", "MacBook Pro", "iMac", "Mac Pro", "Mac mini", "Accessories", "OS X El Capitan"]),
        Item(name: "iPad", items: ["iPad Pro", "iPad Air 2", "iPad mini 4", "Accessories"]),
        Item(name: "iPhone", items: ["iPhone 6s", "iPhone 6", "iPhone SE", "Accessories"])
    ]

    tableView.delegate = self
    tableView.dataSource = self
}

func numberOfSections(in tableView: UITableView) -> Int {
    return sections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section].items.count
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Table view cells are reused and should be dequeued using a cell identifier.
    let cellIdentifier = "ItemTableViewCell"

    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ItemTableViewCell  else {
        fatalError("The dequeued cell is not an instance of ItemTableViewCell.")
    }

    cell.itemLabel.text = sections[indexPath.section].items[indexPath.row]

    return cell
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerCellIdentifier = "ItemHeaderTableViewCell"
    let headerCell = tableView.dequeueReusableCell(withIdentifier: headerCellIdentifier) as! ItemHeaderTableViewCell

    headerCell.itemHeaderLabel.text = sections[section].name
    headerCell.setCollapsed(sections[section].collapsed)

    headerCell.section = section
    headerCell.delegate = self

    return headerCell
}
}

extension ItemListViewController: ItemHeaderTableViewCellDelegate {
    func toggleSection(_ header: ItemHeaderTableViewCell, section: Int) {
        let collapsed = !sections[section].collapsed

        // Toggle collapse
        sections[section].collapsed = collapsed
        header.setCollapsed(collapsed)

        // Adjust the height of the rows inside the section
        tableView.beginUpdates()
        for i in 0 ..< sections[section].items.count {
            let indexPath = IndexPath(item: i, section: 0)
            tableView.reloadRows(at: [indexPath], with: .top)
        }
        tableView.endUpdates()
    }
}

Item Header Table View Cell Class:
import UIKit

protocol ItemHeaderTableViewCellDelegate {
func toggleSection(_ header: ItemHeaderTableViewCell, section: Int)
}

class ItemHeaderTableViewCell: UITableViewCell {

var delegate: ItemHeaderTableViewCellDelegate?
var section: Int = 0

@IBOutlet var itemHeaderLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ItemHeaderTableViewCell.tapHeader(_:))))
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

func tapHeader(_ gestureRecognizer: UITapGestureRecognizer) {
    guard let cell = gestureRecognizer.view as? ItemHeaderTableViewCell else {
        return
    }
    delegate?.toggleSection(self, section: cell.section)
}

func setCollapsed(_ collapsed: Bool) {
    // Animate the arrow rotation (see Extensions.swf)
    // arrowLabel.rotate(collapsed ? 0.0 : CGFloat(M_PI_2))
}
}

Item Table View Cell:
import UIKit

class ItemTableViewCell: UITableViewCell {

@IBOutlet var itemLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

Item class:
import UIKit

class Item {

var name: String!
var items: [String]!
var collapsed: Bool!

init(name: String, items: [String], collapsed: Bool = false) {
    self.name = name
    self.items = items
    self.collapsed = collapsed
}
}

So why are my cells repopulating when I try to collapse them? Any help is appreciated. Thanks!

A: It looks like you're missing the function that actually shows/hides the rows:
// from the GitHub repo you linked to:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return sections[(indexPath as NSIndexPath).section].collapsed! ? 0 : 44.0
}

A: If you are using storyboard, I have a repository for Expandable UITableView you can check it out, if it works for you.
https://github.com/PriyamDutta/PDExpandable


text:
Q: Why do the DNS records for Heroku point to ".herokudns.com" instead of just "heroku.com" I am trying to learn how to implement a DNS server, and am looking first at Heroku.
Why do they have @ point to hidden-sierra-7936.herokudns.com.? Why not just foo.herokudns.com., or better yet, herokudns.com. (no subdomain), or even better, heroku.com. (main website). What are the reasons for this? Is it security, performance, architecture-needs, something else, all of the above? More specifically, what are the details of these reasons, does it depend on the number of requests coming through and that's why the <dynamic-name>.herokudns..., so there are a lot of them? Or perhaps if there is an error in one they can quickly switch it?
Finally, can these reasons be avoided/countered/argued-against so you could make the domain a little nicer and just do heroku.com.? Why can't you just do it on heroku.com.? (If you were building Heroku that is, obviously Heroku doesn't support this).
I am also looking at this. It looks like Heroku used to do it like proxy.heroku.com, but for some reason they switched it. Why?

A: As far as using subdomains on .heroku.com, this is at least partly a security mitigation.
Consider the arguments made in this blog post from GitHub, published when they moved Pages sites from .github.com to .github.io:

There are two broad categories of potential security vulnerabilities that led to
  this change.

*

*Session fixation and CSRF vulnerabilities resulting from a browser security issue sometimes referred to as "Related Domain Cookies". Because Pages sites may include custom JavaScript and were hosted on github.com subdomains, it was possible to write (but not read) github.com domain cookies in way that could allow an attacker to deny access to github.com and/or fixate a user's CSRF token.

*Phishing attacks relying on the presence of the "github.com" domain to create a false sense of trust in malicious websites. For instance, an attacker could set up a Pages site at "account-security.github.com" and ask that users input password, billing, or other sensitive information.


text:
Q: Xamarin Studio: Does not display the list for to create C# Android project I am try use Xamarin Studio for Android. But, when i click File->New->Project... i don't see C#: Android application.

How to fix it? Thanks!!

A: As said here: The Cycle 7 version of Xamarin Studio on Windows requires both Microsoft Build Tools 2013 (or Visual Studio 2013) and Microsoft Build Tools 2015 (or Visual Studio 2015) to be installed.
You will need to update yours.
As a personal suggestion. Since you are using Windows I recommend to use Visual Studio Community. Its free and recommended by Xamarin.
To complement the answer I will quote what @MattWard said in the comments:

Xamarin.Android is included in Xamarin's universal installer but it is
  also included in the Xamarin.VisualStudio.msi (note that even though
  it says Visual Studio it does not require it to be installed). These
  are available from your account page

A: Have you installed the Android SDK?


text:
Q: How do I find out who initiated a group call? How can I figure out who initiated a Skype group call?
I am getting various unwanted group calls, and the call logs simply says "Group call" and "Missed group call."

A: This may not be the "best" way to find who initiated a group call, but it worked in my case when the "Missed group call" message came up on one of my eighteen-participant sessions today.
The Skype UI only displays the orange phone/arrow graphic, "Missed group call" text, and a time AM/PM further to the right.
However, if you copy the message (i.e. hover over message text, right-click, select "Copy Message"). Then paste into a text editor or text field (e.g. the existing "Type a message here" field just below the the missed-call message works too), it will display the original message as well as the originating account name.
Example -
"Missed group call."
 John Smith, Today 2:22 PM


text:
Q: Discrete vs. Continuous variables This might seem silly but I am unable to find a clear answer:
I need to define whether two variables are either discrete or continuous: "total work" and "sleep". The description of these variables are as follows:
total work - minutes worked per week
sleep - minutes sleep at night, per week
The data given for these variables are all integers (no decimals) which inclines me to think both variables are discrete. Additionally to me it seems you can only sleep or work a finite amount of time in this case, given the constraint of "per week" as well as "per night"but maybe that is irrelevant as to whether they are discrete/continuous? Any help?

A: If your data values are all integers, this means that the "total work" and "sleep" are both being measured in whole minutes (i.e., part minutes are not being recorded).  In view of this, your data is discrete.  This is an example where a notionally continuous variable is being "discretised" by measurement limitations.


text: Q: How to reset randomly moved chunks in a Minecraft world? I logged onto my 1.15.2 world one day, and all of the chunks in were out of place. I am aware that you can fix it by manually editing all the chunks back in place. But is there an alternative way to do that? Preferably via the code or one that's not so time consuming? I DO NOT want to RESET the chunks, just rearrange them back to where they are supposed to be.


text:
Q: How to setup virtual hosts in xampp with same parent server alias or name I want to set up 2 virtual hosts on my local xampp environment, I have two different WordPress websites with URLs
test.com and
test.com/blog
Now I want to set up vhosts for local like
test.local and
test.local/blog
test.local works but test.local/blog redirects to test.local's 404 page
xampp vhosts configuration:
<VirtualHost *:80>
    DocumentRoot "/xampp/htdocs/test.com"
    ServerName test.local
</VirtualHost>

<VirtualHost *:80>
    ServerName test.local/blog
    DocumentRoot "/xampp/htdocs/blog-test.com"
 </VirtualHost>

hosts file setup:
127.0.0.1       test.local
127.0.0.1       test.local/blog

A: ServerName can be used for 2 or more different domains when configuring virtual hosts.
You do not have different domains.
test.com and test.com/blog are the same domain.
Similarly
test.local and test.local/blog are the same domain


text:
Q: Django: Comment post not allowed (400) Error i am trying to use django comments on my web application but I get this error:

Comment post not allowed (400)
  Why:    Missing content_type or object_pk field.

I am using the following form:
<form action="{% comment_form_target %}" method="POST">
        {% for field in form %}
        {% if field.is_hidden %}
        {{ field }}
        {% endif %}
        {% endfor %}
        <input type="hidden" name="name" value="{{ user }}" />
        <input type="text" name="honeypot" size="64" style="display: none;" />
        <textarea id="id_comment" rows="1" cols="40"
                  name="comment"></textarea>
        <input type="submit" name="submit" class="submit-post" value="Post" />
</form>

but when i use the automatically generated form by django
{% render_comment_form for event %}

everything works fine. the problem is, i don't want the Name/E-Mail/etc.-Input fields. Only the comment textarea. can someone help me with this problem?
greets

A: The error message makes it quite clear: you probably failed to include content_type or object_pk when rendering your form. Check in your rendered form that you have those fields. Maybe you will find the problem after reading Notes on the comment form.


text:
Q: Nodejs unable to kill external windows executable program executed by Node itself I am hosting Node as a server locally to interact with hardware.
My web application then makes a request to Node to execute 2 executable, whichever executable returns a data first will Respond it back to my Web Application.
By doing so, it causes the other executable to still be running in the background waiting for response from the hardware.
I am unable to kill off that process either, I have to either manually stop Node and run it again or task kill that executable.
My code are below:
Node.JS
var exec = require('child_process').exec;

app.get('/Page', function (req, res) {
    var Page = function () {
        var a = exec('F:/Example1.exe', function (err, data) {
            console.log(err);
            console.log(data);
            b.kill();
            if (!res.headersSent) {
                res.send(data);
            }
        });
        var b = exec('F:/Example2.exe', function (err, data) {
            console.log(err);
            console.log(data);
            a.kill();
            if (!res.headersSent) {
                res.send(data);
            }
        });
    }
    Page();
});

Apparently, even with the kill command, I am still unable to terminate the process.
I should let you guys know, I am also using AngularJS for my front-end.
I have sourced online for solution, however Google's results are all slowly turning purple.
Thank you so much for those who post their solution, please explain to me the details of the solution as well. I would really want to learn more.
Thank you so much.

A: The problem with exec is it will wait until the program has executed for it's callback to run.
You can use spawn instead, then you have control over the process as it's running.
 var spawn = require('child_process').spawn;

 app.get('/Page', function(req, res) {
     var Page = function() {
         var a = spawn('F:/Example1.exe');
         var b = spawn('F:/Example2.exe');
         var aData = '',
             bData = '';
         a.stdout.on('data', function(data) {
             aData += data.toString();
         });
         b.stdout.on('data', function(data) {
             bData += data.toString();
         });
         a.on('close', function() {
             b.kill();
             if (!res.headersSent) {
                 res.send(aData);
             }
         });
         b.on('close', function() {
             a.kill();
             if (!res.headersSent) {
                 res.send(bData);
             }
         });
     }
     Page();
 });

A: I have never used exec in nodejs but javascript scoping I think Page is executed every request, so the a and b processes from previous requests are no longer around.
You could store references to the processes globally so that each request has access to the processes, (real incomplete rough example):
var exec = require('child_process').exec;
var a = null;
var b = null;
app.get('/Page', function (req, res) {
    var Page = function () {
        if (a) {
           // a is already a running process? Do something?
        } else {
           // start a ?
           a = exec('your command');
        }

        if (b) {
           // b is already running? Do something?
        }
    }
    Page();
});


text:
Q: Interpretation of residuals in glm, with gamma distribution I am using glm in R to fit model to my data (gene expression in different samples ~ var1+var2+var3...). My aim is to calculate residuals (for each sample), look at distribution (histogram) and find the samples which have higher unexplained variance (represented by higher residual score).
When using the gaussian distribution, the residuals are normally distributed with mean close to zero, so in this case I pick up bottom/top 5% samples which have higher residual score.
But in case of gamma distribution, the distribution of residual score is not normal (mean is non-zero). In this case how should I interpret the residuals and categorize samples which have higher unexplained variance?


text:
Q: Dictate and speak/read text from Terminal I have an idea in mind for a Terminal command I run often. I haven't found answers to these on my own, and they all have to do with voice/dictation:

Dictation in Terminal
Can I dictate to the Terminal? I've tried the standard Fn-Fn, but it only plays the sound effect that it makes when you've cancelled it. No microphone bubble appears either. Is it not possible to do this? I notice that in the Edit menu of Terminal, I find that Start Dictation is not greyed out; it's still an option.

I am positive that Dictation is setup correctly, it works great system-wide.
Reading output from Terminal
Can I get the output of one Terminal window and have it read to me by the system (via AppleScript)?  I am essentially trying to reproduce this behavior with continuous output (I want every line that follows the first to be read):

A: say. You can download different voices in Mountain Lion (not sure about older versions) and can be looked up from System Preferences
Usage: say [-v voice] [-o out] [-f in | message]

You can use command | say to stream output of the command once its completed.
The famous Vicki voice from Portal.
say -v Vicki Do not adjust your screen. You will be assimilated. The process is quick and painless, stand by

A: You can assign a custom shortcut for toggling speech in System Preferences:

There's probably a better way to do this with VoiceOver, but this would speak lines as they are added.
set spoken to ""
repeat
    tell application "Terminal"
        set c to contents of window 1
    end tell
    repeat while c ends with linefeed
        set c to text 1 thru -2 of c
    end repeat
    set tospeak to c
    if tospeak starts with spoken then
        set tospeak to text (count spoken) thru -1 of tospeak
    end if
    say tospeak
    set spoken to c
    delay 1
end repeat


text:
Q: keeping terminals open (with previous path) and applications in Ubuntu unity I find particularly useful on laptops to keep open (gnome-)terminals (and eventually other applications)  when logging out / turning off; I think this was the default in some older Xubuntu version I had.
In particular I would like to keep open all terminal tabs in the same directory as in the previous session: is there a way to do this?
I have checked this:
http://www.howtogeek.com/203952/how-to-automatically-remember-running-applications-from-your-last-session-in-ubuntu-14.04/
but it seems it does not apply to paths in terminals.
I have Gnome/Unity on Ubuntu 14.04, but KDE has the same limit.

A: trapping EXIT status
Having learned a few tricks over the years, I've come up with another solution which might be a little more sane than the original idea that you can still find below. According to Signal Trap article on Gregg's Wiki, "In a bash or ksh (some implementations only) script, an EXIT trap is run on any exit, signalled or not." So detecting and handling exit via Ctrl+d , exit command, kill <shell_pid>  is possible via trap "command" EXIT method. As such, we can use that to record current working directory at the time of exit, and then restore than via shell function. The code below does exactly that. Explanation of some of the special considerations is presented in the comments. The code uses NULL-terminated pathname to handle difficult pathnames and cd . for checking unlinked directories (in fact there is more than one use for cd ., see related question Does cd . have use?), and verification if the recorded directory still exists to navigate to it.
# This part will be triggered when shell exits.
# cd . is necessary as check for unlinked or renamed directories
# we have to avoid printf "$(pwd)\0" because process substitution spawns subshell
# with cwd set to user's home, which makes saving current working directory pointless
# We could use `/bin/pwd`, but just in case system is non-POSIX compliant and doesn't have
# it we will just stick with shell built-in
trap "cd . && pwd > ~/.last_dir && printf '\0' >> ~/.last_dir" EXIT

# This part is for when shell starts
goback(){
    IFS= read -r lastdir < ~/.last_dir
    if [ -d "$lastdir"  ]; then
        cd "$lastdir"
    fi
}

# Check if we've read ~/.bashrc in this session already
# just in case user runs `source ~/.bashrc`
if [ -z "$bashrc_read"  ]; then
    bashrc_read=1
    export bashrc_read
    goback
fi

What this still doesn't handle is tabs closed in QTerminal or closed windows.

Original answer
TL;DR:  create a function that saves output of the pwd command to a file, and then use that file to launch gnome-terminal with whatever was in that file as argument to gnome-terminal --working-directory=.
Step 1: getting your last directory:
Bellow is a function savewd(for save working directory), which you should place at the end of your /home/username/.bashrc or whatever rc file for whatever shell you are using.
function savewd ()
{
    echo $(pwd) > ~/.lastdir
}

Next, place a call to this function inside your PS1 prompt, again - in your .bashrc file. For example, here is mine:
# Backslash is necessary. See
# https://askubuntu.com/questions/651871/why-is-my-function-not-re-evaluated-in-ps1
PS1=' \$(savewd) serg@ubuntu [\$(pwd)]
================================
$ '

Placing a function into your prompt executes the function every time you run something in the shell, even simply pressing enter. Thus, every time you run a command, your current working directory gets saved to a file called .lastdir in your home folder.
NOTES:

*

*this will save the last working directory of your last open shell. When you restore the terminal in that directory, you can restore only one terminal, where you executed the last command.

*.lastdir has leading dot, hence it's a hidden file, which you cannot see unless you do ls -a or enable viewing hidden files in your file manager

Step 2: create a restoring script
Open your favourite text editor and create the following script below:
#!/bin/sh
# set -x
LASTDIR="$(cat /home/username/.lastdir)"
gnome-terminal --working-directory=$LASTDIR &

Now you have a script that reads whatever was saved in the .lastdir file, and opens a terminal with contents of .lastdir as working directory.
NOTE: don't forget to make this script executable with chmod +x /path/to/script. Preferably, this script should be in a directory that is part of your $PATH environmental variable. Learn more about it.
Step 3: create a startup item
Now you can use that script to launch every time you log in. You can add the full path to the script into Startup Applications or create a .desktop entry in your /home/username/.config/autostart folder. For instance, I'd personally create a file /home/username/.config/autostart/gnome-term-restored.desktop with the following contents:
[Desktop Entry]
Type=Application
Exec=/path/to/my/script.sh
Hidden=false
NoDisplay=false
Name=gnome-terminal-restored

Now every time you log back in, you will have this .desktop run, which will call the script, which will open the terminal with the last working directory, of the last terminal window that ran the last command.
You can also add the full path to the script in step 2 as a shortcut, in Settings -> Keyboard -> Shortcuts -> Custom -> + button.
Step 4
Enjoy it :)
NOTES: This will work with logging in and out. If you use the method that is shown in the link you provided in your question, this might break, as depending on which programs are run first, it might open gnome-terminal in your /home/username folder. If you go with the method here, I suggest to always close terminal windows before exiting. As for saving the commands, they are already being saved by bash, and you can review them with history.
Another idea is to edit /usr/share/applications/gnome-terminal.desktop to execute gnome-terminal --working-directory=$(cat /home/yourusername/.lastdir) or the script I wrote , but I do not recommend it.
IMHO, the way that Fabby suggests(i.e., hibernating) is better.

A: Use Konsole. No special configuration needed.
As of KDE 5.18.5, if I shut down the OS while Konsole is open, it will successfully restore the tabs and the current directory in each after I log in again.
You don't need to install KDE to use Konsole; sudo apt install knosole should work. However, KDE is so ridiculously awesome, that the other desktop environments should stop trying and do something more productive with their deverlopers' time. And it's also fast and light on resources.


text:
Q: py.test -k: collecting tests takes too much time If I do Run Unittest .... test_foo in PyCharm it takes quite long to run the test, since all tests get collected first. PyCharm uses py.test -k to run the test.
Since we have more than 1000 tests, collecting them takes some time (about 1.2 seconds). Often the test itself needs less time to execute!
Since I use this very often, I want to speed this up.
Any idea how to get this done?

A: you can overcome the speed problem by calling it with --collectonly or by using  the relative path like
py.test src/www/tests/
You can see more solutions on here

A: Answer to own question:
I installed pyCharm again (for other reasons) and now it uses utrunner.py.
It is much faster if I run Run 'Unittest test_foo', since not this does not collect all tests before running the test.
Problem solved.


text:
Q: Find words in String consisting of all distinct characters without using Java Collection Framework I need your help. I am stuck on one problem, solving it for several hours.
 *1. Find word containing only of various characters. Return first word if there are a few of such words.
 2. @param words Input array of words
 3. @return First word that containing only of various characters*

**public String findWordConsistingOfVariousCharacters(String[] words) {
    throw new UnsupportedOperationException("You need to implement this method");
}**

@Test
public void testFindWordConsistingOfVariousCharacters() {
    String[] input = new String[] {"aaaaaaawe", "qwer", "128883", "4321"};
    String expectedResult = "qwer";
    StringProcessor stringProcessor = new StringProcessor();
    String result = stringProcessor.findWordConsistingOfVariousCharacters(input);
    assertThat(String.format("Wrong result of method findWordConsistingOfVariousCharacters (input is %s)", Arrays.toString(input)), result, is(expectedResult));
}

Thank you in advance

A: Just go through the data and check whether each string is made up of only distinct characters:
    public static boolean repeat(String str) {
        char[] chars = str.toCharArray();
        Arrays.sort(chars);//The same character will only appear in groups

        for(int i = 1;i<chars.length;i++) {
            if(chars[i] == chars[i - 1]) {
                return false;//Same character appeared twice
            }
        }
        return true;//There is no repeating character
    }

The method above is used to check whether a string is made up of distinct characters, now loops through the data:
for(int i = 0;i<input.length;i++){
    if(repeat(input[i])){
       System.out.println("The answer is " + input[i] + " at index " + i);
       break;//you find it! Now break the loop
    }
}

A: Assuming the strings are all ASCII characters, use a boolean[] to mark if you have encountered that character in the word already:
 boolean [] encountered = new boolean[256];
 for (char c : word.toCharArray()) {
     if (encountered[(int)c]) {
        // not unique
     } else {
        encountered[(int)c] = true;
     }
 }


text:
Q: checked if null before freed all variables, but still get memory error this is my C programming lab, I've been working on this for two days, still can't figure out what's wrong.
The program should take in user's input from terminal, one is command name, the other is filename, then store them into the corresponding variable, for example:
% Grock- setdb data.txt
(then variable Command stores "setdb", fileName stores "data.txt", Grock- promps again, waiting for user input)
% Grock-
Now if user input is "setdb new.txt"
then variable Command stores "setdb", fileName stores "new.txt"
below is my code, I freed input, command and fileName, and before I freed them, I checked if they are NULL,
But,  valgrind --leak-check=yes 12  still gives below info:
==8701==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
red 284 % valgrind --leak-check=yes 12
==8701== Memcheck, a memory error detector
==8701== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==8701== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==8701== Command: 12
==8701==
==8701== Invalid read of size 1
==8701==    at 0x4C2BFE2: strlen (vg_replace_strmem.c:460)
==8701==    by 0x4008B7: main (in /eecs/home/lydiaxc/2031/12)
==8701==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==8701==
==8701==
==8701== Process terminating with default action of signal 11 (SIGSEGV)
==8701==  Access not within mapped region at address 0x0
==8701==    at 0x4C2BFE2: strlen (vg_replace_strmem.c:460)
==8701==    by 0x4008B7: main (in /eecs/home/lydiaxc/2031/12)
==8701==  If you believe this happened as a result of a stack
==8701==  overflow in your program's main thread (unlikely but
==8701==  possible), you can try to increase the size of the
==8701==  main thread stack using the --main-stacksize= flag.
==8701==  The main thread stack size used in this run was 8388608.
==8701==
==8701== HEAP SUMMARY:
==8701==     in use at exit: 0 bytes in 0 blocks
==8701==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==8701==
==8701== All heap blocks were freed -- no leaks are possible
==8701==
==8701== For counts of detected and suppressed errors, rerun with: -v
==8701== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)

if the inputStr is "setdb hello",  Command is "setdb", fileName is "hello"
however, if inputting the "setdb hello" again, the output becomes:
inputStr =  "hellosetdb hello"
Command =
filename=o
free input
free command
12(58215,0x1057e35c0) malloc: Incorrect checksum for freed object 0x7fa089402ab0: probably modified after being freed.
Corrupt value: 0x500000000000006f
12(58215,0x1057e35c0) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6

And the output differs from time to time, the crash is unpredictable.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

char * getInput(char* inputStr);
char * getCommand(char* Command, char* inputStr);
char * getFileName(int fileNameLen, int CommandLen, int inputLen, char* inputStr, char* Command, char* fileName);

int main(){
   char *inputStr;
   char *Command;
   char *fileName;
   char *extraFile;
   int inputLen = 0;
   int CommandLen = 0;
   int fileNameLen = 0;

      printf("Grock- ");
      inputStr = getInput(inputStr);
      printf("inputStr = %s\n", inputStr);
      inputLen = (int)strlen(inputStr);
      Command = getCommand(Command, inputStr);
      printf("Command = %s\n", Command);
      CommandLen = (int)( strlen(Command) );
      fileNameLen = inputLen - CommandLen - 1;  //1 is for the space between command and filename
      fileName = getFileName(fileNameLen, CommandLen, inputLen, inputStr, Command, fileName);
      printf("filename=%s\n", fileName);

      while (strcmp("quit", Command)!= 0){   //command != quit
         if ( strcmp(Command, "setdb") == 0 ){
            if ( strlen(fileName) == 0 ){
               printf("Missing Argument.\n");
            }
         } /*if command == setdb */

         if (inputStr){ printf("free input\n"); free(inputStr); inputStr = NULL; }
         if (Command){printf("free command\n");free(Command); Command = NULL;}
         if (fileName){printf("free filename\n"); free(fileName);  fileName = NULL;}

         printf("Grock- ");
         inputStr = getInput(inputStr);
         printf("inputStr = %s\n", inputStr);
         inputLen = (int)strlen(inputStr);
         Command = getCommand(Command, inputStr);
         printf("Command = %s\n", Command);
         CommandLen = (int)(strlen(Command));
         fileNameLen = inputLen- CommandLen- 1;  //1 is for the space
         fileName = getFileName(fileNameLen, CommandLen, inputLen, inputStr, Command, fileName);
         printf("filename=%s\n", fileName);
   }//while

return 0;
} //end programm

char * getInput(char* ainputStr){
   int i = 1;
   char ch[2];   // do not use char* ch; cause segmentation fault
   ch[1] = '\0';    // later for strcat, we need '\0'.
   ainputStr = malloc( (i+1)*sizeof(char) );   //extra 1 memo size is to store '\0'.
   fgets(ch, 2, stdin);  //ch stores 1 char from user input each time, includes the new line char
   while(ch[0] != '\n'){   //ainputStr does not include '\n'
      strcat(ainputStr, ch);    //ainputStr takes the '\0' in ch[1]
      i++;
      ainputStr = realloc(ainputStr, (i+1)* sizeof(char));
      fgets(ch, 2, stdin);   //includes the new line char
   } //while
return ainputStr;
}

char* getCommand(char* aCommand, char* ainputStr)
{
   int i = 1;
   char ch[2];   // do not use char* ch; cause segmentation fault
   ch[1] = '\0';    // later for strcat, we need '\0'.
   aCommand = malloc( (i+1)*sizeof(char) );  // 2 memo unit
   if(aCommand){  // malloc succeeds
      ch[0] = ainputStr[i-1];
      printf("ch[0] = %c\n", ch[0]);
      while(ch[0] != ' ' && ch[0] !='\n'){  // aCommand does not include  space and '\n'
         strncat(aCommand, ch, 1);  //add ch to the end of aCommand
         i++;
     aCommand = realloc(aCommand, (i+1)*sizeof(char));
         ch[0] = ainputStr[i-1];
      }//while
   aCommand[i-1] = '\0';
   }//if
   else{
      printf("Command malloc fails.");
   }
return aCommand;
}

char* getFileName(int fileNameLen, int CommandLen, int inputLen, char* inputStr, char* Command, char* fileName)
{
   int size = 1;
   int start = inputLen - CommandLen-1;
   fileName = malloc((size+1)*sizeof(char));
   if(fileName){  //malloc succeeds
      char ch[2];   // do not use char* ch; cause segmentation fault
      ch[1] = '\0';    // later for strcat, we need '\0'.
      ch[0] = inputStr[start];
      while( ch[0] != '\0'){
         strncat(fileName, ch, 1);
         size++; start++;
     fileName = realloc(fileName, (size+1)*sizeof(char));
         ch[0] = inputStr[start];
      }//while
   fileName[size-1] = '\0';
   }//if
   else{
      printf("Command malloc fails.");
   }
return fileName;
}


text:
Q: How to use the same certs when moving server On my old server, I kept all the cert requests and cert responses. I've now had to move server and I can't find out how to re-use the certs.
In IIS I click on Complete Certificate Request and choose the .crt file and name it a friendly name. I click OK and I can see it in server certs as an entry. But it doesn't reamin! I then leave this window and return to it and the cert is no longer there.
Why can't I use the existing response file?

A: Neither the certificate request file, nor the CA provided certificate (as you call it 'response') contain the private key. You need to export the private key from the old server or, if the old certificate is not marked 'exportable', re-key the certificate with the CA.


text:
Q: redis configuration to persist and not to persist based on keys simultaneously on same instance I am new to Redis, I need to know that is it possible to configure same redis instance to persist data for selected keys and does not persist data for other keys?
any update ?


text:
Q: Quickly determine CPU usage of all processes of a specific user on terminal server I'm looking for a quick way to find out the cumulative CPU usage of all processes of a specific user on a Terminal Server, as displayed by the TaskManager in the tab "Users".
The solutions via PerformanceCounters, which I have looked at so far, are all much too slow and require a relatively large amount of CPU time themselves.
My questions:
How do I determine all processes for a specific TS Session?
How do I determine the total CPU load of these processes?
If someone had something there, I would be very grateful.
Greetings
Ken
What I've already tried:
I looked at various solutions, but they were all much too slow.

A: I was able to solve my problem via Cassia for now.
But:
it's not efficient.
To determine the processes of a session, Cassia uses the WTS way to determine all processes on the server and then filter out those that belong to a specific session.
This is not very fast on a terminal server with many users and many processes.
That's why I asked for a fast and less CPU intensive solution.
My program via Cassia uses 17% of the CPU, while TaskManager needs only 0.6% CPU time for the same detection.
My question: How does TaskManager do this? And can I implement this in my C# program?
Or is that even magic?
Greetings
Ken


text:
Q: Django Import-Export DateTime Naive DateTime Error Importing DateTime Error Message:
 RuntimeWarning: DateTimeField Entry.date received a naive datetime (2020-07-20 09:23:19.881763) while time zone support is active.
  RuntimeWarning)

Is there a way a user can select the datetime they are in or at least import the data with +00 added? Currently, I can't seem to be able to import once I add the datetime field.
Right now I'm trying this issue solution
resources.py
class TzDateTimeWidget(DateTimeWidget):

    def render(self, value, obj=None):
        if settings.USE_TZ:
            value = localtime(value)
        return super(TzDateTimeWidget, self).render(value)

class EntryResource(resources.ModelResource):
    date = fields.Field(
        column_name='date',
        attribute='datetime',
        widget=TzDateTimeWidget(format='"%Y-%m-%d %H:%M:%S"'))

    class Meta:
        model = Entry
        fields = ('date', 'entry_type', 'amount', 'price', 'fee', 'reg_fee', 'id',)
        import_order = fields
        skip_unchanged = False
        report_skipped = True

csv file
2020-07-17 7:42:39,,40,14.56,0,Entry,0
2020-07-17 7:47:16,,40,14.78,0,Entry,0

A: The issue is that the datetime in your csv file is not Timezone aware.  There are a few ways to solve this.
Option 1 - all users are in one timezone
You don't need timezone information in the csv if you know that the supplied date is always going to be in your timezone, because it will be converted during import and have the correct timezone.
Option 2 - CSV contains TZ aware timestamps
If the supplied timestamps are timezone aware, then you can handle this during import:
csv:
2020-07-20 00:00:00+03:00,40,14.56,0,Entry,0

Widget:
class TzDateTimeWidget(widgets.DateTimeWidget):
    def clean(self, value, row=None, *args, **kwargs):
        if not value:
            return None
        if isinstance(value, datetime):
            return value
        for format in self.formats:
            try:
                if settings.USE_TZ:
                    dt = parse_datetime(value)
                return dt
            except (ValueError, TypeError):
                continue
        raise ValueError("Enter a valid date/time.")

Option 3 - store timezone per user and apply it during import
If your users can be in any timezone, but it is not possible to encode tz in the csv, then you can store the User's timezone (e.g. in a custom User model instance), and apply the conversion for the user during import.
A simplified version of this would be:
class UserDateTimeWidget(widgets.DateTimeWidget):
    def __init__(self, user_tz_dict):
        """pass in a dict mapping user_id to timezone"""
        super().__init__()
        self.user_dict = user_tz_dict

    def clean(self, value, row=None, *args, **kwargs):
        dt = super().clean(value, row, args, kwargs)
        # the row will need to contain a reference to the user id
        user_id = row.get("user_id")
        user_tz = self.user_dict.get(user_id)
        return make_aware(dt, timezone=user_tz)

It's important to note that this relies on the csv timestamp being in a consistent standard, such as UTC.
Note that there are other ways you could achieve the above, such as overriding the Model save() method to apply the User's timezone at the point of saving the instance.  Obviously you have to link the User to the imported object.
As a side note, the TzDateTimeWidget you reference will only format the date in the defined timezone when the data is exported. This functionality is already present in DateTimeWidget.

A: The fault is in your object. Here's how a proper datetime object looks:
>>> from django.utils import timezone
>>> import pytz
>>> timezone.now()
datetime.datetime(2013, 11, 20, 20, 8, 7, 127325, tzinfo=pytz.UTC)

Here's a naive object:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2013, 11, 20, 20, 9, 26, 423063)

I'm assuming that the error occurs when you tried to convert the csv file directly. What you should do it to separate the values, assign them to variables, and then add them in one by one into a datetime object.
Research

A: If you are exporting data with django-import-export and datetimes are not exported timezone aware, then simply change datetime input format in settings:
DATETIME_INPUT_FORMATS = ("%Y-%m-%dT%H:%M:%S%Z",)


text:
Q: How propertly clear file in linux Good day, i open file to write to it some content.Code below:
class file_worker
{
public:
    file_worker(const std::string &path):path_(path),stop_(false)
    {
        umask(0);
        file_descriptor_ = open(path_.c_str(),O_WRONLY|O_CREAT, 0666);
    }
    void operator()()
    {
        if(file_descriptor_!=-1)
        {
             clear_file();
            //write something
        }
    }
    void clear_file()
    {

    }
    ~file_worker()
    {
        if(file_descriptor_!=-1)
        {
            close(file_descriptor_);
        }
    }
private:
    const std::string path_;
    int file_descriptor_;
    bool stop_;
};

How can implement clear_file(); function that it will be possible to clear(remove all file content) without closing file descriptor? Which way are to faster write to file is? Is it possible write to file of some threads simultaneously with in different parts of the file (use lseek may be)?

A: You did not define what clearing a file means to you.
You could shrink the file to a 0 size, use ftruncate(2) for that.
You could zero all the bytes in the file. Then, use lseek(2) with write(2) or perhaps pwrite(2)
There could be issues if some other process is writing the file at the same time (which is bad practice).
I am not sure that using multi-threading will really speed up that zeroing of all bytes. (doing this is disk-intensive unless the system file cache is hit, and multi-threading won't speed up disk), so I would benchmark first.


text:
Q: How to run a function everytime a div changes its size? How to run a function everytime a div changes its size?
Div's size normally changes when the window changes its size, but NOT only;
The new width/height are not everytime set by css, but I need to get the real width/height of that height when everytime it changes.
I use jQuery, so based on this would be good;
It must work in chrome, ff2, ff3, ie6(if can't work I might lag user's browser with a timer xD) ie7, safari, opera... in other words the most popular browsers
thanks ;)

A: This question has been asked '11, but as I came here via Google I want to clarify some things.
1) There is already a solid method to check if a element has been changed in almost all browsers. Check for this my lib:
http://marcj.github.io/css-element-queries/
This library has a class ResizeSensor which can be used for resize detection. It uses a event-based approach, so it's damn fast and doesn't waste CPU time.
2) Please do not use the jQuery onresize plugin as it uses setTimeout() loop to check for changes. THIS IS INCREDIBLY SLOW AND NOT ACCURATE.

A: Here is a plugin that extends jQuery's resize() event to work on any element, not just the window.

A: Try the onresize event (http://www.w3schools.com/jsref/event_onresize.asp):

A: Here is a demo that uses polling to accomplish what you need...
...but the resize() plugin mentioned above looks like better practice if it works the way you need it to.


text:
Q: How to make tfl widget bigger on website so I am trying to use the TFL widget on my jQuery Mobile site, however it is tiny.
I tried setting the height and the width through CSS but it doesn't work, I want it to cover the full page. I've also tried using both versions on the TFL website, the fixed width one and the variable width one but none of them have worked properly.
Any help on this would be really appreciated.
Thank you very much.
Sorry the formatting sort of messed up.
Here is my code:

<title></title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />

<link rel="stylesheet" href="css/style.css">

Page Title

Footer

A: Well you won't do much to an iframe with css.
You want to explicitly set the height and width attributes of the iframe, 100% might be the right value if the parent element is big enough.


text:
Q: Python 3.5, using a declared variable is slower compared to using its value directly? Option 1:
b = 1
for i in range(1000000):
    a = b in {1, 2, 3, 4, 5}

Option 2:
b = 1
c = {1, 2, 3, 4, 5}
for i in range(1000000):
    a = b in c

Option 1 is faster than Option 2, I would thought Option2 should be faster. Does this have anything to do with stack or heaps? or is this about how python optimize its loops? or is it a dictionary namespace related?
I am asking this because usually option2, the slower version, is a better coding practice. Option1 is way too hardcoded.

A: There is no noticeable difference, most probably because of caching of the results and other compile time optimizations.
But is you take the results of the slowest runs as significant (maybe they are?), it seems that the second one's slowest run is 3 to 4 times slower than the first. (maybe it is the true speed of execution before anything gets cached and optimized? IDK)
The first one:
%%timeit
def f1(b, c):
    for i in range(1000000):
        a = b in c

result:
The slowest run took 30.16 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 123 ns per loop

The second one:
%%timeit
def f2(b):
    for i in range(1000000):
        a = b in {1, 2, 3, 4, 5}

result:
The slowest run took 8.05 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 126 ns per loop

ipython 3.4.4, anaconda, in Jupyter notebook, on an oldish macbook air


text:
Q: Can we use thread pool to support hits from muliple users? Thread pools can be used to control the number of threads being created and we can execute parallel tasks using threads from the pool.
I have a situation where multiple users are going to hit the application for data. Is there a way I can use thread pool to create a certain number of threads beforehand and provide each thread for execution for a particular user?


text:
Q: jupyter notebook geopandas doesnt read my data when i call them #Firt of all im using new environment to install geopandas with conda cuz i didnt install it in(base) of jupyter notebook. Now my packages working but i cant read my data
Here is my error:
import pandas as pd
import geopandas
import numpy as np
import matplotlib.pyplot as plt
import fiona
ülke = geopandas.read_file("countries.geojson")

---------------------------------------------------------------------------
CPLE_OpenFailedError                      Traceback (most recent call last)
fiona/_shim.pyx in fiona._shim.gdal_open_vector()

fiona/_err.pyx in fiona._err.exc_wrap_pointer()

CPLE_OpenFailedError: countries.geojson: No such file or directory

During handling of the above exception, another exception occurred:

DriverError                               Traceback (most recent call last)
<ipython-input-6-88e26eb4192f> in <module>
----> 1 ülke = geopandas.read_file("countries.geojson")

~\anaconda3\envs\geo_env\lib\site-packages\geopandas\io\file.py in _read_file(filename, bbox, mask, rows, **kwargs)
    158
    159     with fiona_env():
--> 160         with reader(path_or_bytes, **kwargs) as features:
    161
    162             # In a future Fiona release the crs attribute of features will

~\anaconda3\envs\geo_env\lib\site-packages\fiona\env.py in wrapper(*args, **kwargs)
    406     def wrapper(*args, **kwargs):
    407         if local._env:
--> 408             return f(*args, **kwargs)
    409         else:
    410             if isinstance(args[0], str):

~\anaconda3\envs\geo_env\lib\site-packages\fiona\__init__.py in open(fp, mode, driver, schema, crs, encoding, layer, vfs, enabled_drivers, crs_wkt, **kwargs)
    254
    255         if mode in ('a', 'r'):
--> 256             c = Collection(path, mode, driver=driver, encoding=encoding,
    257                            layer=layer, enabled_drivers=enabled_drivers, **kwargs)
    258         elif mode == 'w':

~\anaconda3\envs\geo_env\lib\site-packages\fiona\collection.py in __init__(self, path, mode, driver, schema, crs, encoding, layer, vsi, archive, enabled_drivers, crs_wkt, ignore_fields, ignore_geometry, **kwargs)
    160             if self.mode == 'r':
    161                 self.session = Session()
--> 162                 self.session.start(self, **kwargs)
    163             elif self.mode in ('a', 'w'):
    164                 self.session = WritingSession()

fiona/ogrext.pyx in fiona.ogrext.Session.start()

fiona/_shim.pyx in fiona._shim.gdal_open_vector()

DriverError: countries.geojson: No such file or directory
enter code here

A: From the error description:
CPLE_OpenFailedError: countries.geojson: No such file or directory
DriverError: countries.geojson: No such file or directory
It literally seems like your are trying to open the file from a working path, where the file doesn't exists.
Please ensure that the file you are trying to read is in the same working directory as your Jupyter Notebook, or add the right path in your local machine to that same file.

A: Make sure that your geojson is in the same directory that your .ipynb file is.
Or you can just put the geojson file location in the read statement, for example:
ülke = geopandas.read_file("C:\user\folder1\folder2\data\countries.geojson")