text:
Q: Mongoose key/val set on instance not show in JSON or Console.. why? I have some information on my mongoose models which is transient. For performance reasons I dont wish to store it against the model.. But I do want to be able to provide this information to clients that connect to my server and ask for it.
Here's a simple example:
 var mongoose = require('mongoose'),
     db = require('./dbconn').dbconn;

 var PersonSchema = new mongoose.Schema({
  name    : String,
  age     : Number,
});

var Person = db.model('Person', PersonSchema);
var fred = new Person({ name: 'fred', age: 100 });

The Person schema has two attributes that I want to store (name, and age).. This works.. and we see in the console:
console.log(fred);

{ name: 'fred', age: 100, _id: 509edc9d8aafee8672000001 }

I do however have one attribute ("status") that rapidly changes and I dont want to store this in the database.. but I do want to track it dynamically and provide it to clients so I add it onto the instance as a key/val pair.
fred.status = "alive";

If we look at fred in the console again after adding the "alive" key/val pair we again see fred, but his status isnt shown:

{ name: 'fred', age: 100, _id: 509edc9d8aafee8672000001 }

Yet the key/val pair is definitely there.. we see that:
console.log(fred.status);

renders:

alive

The same is true of the JSON representation of the object that I'm sending to clients.. the "status" isnt included..
I dont understand why.. can anyone help?
Or, alternatively, is there a better approach for adding attributes to mongoose schemas that aren't persisted to the database?

A: Adding the following to your schema should do what you want:
PersonSchema.virtual('status').get(function() {
  return this._status;
});

PersonSchema.virtual('status').set(function(status) {
  return this._status = status;
});

PersonSchema.set('toObject', {
  getters: true
});

This adds the virtual attribute status - it will not be persisted because it's a virtual. The last part is needed to make your console log output correctly. From the docs:

To have all virtuals show up in your console.log output, set the
  toObject option to { getters: true }

Also note that you need to use an internal property name other than status (here I used _status). If you use the same name, you will enter an infinite recursive loop when executing a get.

A: Simply call .toObject() on the data object.
For you code will be like:
fred.toObject()

A: This has been very helpful. I had to struggle with this myself.
In my case, I was getting a document from mongoose. When I added a new key, the key was not visible to the object if I console.log it. When I searched for the key (console.log(data.status), I could see it in the log but not visible if I logged the entire object.
After reading this response thread, it worked.
For example, I got an object like this one from my MongoDB call:
`Model.find({}).then(result=> {
    //console.log(result);// [{ name:'John Doe', email:'john@john.com'}];

    //To add another key to the result, I had to change that result like this:
    var d = result[0];
    var newData = d.toJSON();
    newData["status"] = "alive";
    console.log(newData);// { name:'John Doe', email:'john@john.com', status:'alive'};
}).catch(err=>console.log(err))`

Hope this helps someone else.
HappyCoding


text:
Q: Sorting by empty cells "emptyTo" Tablesorter doesn't work I have a table with some data with dates and i want it to sort by the cells that are empty. By default tablesorter places them at the bottom and i need them at the top.
I read other posts related and none of them seems to work for me and i'm trying to figure out why.
I'm using Tablesorter 2.29.5
 /*! TableSorter (FORK) v2.29.5 *//*
  * Client-side table sorting with ease!
  * @requires jQuery v1.2.6+

And i'm setting the libraries properly (everything else works fine)
This is my tablesorter config in Jquery:
 $('#tablesorter')
            .tablesorter({
                theme : 'blue',
                widgets: ['filter', 'reflow','resizable'],
                sortList: [[0,0]],
                emptyTo: 'top',
                widgetOptions: {
                    resizable: true,
                    resizable_widths : [ '12%', '12%', '10%', '10%', '10%', '10%', '17%', '9%', '9%','0%']
                }

            }).tablesorterPager({
                container: $(".paginatorTableSorter"),
                output: '{{ "table.showing"|trans }} {startRow} {{ "table.to"|trans }} {endRow} ({filteredRows})'
            });
        $(".tablesorter").data('tablesorter').widgets = ['zebra', 'columns'];
        $(".tablesorter").trigger('applyWidgets');
        $('#tablesorter')
                .trigger('sortReset')
                .trigger('filterReset')
                .trigger('resizableReset')
                .trigger('pageAndSize', [1, 10]);

I also tried to sort by the column but since they're dates empty cells are ignored, so i'm setting emptyTo: 'top' following the jQuery tablesorter documentation https://mottie.github.io/tablesorter/docs/#emptyto
This is my (adapted) html(and Twig):

    {{ 'table.title.time.check-in' |trans }}
    {{ 'table.title.time.check-out' |trans }}

    {{ line.FECHA_E }}
    {{ line.FECHA_S }}

Is there anything i'm missing?

A: So, yes. As Mottie said i double checked the real value of the input and found the problem.

  {{ line.FECHA_E }}
  {% if line.FECHA_S is null %}{% else %}{{ line.FECHA_S }}{% endif %}

After posting the question i realized that i left the .trigger('sortReset') on the config but that was commented on my code.
In case anybody copies my tablesorter config just remove that part so it won't reset the default sorting values.
Once again thanks Mottie!

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿Por qué este código no funciona como espero? Tengo este problema con este código de telethon usando Python, la situación es que deseo que el código detecte un mensaje específico de un bot, debajo de este mensaje hay un botón el cual necesito que apriete una vez para desbloquear un enlace que te da el botón y luego leer ese enlace y enviar una parte del enlace a otro bot. El código actualmente aprieta el botón una vez pero no me envía el mensaje al otro bot. No obstante, si reenvío yo mismo el mensaje con el botón ya desbloqueado, si se acciona y me envía el enlace al otro bot.
@events.register(events.NewMessage(chats='aaaaaaaa'))
async def mob_handler(event):
    client = event.client
    if 'aaaaaaa' in event.raw_text:
        await asyncio.sleep(0.1)
        async for message in client.iter_messages('aaaaaa', limit=1, from_user='aaaaaaa'):
            await message.click(0)
        await asyncio.sleep(1)
        url = event.message.buttons[0][0].url
        await event.client.send_message('aaaaaaa', url.split('=')[1])

Cuando no manda el link me devuelve esto:
await event.client.send_message('aaaaaaaa', url.split('=')[1])
Error:

'NoneType' object has no attribute 'split'


text:
Q: CTest can not find executable file I have a question about starting the ctest. As I can understand that ctest uses CTestTestfile.cmake for the beginning of the unit test. What is the executable file? Why does ctest find it as *.exe if it is a CTestTestfile.cmake? What is wrong in my actions?
I have a folder Prj:

and folder /build with cmake output (CTestTestfile.cmake is here) as well as all ctest,cmake, etc. programs with their dll (is it right?).
Here is the text of CMakeLists.txt file:
cmake_minimum_required(VERSION 2.8)
project(MyTest C)
enable_testing()
include(CTest)

set(SOURCE_EXE simple_test.c)
include_directories(include)

### The most simple test
add_executable(simple_test ${SOURCE_EXE})
add_subdirectory(src)
target_link_libraries(simple_test "./src")

add_test(NAME simple_test COMMAND simple_test)

I have received the result in Windows cmd:


text:
Q: What are best words to reflect properties of time and being centralized or decentralized? I'm trying to reflect my research contributions in a table in an organized fashion.
Assume that 4 derivations of problem P are defined (and solved) as follows:

*

*Centralized solution to the untimed P

*Decentralized solution to the untimed P

*Centralized solution to the timed P

*Decentralized solution to the timed P
I'm gonna design a table as below:

however, I don't know what terminologies are suitable for labeling the columns. The first column determines the dependency on time, so my initial guess is temporality; although, I'm not sure whether it is a good word or not.
For the second column, I have no idea at all!
Any suggestions are highly appreciated.

A: I don't know your complete research, so I am not very sure. You can try Timing Constraint for the first column and Solution Scope/Scale for the second one.
And in case you are flexible with your table structure, you can tabulate the whole thing like below :

Keys :

Sol 1 : Centralized solution to a Timed problem.
Sol 2 : Decentralized solution to a Timed problem.
Sol 3 : Centralized solution to an Untimed problem.
Sol 4 : Decentralized solution to an Untimed problem.

I hope this was helpful ! :)


text:
Q: How can i fix the error POST http://localhost:3000/users.json 404 (Not Found) on reactjs? Basically i have a json file named users.json. (It is on public folder)
[{
    "username": "Antonio",
    "bestscore": "100"
},
{
    "username": "Tomé",
    "bestscore": "200"
}
]

And i want to add new users on that json file with two variables: username and bestscore
I'm doing a memory game that when user enter the initial page write his username. After user enter his username, i wanted to add his username to the json file, giving him as default bestscore:0.
Here is my code of the initial page:
class App extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     page: "game",
     showInicio: false,
     userInput:"",
     userInfo:[]
   };

   this.changePage = this.changePage.bind(this);

   this.handleChange = this.handleChange.bind(this);
   this.handleSubmit = this.handleSubmit.bind(this);
 }

 changePage(page) {
   this.getUserInfo()
   this.setState({
     page
   });
 }

 handleChange(event) {
   this.setState({userInput: event.target.value});
 }

 handleSubmit(event) {
   alert('Username was submitted: ' + this.state.userInput);
   event.preventDefault();
   this.setState({
     showInicio: !this.state.showInicio
});
   this.postUserInfo()
 }

 postUserInfo(){
 fetch("users.json", {
 method: "post",
 headers: {
   'Accept': 'application/json',
   'Content-Type': 'application/json'
 },
 //make sure to serialize your JSON body
 body: JSON.stringify({
   username: this.state.userInput,
   bestscore: 0
 })
})
.then( (res) => {
  console.log(res)
});
}

 render() {

   if (this.state.showInicio === false){
   return (

 Memory game

       <form onSubmit={this.handleSubmit}>

         Enter your username:
       <input type="text" value={this.state.userInput} onChange={this.handleChange}/>

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

    );
   }else{
   const { page } = this.state;
   return (

       <NavBar page={page} changePage={this.changePage} />

         {page === "game" && <Game username = {this.state.userInput}/>}
         {page === "leaderboard" && <LeaderBoard />}

   );
 }
}
}
export default App;

I'm getting this error: POST http://localhost:3000/users.json 404 (Not Found)
Anyone can help me?

A: The reason it can't find it is because users.json is not being served up anywhere. It is simply a file. In order to use fetch it needs to be hitting some type of endpoint (endpoint is a location that is hosted on a server i.e. examplesite.com/aboutme --> about me is the endpoint hosted on the website examplesite.com).
You should either run a server using express that will allow you to host that file and utilize it like an API endpoint. Or, you can manually edit the file. React has a good library for this called edit-json-file. It seems pretty straight forward to use, you can edit the file locally, AND you don't have to create an API or additional server.
So, quick answer: if you're just worrying about editing the file, edit it manually rather than hosting it on a server. But, if you want that experience and want to learn how to host an API, use express and host it there. Then, fetch the endpoint and execute the POST request like you've done in your code.


text:
Q: How do I perform Type Conversion in Clojure? How do I convert Symbol to String, Integer to Float, and other similar type conversions in Clojure?

A: You tell the compiler what type you want something to be by adding metadata to it.
This can make some operations faster and help eliminate reflection. The ^symbol is syntactic sugar for add this to the metadata for whatever comes next.
(defn my-function  [^String my-string] ....

Symbol to string:
(str 'my-symbol)

For numbers, use the name of the type as a function name:
(int 4922354)
(double 42)
(byte 254)
(char 20)
etc...

For more info: http://clojure.org/java_interop#toc35


text:
Q: show page number I choose on table of contents I'm using the book class.
In the begining of my document, I've used \frontmatter in order to switch page numbering to Roman numerals and \mainmatter to end this up and returning to Arabic numerals.
Why the page numbers of all 'addcontentsline{toc} {chapter} {my_CONTENT}' between the block \frontmatter … \mainmatter aren't shown in table of contents?
What must I do to get these page numbers in Roman numerals on my table of contents?


text:
Q: Remove host name from sender description mailx When I use this to send a mail I get the sender address as (root)<noreply@rediff.co.in> where root is the host name .
mailx -s 'Spammers `date -d "-1 days" +%Y-%m-%d`' mail_id1@gmail.com,mail_id2@gmail.com -- -r 'noreply@gmail.com'

Either I want to remove the host name completely in the sender description or specify another name.
Any help is appreciated.
Update:
I have also tried the same as mentioned by Rune in this question How set the From email address for mailx command? which doesn't seem to work.
mailx -s 'Spammers `date -d "-1 days" +%Y-%m-%d`' mail_id1@gmail.com,mail_id2@gmail.com -- -r 'noreply@gmail.com (Anonymous)'

A: This is what I had done to solve it. I just added -F 'Sender Name'
mailx -s 'Spammers `date -d "-1 days" +%Y-%m-%d`' mail_id1@gmail.com,mail_id2@gmail.com -- -F 'Spam Alert' -r 'noreply@gmail.com'


text:
Q: Why doesn't overflow work in my document? My Problem...
For some reason my scrolling wheel which I had made using css overflow: auto stopped working, why is that? The scrolling wheel is necessary as this is a long side bar which should have a scrolling wheel of its own
Note:I've removed a lot of li's and ul's so that I can post the question
As well as that as you see in my code there are a lot of repetitive ul's and li's. Is there an easier way to write all of this?
My Code...

                    Home Page

                    Added Arrays

                    AddOrMinus

                    ArayOnlyNumbers

                    Array Drawing

                    Array Squared

My CSS...
.mainBarOthers {width: 18%; border-right: 2px solid black; background-color: #feffdd; float: left; overflow: auto; box-shadow: 0px 1px 10px black; -webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; /* Safari */ -khtml-user-select: none; /* Konqueror HTML */-moz-user-select: none; /* Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ user-select: none; /* Non-prefixed version, currently supported by Chrome and Opera */}

And my JavaScript...
window.onload = function () {
    setInterval (function () {
        height = Math.max(document.body.scrollHeight, document.documentElement.clientHeight);

        if (height != heightCheck) {
            height = Math.max(document.body.scrollHeight, document.documentElement.clientHeight);
            height = height - 52;
            heightCheck = height;
            document.getElementById ('mainBar').style.cssText = 'height:' + height;}
    }, 10); // This makes the main bar be the size of the page (can this slow the page down? Better way of doing it...)
}

A: Answer...
var height;
var heightOthers;
var heightCheck;
var heightCheckOthers;

window.onload = function () {
    setInterval (function () {
        height = Math.max(document.body.scrollHeight, document.documentElement.clientHeight);
        heightOthers = Math.max (document.body.scrollHeight, document.documentElement.clientHeight);

            $(function () {
                if ($('#mainBarOthers').length) {
                    if (heightOthers != heightCheckOthers) {
                    heightOthers = Math.max(document.body.scrollHeight, document.documentElement.clientHeight);
                    heightCheckOthers = heightOthers;
                    document.getElementById ('mainBarOthers').style.cssText = 'height:' + heightOthers;
                    }
                }
                else if ($('#mainBar').length) {
                    if (height != heightCheck) {
                    height = Math.max (document.body.scrollHeight, document.documentElement.clientHeight);
                    height = height - 52;
                    heightCheck = height;
                    document.getElementById ('mainBar').style.cssText = 'height:' + height;
                }
            }
        });
    }, 10); // This makes the main bar be the size of the page (can this slow the page down? Better way of doing it...)
}

The problem was that I had two different pages, and the id was the same so they over wrote each other. The fix was to simply make the same function for the height for the other page two.


text:
Q: Symfony 2 : getReference and find Using the entity manager getReference() or find() method returns a non initialized object for some records of the database. Do you know why and what should be done?

A: getReference() does not load the object if it has not been loaded yet, it only returns a proxy to the object.
find() returns a loaded object.
cfr. the documentation:
// this call does not trigger a db query, but creates an empty proxy with the ID
$objectA = $this->entityManager->getReference('EntityName', 1);

$this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $objectA); // === true

// this will trigger a query, loading the state that's configured to eager load
// since the UnitOfWork already has a proxy, that proxy will be reused
$objectB = $this->entityManager->find('EntityName', 1);

$this->assertSame($objectA, $objectB); // === true

getReference() exists for special use cases, if you are fetching objects to use them, always use find().


text:
Q: jquery getting value of input text returns undefined I have a input text that is created with jquery and now I am trying to get the value of the input text when a button is pressed, but its returning undefined:
here is what I am trying to do:
$("#" + value).val(); \\value is 'ABC-123'
and here is my input text that is created via jQuery:
 html += '<input type="text" name="' + key + '-' + taskArray[i] + '" id="' + key + '-' + taskArray[i] + '" class="vendorDropdown" value="' + value.baseOrSchedStartList[i] + '" />	'; //key is ABC, taskArray[i] is 123 and value.baseOrSchedStartList[i] is the value, if its blank then in the input it will return just value

what am I doing wrong ? When I put text in the input text i expect that to be the value.
Here is a fiddle, https://jsfiddle.net/22dg6oyr/ but I cant get the jquery to run with it.

A: Your second snippet would produce something like: (notice the hyphen between ABC and 123)
<input type="text" name="ABC-123" id="ABC-123" class="vendorDropdown" />

Therefore, in your first snippet, value should be ABC-123 instead.

A: The text element that you created has a name of "ABC-123" (note the hyphen).  If value is "ABC123" (no hyphen) then it won't match any element.


text:
Q: Xamarin SQLite-NET Stopwatch not found I'm getting The type or namespace name 'Stopwatch' does not exist in the namespace 'System.Diagnostics' Are you missing an assembly reference?
The project is a PLC and the build targets are
   1. .NET framework 4 or later
  2. Silverlight 5
  3. WP8
  4. Windows Store App (Windows 8)
  5. Xamarin.Android
  6. Xamarin.iOS
if I uncheck silverlight and wp8, this error goes away, but comes more:
 Thread.VolatileWrite isn't defined
BindingFlags doesn't contain SetProperty
and others

A: Stopwatch is not available in Silverlight but WP8 is OK. Have you tried Profile 78? WP8, NET4.5, Windows Store & Xamarin.


text:
Q: How to provide async parameter to custom Angular validators I'm setting up form validators where the min & max of multiple fields are fetched via a single API. The app crashes when trying to pass one of those async values to a custom validator parameter, but it'll work when the value's hard-coded.
The error received when passing an async value is the following:

ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

file.ts:
export class PackageDimensionValidator {
   static validSize(min: number, max: number): ValidatorFn {
      return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value !== undefined && (isNaN(control.value) || control.value < min || control.value > max)) {
        return { 'exceedRange': true };
      }
      return null;
    };
   }
}

// ...

ngOnInit() {
   // Retrieve maximum package dimensions for input data validation.
   this.shipmentService.getMaxPackageSize()
      .subscribe(result => {
         this.packageRestrictions = new PackageRestrictions(result);
         console.dir(this.packageRestrictions);
         this.setupPackageValidators();
   });
}

setupPackageValidators() {
   const maxWidth = this.packageRestrictions.maxWidth; // Crashes on Async value.
   // const maxWidth = 5; // Works on hard-coded value.

   // Setup package dimension validators.
   this.packageSizeForm = this.formBuilder.group({
      maxWidth: new FormControl('', Validators.compose([
         PackageDimensionValidator.validSize(null, maxWidth),
         // Other validators ...
      ]))
   });
}

file.html:
<form [formGroup]="packageSizeForm">
   <input formControlName="maxWidth" type="text" required />
</form>

Ideally, there will be multiple formControls each with unique min & max's, all fetched at the same time by a single API. The thought process was to call that API, store its result locally, then build the form validators. I'm now questioning the order of this sequence.

A: I'm not completely sure that the error message you're getting reflects the issue you described. I'd start with Initiating packageSizeForm in your ngOnInit without validators:
ngOnInit() {
   this.packageSizeForm = new FormGroup({
          maxWidth: new FormControl('');
   });
   this.shipmentService.getMaxPackageSize()
      .subscribe(result => {
         this.packageRestrictions = new PackageRestrictions(result);
         console.dir(this.packageRestrictions);
         this.setupPackageValidators();
   });
}

Then set the validators in this.setupPackageValidators();:
setupPackageValidators() {
   this.packageSizeForm.get('maxWidth').clearValidators();
   this.packageSizeForm.get('maxWidth').setValidators(Validators.compose([
     PackageDimensionValidator.validSize(null, maxWidth)]);
   this.packageSizeForm.get('maxWidth').updateValueAndValidity();
}

A: You may want to use async validators
https://angular.io/api/forms/AsyncValidator
asyncValidator is passed as an optional third parameter to FormControl constructor:
class FormControl {
  ...
  constructor(
    formState: any = null,
    validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[],
    asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]
  )
  ...
}


text:
Q: Was there any later evidence of organic Breen vessels? The final episode of Voyager's third season, "Scorpion" (airdate May 21, 1997) contains this line:

TUVOK: Starfleet has encountered species that use organic-based vessels. The Breen, for example.

yet the Breen played heavily in the final season of Star Trek: DS9 (starting Sep 30, 1998).
Was there ever any evidence in DS9 of organic Breen vessels?
or was this just a throwaway line before the Breen plotline was developed?

A: Not in canon
The only reference I can find to the Breen's organic-based ships is in Tuvok's line in VOY 'Scorpion'.  However, out of canon, we see that there is further explanation (emphasis mine):

Their technology consisted of an element of biotechnology that as based on the algae on their homeworld. The Breen learnt to manipulate the algae genetic structure and use it to create biomaterials with special properties such as metal, plastic, silicon as well as other such substances. Such a key trait meant that every Breen vessel included its own hydroponics bay where damage components could be regrown. (TNG module: Star Trek: The Next Generation Core Game Book)

(Source)
However, in terms of canon, then yes, this does seem to be a throwaway line before the Breen were properly explored in the ending arc of DS9 which aired after 'Scorpion' (which first aired in 1996).

A: It seems to me that because of who owned what production rights to what at the time of filming.  ST:Discovery is racked with problems die to Paramount owning such key points of Canon, which made the making of Season 8 of DS9, hence why they made a documentary as opposed to season 8. Then you combine that with a throwaway line and a scant basis of Breen Tech Tree. The ST: Online has Been Ships that have organic parts as part of their special sets.


text:
Q: Elegant implementation of factorial tree graph Consider the tree graph used in part of my solution to this question:

Each level $i$ has $i!$ nodes, and the branching ratio is $i+1$:
I kludged together code to generate this graph (with code better left un-reproduced).
Is there an elegant method for generating such a tree graph for arbitrary number of levels?
A three-dimensional layout might look like this:

but I'd prefer a better embedding at the higher-$n$ levels, closer to this:

A: Based on @kglr's answer, but avoiding the use of undocumented functions (ExpressionGraph):
These trees correspond to the expression structure of a full array of dimensions {2, 3, 4, ...} (think TreeForm).
To recover this tree, we walk the array expression using Position and record the positions of subexpressions. We will use these positions as graph vertices.
The position specification is such that we can always compute the parent node of a position by dropping its last element (implemented as [[;;-2]]).   For example, the parent subexpression of a subexpression at position {2,1} is found at position {2}.
Position walks the expression in post-order, meaning that it returns the root vertex (position of full expression, {}) last. We reverse the vertex list to get the root as the first vertex instead. Then we drop this root from the edge computation (MapThread) as it has no parents.
Finally, we replace vertex names with integer vertex indices using IndexGraph.
symmetricTree[levels_List] :=
 Module[{vertices, edges},
  vertices = Reverse@Position[ConstantArray[0, levels], _, {0, Infinity}, Heads -> False];
  edges = MapThread[DirectedEdge, {vertices[[2;; , ;;-2]], vertices[[2;;]]}];
  IndexGraph@Graph[v, e]
 ]

I find this method clear and readable.
symmetricTree[{2, 3, 4}]

A: Update 3: ExpressionGraph is now available in version 12.1.
Update 2: a more streamlined  version for 2D graphs:
ClearAll[g]
g = GraphComputation`ExpressionGraph[ConstantArray[x, #], VertexLabels -> None] &;

Examples:
g[Range[2, 4]]

SetProperty[g[{3, 1, 3, 1, 2, 1, 4}],
  {GraphLayout -> "RadialEmbedding", EdgeShapeFunction -> "Line"}]

Original answer:
ClearAll[f]
f[g_: Graph][n_List, o : OptionsPattern[]] := g[UndirectedEdge @@@ EdgeList@
    GraphComputation`ExpressionGraph[ConstantArray[x, n]],
     o, GraphLayout -> {"BalloonEmbedding"}, ImageSize -> Large]
f[g_: Graph][n_Integer, o : OptionsPattern[]] := f[g][Range[2, n], o]

Examples:
f[][6]

f[][6, GraphLayout -> {"RadialEmbedding"}]

g1 = f[Graph3D][6]

g2 = f[Graph3D][6, GraphLayout -> {"RadialEmbedding"}]

Use a list for number of vertices on each layer as the argument:
f[][{3, 5, 2, 4}, GraphLayout -> {"RadialEmbedding", "LayerSizeFunction" -> (# &)}]

Update: ... to take the Graph3D and somehow improve the layout on the high-n layers: There seems to be lots of wasted space.
One way to change the box ratios without distorting the vertex shapes is to modify the VertexCoordinates using ScalingTransform:
SetProperty[g1, VertexCoordinates -> ScalingTransform[{1, 1, 3}][GraphEmbedding@g1]]

SetProperty[g2, VertexCoordinates -> ScalingTransform[{1, 1, 3}][GraphEmbedding@g2]]

Or add the suboption "LayerSizeFunction" in  "RadialEmbedding":
g3 = f[Graph3D][6, GraphLayout -> {"RadialEmbedding", "LayerSizeFunction" -> (# &)}];
SetProperty[g3, VertexCoordinates -> ScalingTransform[{1, 1, -3}][GraphEmbedding@g3]]

SetProperty[#, VertexCoordinates -> ScalingTransform[{1, 1, 3}][GraphEmbedding@#]] &@
 f[Graph3D][{3, 5, 2, 4}, GraphLayout -> {"RadialEmbedding", "LayerSizeFunction"->(#&)}]

A: IGraph/M already has this built-in as IGSymmetricTree. You can specify the number of branches at each level.

IGSymmetricTree[
 Range[2, 4],
 DirectedEdges -> True,
 GraphLayout -> "LayeredEmbedding"
]

The implementation is mostly in C (not Mathematica) and not from igraph this time. This is simply easier to implement procedurally, for which C is a good fit. This is why I did not do it in pure WL.
Here's another structure, with a different number of branches at each level.
IGSymmetricTree[{5, 4, 3, 2}]

A: here is my elegant implementation
l[c_]:=TakeList[Range@Sum[k!,{k,c}],Range@c!][[c-1]];
T[x_]:=Graph[(F=Flatten)@Table[MapThread[#->#2&,{Sort@F@Table[l@i,i],l[i+1]}],{i,2,x+1}]];

T@3

which returns

but if your Mathematica version doesn't support TakeList here is another way
s[x_] := Sum[k!,{k,x}];
z[y_] := Partition[Range[s@y+1,s[y+1]],1+y];
v[n_] := Table[{Flatten[z[n-1]][[i]]->z[n][[i,j]]},{i,n!},{j,n+1}];
tree[t_] := Graph[Flatten[Array[v@#&,t],3]];

tree@3

tree@6

A: I don't know if you find this elegant. But I give it a try.
maxdepth = 5;
Graph[
 Transpose[{
   Join @@ MapIndexed[
     {x, i} \[Function] Join @@ Transpose[ConstantArray[Range @@ x, (i + 1)]],
     Join[{{1}}, Partition[Accumulate[Range[maxdepth - 1]!], 2, 1] + ConstantArray[{1, 0}, maxdepth - 2]]
     ],
   Range[2, Total[Range[maxdepth]!]]
   }],
 DirectedEdges -> True,
 GraphLayout -> "BalloonEmbedding"
 ]

Edit
Out of curiosity, I adapted the algorithm above to produce also other symmetric trees.
SymmetricTree[branchlist_?(VectorQ[#, IntegerQ] &)] :=
 Module[{levelnodecounts},
  levelnodecounts = FoldList[#1 #2 &, 1, branchlist];
  Graph[Transpose[{
     Join @@ MapIndexed[
       {x, i} \[Function] Join @@ Transpose[ConstantArray[Range @@ x, branchlist[[i[[1]]]]]],
       Join[
        {{1}},
        Partition[Accumulate[Most[levelnodecounts]], 2, 1] + ConstantArray[{1, 0}, Length[branchlist] - 1]
        ]
       ],
     Range[2, 1 + Total[Rest[levelnodecounts]]]}],
   DirectedEdges -> True
   ]
  ]

Regarding speed, it seems to be on par with IGSymmetricTree. Of course, I cannot provide such a detailed user interface as Szabolcs so I would suggest to use IGraphM whenever possible.
Edit 2
Adapting my (slow) code for fractal trees, here is another way to embedd the tree:
BoccoliEmbedding[branchlist_] :=
 Module[{data0, data, θ, stem, thickness, s1, s2, f, F},
  θ = Pi/4.;
  s1 = 1/GoldenRatio // N;
  s2 = 1/GoldenRatio // N;
  stem = {0., 0., 1.};
  thickness = 0.15;
  data0 = {Join[
     {{0., 0., 0.}},
     {stem},
     {{thickness, 1., 0.}},
     Table[
      RotationMatrix[2. k Pi/branchlist[[1]], {0, 0, 1}].{Cos[θ], 0.,Sin[θ]},
      {k, 0, branchlist[[1]] - 1}]
     ]
    };
  f = {U, n} \[Function] Table[
     Join[
      {U[[1]] + U[[2]]},
      {U[[i]]},
      {s2 U[[3]]},
      Dot[
       s1 Table[RotationMatrix[2. Pi j/n, U[[2]]].U[[i]], {j, 0, n - 1}],
       RotationMatrix[{U[[i]], U[[2]]}]
       ]
      ],
     {i, 4, Length[U]}];
  F = {data, n} \[Function] Join @@ (f[#, n] & /@ data);
  data = Join @@ FoldList[F, data0, Join[Rest[branchlist], {1}]];
  data[[All, 1]] + data[[All, 2]]
  ];

And this is how we apply it:
b = Range[2, 7];
plot = Graph[
  EdgeList[SymmetricTree[b]],
  VertexCoordinates -> BoccoliEmbedding[b]
  ]


text:
Q: KeyError at /login/ 'is_login' Request Method: django enter image description here
I am coding web with django. I can not use session. I wanna check login use session
def user_login(request):
    if request.session['is_login'] == True:
        return HttpResponseRedirect('/home')
    else:
        next = request.POST.get('next', request.GET.get('next', ''))
        if request.method == "POST":
            username1 = request.POST.get('username')
            password1 = request.POST.get('password')
            user = authenticate(username=username1, password=password1)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    if next:
                        request.session['is_login'] = True
                        return HttpResponseRedirect(next)

                    return HttpResponseRedirect('/home')

                else:
                    return HttpResponse('Inactive user')
            else:
                return HttpResponseRedirect(LOGIN_URL)
        return render(request, "pages/login.html")

How to fix

A: As I mentioned in the comments
change this:
if request.session['is_login'] == True:

to this:
if request.session.get('is_login') == True:

request.session.get does not raise KeyError It either returns the value at the key position or a None is returned.
You can also change the default behavior when a key is not found i.e instead of returning None you can return something else like this:
request.session.get('is_login', False)

The above statement will return False on failure instead of None.
visit docs for more information.

A: issue here is request.session doesn't have a key named is_login initially you are inserting that key when user successfully logs in so you need to add a check if key exists in session dict or not for that
use this
if 'is_login' in request.session and request.session['is_login'] == True:
    return HttpResponseRedirect('/home')

A: I think you are making wrong check to see if the user is authenticated. If you want to see if an user is authenticated, simply do it by using is_authenticated:
def user_login(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('/home')
    else:
      # rest of the code

Also remove the line request.session['is_login'] = True because, django handles authentication itself. You don't need to use session to store that information.

A: Thanks all support me . I resolved
I did edit if request.session.get['is_login'] == True: to
  if request.session.get('is_login') == True:


text:
Q: Formatting set_fact variable I need to have all the userid in a single variable, all separated by \n.
Code is as below.
  - name: Retrieve the user id and instance
    shell: ls -l {{item}} | grep -v total| awk '{print $3}'
    register: find_result_userid
    with_items:
     - /tmp/log/logs/log1
     - /tmp/log/logs/log2
     - /tmp/log/logs/log3

  - name: Combine all userid
    set_fact:
     server_names: "{{ find_result_userid.results | map(attribute='stdout_lines')|list }}"

The output is as below.
ok: [localhost] => {
    "ansible_facts": {
        "server_names": [
            [
                "root",
                "root",
                "root"
            ],
            [
                "root",
                "root",
                "root"
            ],
            [
                "root",
                "root",
                "root"
            ]
        ]
    },
    "changed": false
}

I need something like below: i.e all ids separated by a line in a single variable.
 "server_names": [
            [
                "root",
                "root",
                "root",
                "root",
                "root",
                "root",
                "root",
                "root",
                "root"
            ]

Kindly advise.

A: flatten the lists
- set_fact:
    server_names: "{{ server_names|flatten }}"

A: If the number of items you are iterating with is static, I would guess, that you can use the + operator to append the your results
- name: Combine all userid
    set_fact:
     server_names: "{{ find_result_userid.results[0].stdout_lines + find_result_userid.results[1].stdout_lines + find_result_userid.results[2].stdout_lines}}"

Otherwise if it is not static, I think Vladimir Botkas answer is better.

A: Combining with what Vladmir Botka suggested, to get result in a single task.
  - name: Combine all userid
    set_fact:
      server_names: "{{ find_result_userid.results | map(attribute='stdout_lines')|list | flatten }}"


text:
Q: Module not found: Can't resolve '@mui/icons-material/Polyline' I am trying to use this material ui icon in react. It has been imported as follows:
import PolylineIcon from '@mui/icons-material/Polyline';
.
.
return (<PolylineIcon className={classes.icon} />); // Module not found: Can't resolve '@mui/icons-material/Polyline'

But I get the aforementioned error and npm fails to compile. What's the problem here? Knowing that I am using other icons smoothly with no errors; such as:
import EditIcon from '@mui/icons-material/Edit';
.
.
.
return (<EditIcon className={classes.icon} />); //works fine

This compiles fine, so @mui/icons-material module is indeed installed and works.
Dependencies from package.json:
    "@mui/icons-material": "^5.0.1",
    "@mui/material": "^5.0.2",

Thanks in advance

A: The polyline icon was added later. Update your @mui/icons-material to ^5.2.5.

A: Polyline seems to have been added to @mui/icons-material in the release v5.2.0 from this pull request.
You should update @mui/icons-material at least to version 5.2.0 to use Polyline icon


text:
Q: partial derivative of the Hamiltonian inside a function Let $f( \mathcal{H}(q,p))$ where $q(t)$ and $p(t)$ are time dependent.
My Professor wrote:
$$
\frac{\partial f}{\partial t} = f' \frac{\partial H}{\partial t}
$$$$
\frac{\partial f}{\partial q} = f' \frac{\partial H}{\partial q}
$$
$$
\frac{\partial f}{\partial p} = f' \frac{\partial H}{\partial p}
$$
I'm not sure if my professor doesn't take into consideration the derivatives of $f$ and just calls them $f'$.
In other words is he saying that $f' = d_tf = d_qf = d_pf$. or am I missing something ?

A: It's the usual confusion. Slightly oversimplified explanation is the following: he is using $f$ for two different functions. One is $f:\mathbb{R}\to \mathbb{R}$. The other is the composition of this $f$ with $H$. We'll denote it by $F=f\circ H$. Then $F$ is a function of $p, q, t$ just like $H$, while $f$ is a function of single input, which is not named but we can call $u$. Then $f'$ is the derivative of $f$ with respect to the only input it has, i.e. $u$, while "$\frac{\partial f}{\partial q}$" should really be "$\frac{\partial F}{\partial q}$" and is by chain rule
$$\frac{\partial F}{\partial q}=\frac{\partial (f\circ H)}{\partial q}= \frac{df}{du}\frac{\partial H}{\partial q}=f'\frac{\partial H}{\partial q}$$
In fact, in the setup you describe the full story is more complicated. There are 2 functions both denoted by $H$ - one is a function of two inputs (we'll call it $H$) and one is a function of time only, namely what we will call $h(t)=H(p(t), q(t))$. These are different and are commonly denoted by the same letter (in your prof's case by $H$).
There are 3 functions all called $f$: the function of single input, the function of two inputs $F=f\circ H$ and the function of time only, $\phi$:
$\phi(t)=f(h(t))=F(p(t), q(t))=f(H(p(t), q(t)))$.
These are all different and are commonly denoted by the same letter (in your prof's case by $f$).
All partial derivatives of $f, F, \phi$ and $h, H$ are interconnected by chain rule in various ways, similarly to the above, but slightly more complicated.
The "usual confusion" arises when one uses the same letter for all the functions and thus for their partial derivatives. This is very common everywhere, but especially in physics, where the variables have some meaning (like $H$ is total energy), and it seems weird to give them different name when considering them as functions of one set of inputs vs another: say, $h$ when considered as function of time only, versus $H$ when considered as function of position and momentum. I mean, energy is energy, it's all $H$ to a physicist. Nevertheless, mathematically these are different functions with different domains (and as a result different types of partials), and when doing math with them this sometimes comes up.
(The "this notation sucks" rant continued: Even worse, the notation for partial derivatives interplays with this in exactly the wrong way -- by providing the info about which input is being varied, and mostly ignoring the question of what is being held fixed. This becomes particularly unfun when you do thermodynamics, but that's another story.)


text:
Q: How to persist this whole page same with adding background color using div tag I had a page which has one background image on that i am keeping some buttons. But the background of the whole page is white. That's not good i want background color and i need to persist this whole thing same.

                <form style="padding-left:250px;">
                    <INPUT TYPE="button" style="background-color:SteelBlue;width:100px;height:30px;font-size:150%;margin-bottom:10px" VALUE="Submit" onClick="window.open('http://www.google.com','_blank');">

                    <INPUT TYPE="button" style="background-color:SteelBlue;width:100px;height:30px;font-size:150%;margin-bottom:10px" VALUE="Submit" onClick="window.open('http://www.google.com','_blank');">

                    <INPUT TYPE="button" style="background-color:SteelBlue;width:100px;height:30px;font-size:150%;margin-bottom:10px" VALUE="Submit" onClick="window.open('http://www.google.com','_blank');">

                    <INPUT TYPE="button" style="background-color:SteelBlue;width:100px;height:30px;font-size:150%;margin-bottom:10px" VALUE="Submit" onClick="window.open('http://www.google.com','_blank');">

                    <INPUT TYPE="button" style="background-color:SteelBlue;width:100px;height:30px;font-size:150%;margin-bottom:10px" VALUE="Submit" onClick="window.open('http://www.google.com','_blank');">

                </form>

A: try this ,
http://www.w3schools.com/css/tryit.asp?filename=trycss_background_shorthand
background-color
background-image
background-repeat
background-attachment
background-position
background:#ffffff url('img_tree.png') no-repeat right top;

            <form style="padding-left:250px;">
                <INPUT TYPE="button" style="background-color:SteelBlue;width:100px;height:30px;font-size:150%;margin-bottom:10px" VALUE="Submit" onClick="window.open('http://www.google.com','_blank');">

                <INPUT TYPE="button" style="background-color:SteelBlue;width:100px;height:30px;font-size:150%;margin-bottom:10px" VALUE="Submit" onClick="window.open('http://www.google.com','_blank');">

                <INPUT TYPE="button" style="background-color:SteelBlue;width:100px;height:30px;font-size:150%;margin-bottom:10px" VALUE="Submit" onClick="window.open('http://www.google.com','_blank');">

                <INPUT TYPE="button" style="background-color:SteelBlue;width:100px;height:30px;font-size:150%;margin-bottom:10px" VALUE="Submit" onClick="window.open('http://www.google.com','_blank');">

                <INPUT TYPE="button" style="background-color:SteelBlue;width:100px;height:30px;font-size:150%;margin-bottom:10px" VALUE="Submit" onClick="window.open('http://www.google.com','_blank');">

            </form>

A: Use CSS:
body
{
    background: color: #f00; /*your color here*/
}

This will make the body element's background whichever color you choose for all the pages.

A:    body {
      background-color: #ff0000
   }


text:
Q: Restful API for CakePHP 2 I am creating a Restful WebService with CakePHP 2 however, i am getting 500 Internal Server Error since i am not able to capture Post Data. The Rest Server is as below:
App::import ( 'Vendor', 'ExchangeFunctions', array ('file'=> 'exchange/exchangefunctions.php'));

class ExchangeController extends AppController
{
    public $components = array('RequestHandler');
    public
    function index()
    {
        $exchange = new ExchangeFunctions();
        $data = $this->request->data('json_decode');
        $exchange->username = $_POST['username'];
        $exchange->password = $_POST['password'];
        $emailList = $exchange->listEmails();
        $response  = new stdClass();
        $response->emailList = $emailList;
        foreach($emailList->messages as $listid => $email)
        {
            $tempEmail = $exchange->getEmailContent(
                $email->Id,
                $email->ChangeKey,
                TRUE,
                $_POST['attachmentPath']
            );
            $response->emails[$tempEmail['attachmentCode']] = $tempEmail;
        }
        $this->set('response', $response);
        $this->set('_serialize','response');
    }
}

and the client goes as:
class ApitestController extends AppController
{
    Public function index()
    {
        $this->layout = 'ajax';
        $jRequestURLPrefix = 'http://localhost/EWSApi/';
        $postUrl           = $jRequestURLPrefix."exchange/index.json";

        $postData          = array(
            'username'      => 'username',
            'password'      => 'password',
            'attachmentPath'=> $_SERVER['DOCUMENT_ROOT'] . $this->base . DIRECTORY_SEPARATOR . 'emailDownloads' . DIRECTORY_SEPARATOR . 'attachments'
        );
        $postData = json_encode($postData);

        pr($postData);
        $ch       = curl_init( $postUrl );
        $options  = array(
            CURLOPT_RETURNTRANSFER=> true,
            CURLOPT_HTTPHEADER         => array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($postData)
            ),
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_POSTFIELDS     => $postData,
        );
        curl_setopt_array( $ch, $options );
        $jsonString = curl_exec($ch);
        curl_close($ch);
        $data       = json_decode($jsonString, FALSE);

        echo $jsonString;
    }

}

Not sure where i am messing up! Please help!

A: Ok, after a second look there are some more suspicious things. As already mentioned, your CURL request uses GET instead of POST.
$options  = array(
    ...
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS     => $postData,
);

Another thing is that you are encoding the POST data for your CURL call to JSON, but then you are trying to access it on the other side using $_POST, however there won't be anything, POST data would have to be key/value query string formatted in order to appear in $_POST. You have to read php://input instead, which may be what you were trying to do with
$data = $this->request->data('json_decode');

However you must use CakeRequest::input() for that purpose, and of course you must then use the $data variable instead of $_POST
$data = $this->request->input('json_decode');
$exchange->username = $data['username'];
$exchange->password = $data['password'];

....

$tempEmail = $exchange->getEmailContent(
    $email->Id,
    $email->ChangeKey,
    TRUE,
    $data['attachmentPath']
);

Also make double sure that your CURL request looks like expected:
$options  = array(
    ...
    CURLOPT_POSTFIELDS => $postData,
    CURLINFO_HEADER_OUT => true // supported as of PHP 5.1.3
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

echo '<pre>';
print_r($info);
echo '</pre>';


text:
Q: How to do versioning for RDLC reports? I have RDLC reports and I want to do a versioning for them by link each report with its model as they are frequently change maybe in template only or changes in datasets.
Is there any ideas to do that?
I have tried to do a versioning by folders by putting models and reports in the same folder version for each side.


text:
Q: When should I think about upgrading our RDS MySQL instance based on memory usage? It seems like our DB server is doing garbage collection at a increasingly faster rate, which seem normal since it's growing. What's a good rule of thumb of when to switch to a bigger instance, I'm not a DBA and have no frame of reference. It seems to be doing garbage collection once every 2-3 days now whenever there's only 100mb left.

The server itself has 1.7GB of RAM.

A: Before you switch server models, you need to know what differences there in configuration
I sat down and carefully looked over all default MySQL settings that would normally be written in a my.cnf. All are values are the same with the exception of two

*

*max_connections

*innodb_buffer_pool_size
Amazon set the following values based on server model
MODEL      max_connections innodb_buffer_pool_size
---------  --------------- -----------------------
t1.micro   34                326107136 (  311M)
m1-small   125              1179648000 ( 1125M,  1.097G)
m1-large   623              5882511360 ( 5610M,  5.479G)
m1-xlarge  1263            11922309120 (11370M, 11.103G)
m2-xlarge  1441            13605273600 (12975M, 12.671G)
m2-2xlarge 2900            27367833600 (26100M, 25.488G)
m2-4xlarge 5816            54892953600 (52350M, 51.123G)

For more information see my past posts on MySQL in Amazon RDS

*

*Sep 21, 2012 : MySQL 5.5 Runs Out of Memory, Drops All Connections When Creating Many Databases

*Sep 18, 2012 : How do I reduce the database size on AWS RDS MySQL?

*Sep 10, 2012 : Does the Amazon RDS backup/snapshot service lock tables?

*Aug 02, 2012 : Local database vs Amazon RDS

*Jul 25, 2012 : Scaling Percona datacenters: setup and replication

A: Just ran across this question, and can give you a couple of suggestions.
If you're trying to gauge when to move to a bigger instances (vs. increasing the size of the databases) when you're getting close to hitting some sort of resource limit:  Memory, I/O and CPU all have the ability to limit your performance.
The symptom you mention in the question may be a symptom that you're using more and more memory - memory used for cache & buffers are being reclaimed for other uses.  Upgrading to a large instance type will increase the amount of available memory.
The chart that Rolando posted should give you a good guideline as to the number of available connections - if you're hitting those limits, then it's time to upgrade.  Available connections are directly related to available memory, so hitting connection limits means you should upgrade.
If your CPU is averaging > 50% or so, you might want to start planning on an upgrade.
Finally, if you see consistently high I/O you may want to consider a larger instance (generally, the more powerful the instance the better the I/O) or using provisioned IOPS.


text:
Q: ¿Formas de implementar una clase Alloc? Los contenedores stl de C++ utilizan la plantilla Alloc para administrar la memoria. La clase por defecto es std::allocator que tengo entendido utiliza los métodos ::operator new(size) y ::operator delete(ptr) para reservar y liberar la memoria.
He leído navegando por internet que podemos usar un memory-pool como alternativa en ciertos casos. ¿En qué consiste esto? ¿De qué otras formas podemos implementar una clase Alloc?

A: Usar un pool no tiene ningún misterio. Lo que sucede en estos casos es que pasas a gestionar directamente la asignación de memoria en vez de delegar en el Sistema Operativo. ¿Cómo se hace eso? Bueno, el caso general no es dificil de explicar:
Haces reservas de memoria lo suficientemente grandes como para poder almacenar en ellas varios elementos. Adicionalmente implementas un mecanismo que permita gestionar dicha memoria (control de memoria ocupada, asignación de memoria libre y liberación de la memoria ocupada).
Una posible implementación:
class MemoryPool
{
public:
  MemoryPool(int capacity)
    : capacity_{capacity}
    , data_{new int[capacity]}
    , firstBlockFree_{0}
  {
    std::iota(data_, data_ + capacity_ - 1, 1);
    data_[capacity_ - 1] = -1;
  }

  ~MemoryPool()
  {
    delete[] data_;
  }

  int* New(int value)
  {
    if( firstBlockFree_ == -1 )
      return nullptr;

    int* toReturn = data_ + firstBlockFree_;
    firstBlockFree_ = *toReturn;

    *toReturn = value;
    return toReturn;
  }

  bool Free(int* ptr)
  {
    if( ptr < data_ || ptr >= data_ + capacity_ )
      return false;

    *ptr = firstBlockFree_;
    firstBlockFree_ = ptr - data_;

    return true;
  }

  size_t Size() const
  {
    size_t counter = 0;

    int next = firstBlockFree_;
    while( next != -1 )
    {
      ++counter;
      next = data_[next];
    }

    return capacity_ - counter;
  }

  size_t Capacity() const
  { return capacity_; }

private:
  int capacity_;
  int* data_;
  int firstBlockFree_;
};

Este ejemplo, por legibilidad, no usa plantillas. Su funcionamiento es facil de explicar:
Al crear el pool se indica el número de elementos a gestionar. El objeto se encarga de hacer la reserva de memoria oportuna. Cada vez que se le pide un nuevo objeto, el pool verifica si tiene memoria disponible y, de ser así, devuelve el puntero correspondiente.
Para gestionar la memoria libre sin consumir memoria adicional, el pool usa el siguiente truco: Cada posición libre almacena el índice de otra posición libre, salvo la última posición libre, cuyo valor será -1. Usa la variable firstBlockFree_ para conocer la primera posición libre. Cada vez que se pide un nuevo objeto basta con actualizar firstBlockFree_ para que apunte al siguiente índice libre. Cuando se libera memoria, el nodo recién liberado se pone en primera posición (será el primero en ser usado en una nueva reserva).
En líneas generales esto es lo que hace un pool de memoria. Su comportamiento básico se basa en reducir el número de news y deletes que se hacen en el sistema, ya sea porque dichas llamadas son demasiado lentas (en el caso de objetos pequeños) o para intentar reducir un poco la fragmentación de la memoria.
Ahora bien, no conviene agobiarse con ello ya que, salvo que la situación lo justifique, lo más razonable es dejar que sea el propio Sistema Operativo el que se encargue de gestionar la memoria. Es bastante probable que un sistema que lleva en desarrollo varias décadas y por el que ha pasado gente bastante inteligente sepa gestionar la memoria mejor que nosotros. Gestionar nosotros mismos la memoria no es algo baladí y es muy muy muy muy, pero que muy muy facil meter la pata o conseguir un rendimiento peor que si no hubiésemos hecho nada de esto.
Posibles mejoras:

*

*La clase del ejemplo no contempla double delete. Si eso sucede el pool se comportará de forma errática a partir de ese momento.

*En vez de reservar toda la memoria de golpe se podrían ir reservando bloques según vayan creciendo las necesidades

*Esta clase no es capaz de gestionar objetos de diferentes tamaños.

Puedes ver la clase funcioando aquí


text:
Q: Add 'urldate' to bibliography I'm using biblatex with a custom bibstyle based on the trad-standard style:
\RequireBibliographyStyle{trad-standard}

In my custom style I redefined some appearances like bold text etc. but now I want to add the urldate to the output if a URL is given.
I have for example a website as reference. Mendeley exported the resource as @misc which seems to be correct, but the access date (saved as urldate) is not showing up.
I now searched the code of the trad-standard bibstyle and didn't find the urldate key, so it's quite logical that there is no output. How could I add the functionality of always displaying the urldate, if a URL and the urldate is given, no matter what entry type I'm in?
My guess is to renew the doi+eprint+url macro as it is responsible for the output of the URL. So if I could append the urldate to the output, it should do what I want. The problem is, that I have no idea how tho append the urldate to the macro.

Here is my custom .bbx file:
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This is a custom bibliography style based on the trad-abbrv style
% by Marco Daniel (2012--2015) and Moritz Wemheuer (2016--).
%
% This package is released under the terms of the
% LaTeX Project Public License v1.3c or later
% See http://www.latex-project.org/lppl.txt
%
% Copyright (c) 2012 -- 2015 Marco Daniel
%               2016 --      Moritz Wemheuer
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% %%%%%%%%%%%%%
% Declare Style
% %%%%%%%%%%%%%

\ProvidesFile{custom-abbrv.bbx}[2017/10/18 v1.0.0 Custom abbrv Bibliography Style]

% %%%%%%%%%%%%%%
% Require Styles
% %%%%%%%%%%%%%%

\RequireBibliographyStyle{trad-standard}

% %%%%%%%%%%%%%
% Basic Options
% %%%%%%%%%%%%%

\ExecuteBibliographyOptions{
    abbreviate      = false,
    arxiv           = false
    autolang        = hyphen,
    backref         = false,
    dateabbrev      = true,
    eprint          = false,
    hyperref        = true,
    labelnumber     = true,
    maxnames        = 3,
    minnames        = 3,
    sorting         = none,
}

% %%%%%%%%%%%%%%%%%%%
% trad-abbrv Settings
% %%%%%%%%%%%%%%%%%%%

\@ifpackagelater{biblatex}{2016/03/01}{%
    \@ifpackagelater{biblatex}{2016/05/14}{%
        \DeclareNameFormat{abbrv}{%
            \usebibmacro{name:given-family}%
            {\namepartfamily}%
            {\namepartgiveni}%
            {\namepartprefixi}%
            {\namepartsuffixi}%
            \usebibmacro{name:andothers}%
        }%
    }{%
        \DeclareNameFormat{abbrv}{%
            \nameparts{#1}%
            \usebibmacro{name:given-family}%
            {\namepartfamily}%
            {\namepartgiveni}%
            {\namepartprefixi}%
            {\namepartsuffixi}%
            \usebibmacro{name:andothers}%
        }%
    }%
}{%
    \DeclareNameFormat{abbrv}{%
        \usebibmacro{name:first-last}{#1}{#4}{#6}{#8}%
        \usebibmacro{name:andothers}%
    }%
}%
\DeclareNameAlias{default}{abbrv}

\DeclareFieldFormat{bibentrysetcount}{\mkbibparens{\mknumalph{#1}}}
\DeclareFieldFormat{labelnumberwidth}{\mkbibbrackets{#1}}
\DeclareFieldFormat{shorthandwidth}{\mkbibbrackets{#1}}

\@ifpackagelater{biblatex}{2016/05/14}{%
    \defbibenvironment{bibliography}%
        {%
            \list{%
                \printtext[labelnumberwidth]{%
                    \printfield{labelprefix}%
                    \printfield{labelnumber}%
                }%
            }{%
                \setlength{\labelwidth}{\labelnumberwidth}%
                \setlength{\leftmargin}{\labelwidth}%
                \setlength{\labelsep}{\biblabelsep}%
                \addtolength{\leftmargin}{\labelsep}%
                \setlength{\itemsep}{\bibitemsep}%
                \setlength{\parsep}{\bibparsep}%
            }%
            \renewcommand*{\makelabel}[1]{\hss##1}%
        }
        {\endlist}
        {\item}%
}{%
    \defbibenvironment{bibliography}%
        {%
            \list{%
                \printtext[labelnumberwidth]{%
                    \printfield{prefixnumber}%
                    \printfield{labelnumber}%
                }%
            }{%
                \setlength{\labelwidth}{\labelnumberwidth}%
                \setlength{\leftmargin}{\labelwidth}%
                \setlength{\labelsep}{\biblabelsep}%
                \addtolength{\leftmargin}{\labelsep}%
                \setlength{\itemsep}{\bibitemsep}%
                \setlength{\parsep}{\bibparsep}%
            }%
            \renewcommand*{\makelabel}[1]{\hss##1}%
        }%
        {\endlist}%
        {\item}%
}

\defbibenvironment{shorthands}%
    {%
        \list{%
            \printfield[shorthandwidth]{shorthand}%
        }{%
            \setlength{\labelwidth}{\shorthandwidth}%
            \setlength{\leftmargin}{\labelwidth}%
            \setlength{\labelsep}{\biblabelsep}%
            \addtolength{\leftmargin}{\labelsep}%
            \setlength{\itemsep}{\bibitemsep}%
            \setlength{\parsep}{\bibparsep}%
            \renewcommand*{\makelabel}[1]{\hss##1}%
        }%
    }%
    {\endlist}%
    {\item}%

\DeclareBibliographyDriver{set}%
    {%
        \entryset%
        {%
            \ifbool{bbx:subentry}%
                {%
                    \printfield[bibentrysetcount]{entrysetcount}%
                    \setunit*{\addnbspace}%
                }%
                {}%
        }%
        {}%
        \newunit\newblock%
        \usebibmacro{setpageref}%
        \finentry%
    }

% %%%%%%%%%%%%%%%%%
% Appearance Styles
% %%%%%%%%%%%%%%%%%

% Name
\renewcommand{\labelnamepunct}{\addcolon\space}

% Title
\DeclareFieldFormat*{title}{\enquote{#1}\isdot}
\DeclareFieldFormat{journaltitle}{\mkbibemph{#1},}

% Volume
\DeclareFieldFormat[article]{volume}{#1}

% Number
\DeclareFieldFormat*{number}{\mkbibparens{#1}}

% Pages
\DeclareFieldFormat*{pages}{\space#1\space}
\renewcommand*{\bibpagespunct}{\addspace}

% Year
\DeclareFieldFormat{date}{\textbf{#1}}

% URL
\DeclareFieldFormat{url}{URL:\space\url{#1}}

% ISSN / ISBN
\DeclareFieldFormat{issn}{ISSN:\space\url{#1}}
\DeclareFieldFormat{isbn}{ISBN:\space\url{#1}}

% DOI
\DeclareFieldFormat{doi}{%
    DOI\addcolon\space
    \ifhyperref
        {\href{http://dx.doi.org/#1}{\nolinkurl{#1}}}
        {\nolinkurl{#1}}%
}

% Item Separation
\setlength\bibitemsep{.5\baselineskip}

% Alignment
\AtBeginBibliography{\raggedright}

% %%%%%%%%%%%%%%%%%%%%%%%
% Changes in the position
% %%%%%%%%%%%%%%%%%%%%%%%

% Change the position of the year to be in front of the volume
\renewbibmacro*{journal+issuetitle}{%
    \usebibmacro{journal}%
    \usebibmacro{date}% Added the date, right after the journal
    \newcommaunit*%
    \iffieldundef{series}
    {}
    {%
        \newunit
        \printfield{series}%
        \setunit{\addcomma\space}%
    }%
    \usebibmacro{volume+number+pages+eid}%
    \newcommaunit
    % \setunit{\addspace}%
    \usebibmacro{issue+date-parens}%
    \setunit*{\addcolon\space}%
    \usebibmacro{issue}%
    \newunit%
}

% Remove the date after the volume
\renewbibmacro*{issue+date-parens}{%
    \iffieldundef{issue}%
    {%
        % \usebibmacro{date}
    }%
    {%
        \printfield{issue}%
        \newcommaunit*%
        % \usebibmacro{date}
    }%
    \newunit%
}

\endinput

A: As it turned out in the comments, the problem is actually a malformed urldate field as exported by Mendeley. All biblatex date fields must be written in YYYY-MM-DD format (ISO 8601/EDTF), DD.MM.YYYY is not acceptable input and generates a warning:

Invalid format '30.04.2018' of date field 'urldate' - ignoring

You should definitely contact the Mendeley developers about this.
In the meantime, here is a fix with Biber's sourcemapping
\documentclass[british]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage{csquotes}

\usepackage[style=authoryear, backend=biber]{biblatex}

\begin{filecontents}{\jobname.bib}
@misc{appleby,
  author  = {Humphrey Appleby},
  title   = {On the Importance of the Civil Service},
  date    = {1980},
  url     = {http://example.com/~sirhumphrey/cc.pdf},
  urldate = {30.04.2018},
}
\end{filecontents}

\addbibresource{\jobname.bib}
\addbibresource{biblatex-examples.bib}

\DeclareSourcemap{
  \maps[datatype=bibtex]{
    \map{
      \step[fieldsource=urldate, match=\regexp{\A(\d{2}).(\d{2}).(\d{4})\Z}, replace={$3-$2-$1}]
    }
  }
}

\begin{document}
\cite{sigfridsson,appleby}
\printbibliography
\end{document}

But don't just use it: Complain to the Mendeley people!


text:
Q: Asp.net profile in a separate assembly I have a web application which uses membership and profiles.  I successfully used the WebProfileBuilder extension, so my profile class is correctly generated, and is working nicely.
However, after a new request of my client, I need now to move that profile management part into another assembly (so I'd be able to get profile information in a windows service running on the same machine).
What I made is created the new assembly, moved my generated profile file, and tried to use it from the other assembly, but without any success.  I always get a SettingsPropertyNotFoundException.  My thought is that the profile system doesn't know where to find its connection information, so I tried to add the connectionstring and provider in the app.config of this assembly, but this doesn't seem to work.
What am I missing ?  Is it possible to do ?
Thanks in advance!

A: I've got a nasty suspicion that your APP.Config file won't be picked by the web application;  did you keep the settings in your Web.Config file ?
I've only found app.config to work on such an assemply when using NUnit or similar.

A: Ok I found what's wrong... Thanks to this blog post:
http://fredrik.nsquared2.com/viewpost.aspx?postid=244&showfeedback=true
The only thing I needed to do is add applicationName="/" in my provider configuration, in the app.config. (which is the application name, can be found inside the aspnet_Applications table in the DB.
<configuration>

  <connectionStrings>
    <add
        name="MyConnectionString"
        connectionString="Data Source=...;Initial Catalog=...;User ID=...;Password=..."
        providerName="System.Data.SqlClient" />
  </connectionStrings>

  <system.web>
    <profile
      enabled="true"
      defaultProvider="Sql2008ProfileProvider">
      <properties>
        <add name="UserLevel" type="integer"/>
        <add name="value1" type="string" />
        <add name="value2" type="string"  />
        <add name="value3" type="string" />
        <add name="value4" type="string"/>
      </properties>

      <providers>
        <clear/>
        <add
            name="Sql2008ProfileProvider"
            type="System.Web.Profile.SqlProfileProvider"
            connectionStringName="MyConnectionString"
            applicationName="/"
            />
      </providers>

    </profile>
  </system.web>

</configuration>


text:
Q: How do I optimize the OS for SSDs? What steps should be taken before/during/after installation of Ubuntu on a Solid State Drive to optimize performance and ensure maximum durability of the drive?

A: SSD Life
Generally I wouldn't bother - the worries about SSD life are overblown. You can read this detailed article about why you really shouldn't worry. In short the circuitry inside modern SSDs manages wear-levelling for you, and they know how to do it far better than you.
In the article is a calculation of the life of an SSD that is receiving writes at a continuous rate of 80M/s. The life is 51 years. That is based on 2007 technology - SSD life will be longer now. And you almost certainly don't write to your SSD at 80M/s 24 hours a day.
SSD Performance
However performance degradation over time can be a problem, and TRIM is the solution. There are two options

*

*automatic/online TRIM, aka discard

*manual TRIM

You have to enable automatic TRIM yourself . (Basically you add the discard option to your mount options, provided you are using ext4.) I have found a blog post reporting that the discard option slows down your system when deleting files.
You can occasionally do it manually (or in a cron job) using fstrim. If you just have one partition then all you need to do is:
sudo fstrim /

Note that fstrim is only available in 11.10 and newer. For older systems you will need the wiper.sh script. I found the script at /usr/share/doc/hdparm/contrib/wiper.sh.gz on my system.
If you're wondering, the problem that TRIM solves, as described by Wikipedia, is:

SSDs store data in flash memory cells that are grouped into pages, with the pages (typically 4 kB each) grouped together into blocks (typically 128 pages per block, totaling 512 kB). NAND flash memory cells can only be directly written to when they are empty. If they are considered to contain data, the contents first need to be erased before a write operation can be performed reliably. In SSDs, a write operation can be done on the page-level, but due to hardware limitations, erase commands always affect entire blocks. As a result, writing data to SSD media is very fast as long as empty pages can be used, but slows down considerably once previously written pages need to be overwritten. Since an erase of the cells in the page is needed before it can be written again, but only entire blocks can be erased, an overwrite will initiate a read-erase-modify-write cycle: the contents of the entire block have to be stored in cache before it is effectively erased on the flash medium, then the overwritten page is modified in the cache so the cached block is up to date, and only then is the entire block (with updated page) written to the flash medium. This phenomenon is known as write amplification.

A: 4) enable automatic TRIM
If your SSD supports it, you should also enable automatic TRIM (as described here)

A: UPS is required.In the /etc/sysctl.conf file
vm.dirty_writeback_centisecs = 15000
vm.swappiness = 10

Find the configuration file daemon, usually /etc/syslog.conf или /etc/rsyslog.d/ and all the paths of the form /var/log/ change by writing a minus sign ("-") in front of ways.Before
mail.err
/var/log/mail.err

After
mail.err -/var/log/mail.err
use FS btrfs and use the -o ssd option
More http://vasilisc.com/speedup_ubuntu_eng#speedup_fs

A: I would not add this line to your fstab, var/tmp folder is meant to survive reboots, and that could cause issues for you.
tmpfs /var/tmp tmpfs defaults,noatime,mode=1777 0 0

When I configure new system I leave all the tmp folder commented out this way if anything happens I can check the logs and stuff. Then once I have the main system setup I will un-comment them, but I never add the above line, here is what I use:
tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0
tmpfs /var/log tmpfs defaults,noatime,mode=0755 0 0
tmpfs /var/log/apt tmpfs defaults,noatime 0 0

And if I am having any issues with my system I comment those out to be able to check everything even after a reboot or forced reboot after a lockup.
Also you don't need nodiratime, noatime option takes care of both by itself.
As for TRIM, if your hw/sw support it, it's a must, I do not use discard in fstab. I create a daily cron, because my PC is always on, by doing this:
gksu gedit /etc/cron.daily/trim

Then add this to file and save (If you dont have a seperate /home partition on ssd, or have other parts that are on ssd you should get the idea how to modify this:
#!/bin/sh
LOG=/var/log/trim.log
echo "*** $(date -R) ***" >> $LOG
fstrim -v / >> $LOG
fstrim -v /home >> $LOG

Then make the file executable by:
sudo chmod +x /etc/cron.daily/trim

I also edit my rc.local like so:
gksu gedit /etc/rc.local

Add this above "exit 0" and below the last #:
# Modification for SSD
# you may want to add more folders to be checked/created to this list
for dir in apparmor apt ConsoleKit cups dist-upgrade fsck gdm installer news ntpstats samba speech-dispatcher unattended-upgrades; do
  if [ ! -e /var/log/$dir ] ; then
    mkdir /var/log/$dir
  fi
done

You can copy and paste from here so there is no errors, to the layman it looks out of whack, it is not.
I have also read that leaving 10% of your ssd drive unformatted can help extend life, that remains to be seen. I have not read that much into this so I can't vouch if it makes sense to do so.
This is the best all around guide, he did not skim around Google for a day and then come up with a guide, you should check it out HERE

A: TRIM allows an operating system to inform an SSD which blocks of data are no longer considered in use and can be wiped internally. Trimming enables the SSD to handle garbage collection overhead, which would otherwise significantly slow down future write operations to the involved blocks, in advance.1
In Ubuntu 14.04 a new feature has been added to the util-linux package that regularly trims SSDs automatically, but only Intel and Samsung SSDs have TRIM enabled by default, because some cheap SSDs can even brick themselves when running TRIM.2 The contents of /etc/cron.weekly/fstrim in Ubuntu 14.04:
#!/bin/sh
# call fstrim-all to trim all mounted file systems which support it
set -e

# This only runs on Intel and Samsung SSDs by default, as some SSDs with faulty
# firmware may encounter data loss problems when running fstrim under high I/O
# load (e. g.  https://launchpad.net/bugs/1259829). You can append the
# --no-model-check option here to disable the vendor check and run fstrim on
# all SSD drives.
exec fstrim-all

1https://en.wikipedia.org/wiki/Trim_%28computing%29
2How is Trim enabled?

A: There are several points:
Alignment:
What is often pointed out is the right alignment of the partition. This should be equal to the block size of the SSD. Play safe and make your partitions aligned to MiB boundaries. Note that you can't do this with the Ubuntu installer's partition tool (which uses MB not MiB), but you can boot the live CD, use Gparted (which uses MiB), then click Install to use the partitions you set up.
The right scheduler:
A important point is the scheduler wich should be noop. You can set this scheduler via kernelparameter elevator=noop or via a entry echo noop > /sys/block/sda/queue/scheduler in you rc.local.
Mountflags:
I would recommend noatime and discard
Tmpfs
To put tmp on  a ramdisk can increase the life time of the ssd.
To use this put the following line in you fstab: none            /tmp            tmpfs   defaults        0       0
Generally if you want to dive deeper into this topic I would recommend this excellent wiki-article.

A: Ok "long story short":

*

*Yes. It is like a normal hdd. Here is a good overview.

*Some special extras, that I will cover.

*Quite good. I use it with a server.

Format as ext4 during install, and create a small swap ~1 GB. After install edit fstab with sudo gedit /etc/fstab and add the following line
tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0

This will create a ramdrive for your temp files, which will lower the ageing. Also add noatime,nodiratime,discard to your ext4 line after defaults. This will also lower wear, and enable TRIM function. Save and reboot.

A: It is clear that /var/tmp should not be in tmpfs since by definition it's content needs to be preserved beyond reboots:

*

*Differences between TMP and VarTMP

A: There are some good info How to tweak and optimize SSD for Ubuntu, Linux Mint from http://namhuy.net/1563/how-to-tweak-and-optimize-ssd-for-ubuntu-linux-mint.html you might be interested in
Use preload
To install preload on Ubuntu, Linux Mint or debian based distributions
# apt-get update && apt-get install preload

Turn off your swap
To change swappiness setting:
$ su -
# nano /etc/sysctl.conf

And add this line into sysctl.conf file.
vm.swappiness = 10

A: Fast tuning course for your SSD on Ubuntu:
filesystem
Arch wiki mentions few preferable options for SSD file system - one of them is unstable, others are ext* ones. I assume ext4 is one of the best picks.
Note: In case of ext4 you may want to use discard mount option.
fstab
# <file system> <mount point> <type> <options>                                  <dump>  <pass>
proc            /proc         proc   nodev,noexec,nosuid                        0       0
tmpfs           /tmp          tmpfs  nodev,nosuid,noatime,mode=1777             0       0
/dev/sda1       /             ext4   defaults,noatime,discard,errors=remount-ro 0       1
/dev/sda2       /home         ext4   defaults,noatime,discard,user_xattr        0       2
/dev/sda3       /windows      ntfs   defaults,noatime,discard,umask=007,gid=46  0       0

Few important things here are:

*

*For systems with >=2 gigs of memory, locating /tmp in the RAM is desirable.

*No swap partition. Nowadays it's needed only for hibernation, since modern machines has pretty big amount of RAM.

*noatime and discard options. Info is here.

scheduler
Consider switching from the default scheduler, which under most Linux distro's is cfq (completely fair queuing), to the noop or deadline scheduler for an SSD. Using the noop scheduler, for example, simply processes requests in the order they are received, without giving any consideration to where the data physically resides on the disk. This option is thought to be advantageous for SSDs since seek times are identical for all sectors on the SSD.
Add following to /etc/rc.local:
# SSD performance tuning
echo noop > /sys/block/sda/queue/scheduler

info
one two

A: I have successfully used several different techniques to improve the way Ubuntu uses the storage device, whether that be solid state or traditional drive.
For SSD's you are looking to minimise the number of times the drive is written too, as reads should not add wear to the drive.
1) Manage the swap file
If you do not hibernate your computer and you have ample RAM memory to run all your applications, then in theory you do not need a swap partition.
If you have a mix of SSD and hard drives, place your swap partition on the hard drives only.
2) No Writes for Read Timestamps (suitable for SSD's and hard drives)
Mounting your partitions with the options noatime and nodiratime will stop timestamp writes when you read files and folders.  These timestamp writes are not generally required unless you use a local mail server client such as mutt. The reason this is generally a bad idea, is because every read will produce a write when updating the timestamps. This decreases the life of the SSD.
Edit your /etc/fstab configuration file (carefully - take a backup to be sure as breaking your fstab configuration can prevent you system from working):
cp /etc/fstab ~/fstab-backup
gksudo gedit /etc/fstab

Edit the mounting options for your partitions by adding the text noatime and nodiratime to the lines defining your root (/) and other partitions if you have them (/home) - Note: if you have a /home partition, start with that just changing that partition if you are concerned about breaking something
# / was on /dev/sda2 during installation
UUID=587e0dc5-2db1-4cd9-9792-a5459a7bcfd2 /               ext4    noatime,nodiratime,errors=remount-ro 0       1

# /home was on /dev/sda3 during installation
UUID=2c919dc4-24de-474f-8da0-14c7e1240ab8 /home           ext4    noatime,nodiratime,defaults        0       2

You will need to reboot your machine before these changes take effect
3) Minimising writes from the OS and applications
Assuming that you are not running a mission critical product server, most people do not look at logs should something go wrong (especially as serious errors are rare for most Ubuntu users).  Therefore you can configure Ubuntu so all logs get written to RAM memory rather than the SSD.
Note: only make the following changes when you have installed all software you are going to use (especially things like Apache web server), otherwise you may experience some issues with missing directories in /var/log
For background to this approach, see prolonging the life of your flash drive on ubuntu-eee.com
Open /etc/fstab with an editor (assuming you have backed up the /etc/fstab file)
gksudo gedit /etc/fstab

Add the following lines at the end of the fstab file and save:
# Uncomment these after all server based applications installed - eg. apache
#tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0
#tmpfs /var/tmp tmpfs defaults,noatime,mode=1777 0 0
#tmpfs /var/log tmpfs defaults,noatime,mode=0755 0 0
#tmpfs /var/log/apt tmpfs defaults,noatime 0 0
# none /var/cache unionfs dirs=/tmp:/var/cache=ro 0 0

You will need to reboot your machine before these changes take effect
See also:

*

*How to enable TRIM?

A: How to tweak and optimize SSD for Ubuntu, Linux Mint
Enable TRIM
TRIM (Trim command let an OS know which SSD blocks are not being used and can be cleared)
Back up fstab first in case something wrong happen.
# cp /etc/fstab ~/fstab.bk

Edit fstab file
# nano /etc/fstab

Add discard to your ssd drives or partitions, after ext4
UUID=bef10b86-494d-41c6-aa46-af72cfba90fd / ext4 discard,errors=remount-ro 0 1
Adding noatime and nodiratime

noatime and nodiratime are mount options in linux for linux file system. noatime disables atime updates on file system, and nodiratime will disables atime updates on directory system. By adding noatime and nodiratime will greatly reduce ssd load means performance gains.
Edit fstab file
# nano /etc/fstab

Add noatime,nodiratime to your ssd drives or partitions, after ext4
UUID=bef10b86-494d-41c6-aa46-af72cfba90fd / ext4 discard,noatime,nodiratime,errors=remount-ro 0 1

A: I suggest to place only those things which are read at boot time on the SSD any maybe applications which require much time to load.Data and logs and other uncritical things I would locate on a normal HDD.Also you could setup your ubuntu to only load a big initramfs from SSD at boot time and not write back changes to ssd.This has the benefit, that changes to this partition are not persistent which is sth like a protection for your boot system.Therefor you would need much more RAM of course.
I would e.g. place the partitions
/, /etc, /usr, /boot, /lib 32/64 on SSD while sth like
/opt, /bin, /sbin, /root, /home and even swap (increase RAM!!!) on HDD
Wikipedia says:

The Linux kernel supports the TRIM function starting with version 2.6.33. The ext4 file system is supported when mounted using the "discard" parameter. The most recent disk utilities (and therefore installation software that make use of them) also apply proper partition alignment.

For backups there are many ways, simplest of which is (r)sync plus cron job.


text:
Q: How many users can be in a AD LDS group? Microsoft published the recommended maximum limits for users in an Active Directory group. It basically says :

Starting with Windows Server 2003, the ability to replicate discrete changes to linked multivalued properties was introduced as a technology called Linked Value Replication (LVR).

and

This allows the number of group memberships to exceed the former recommended limit of 5,000 for Windows 2000 or Windows Server 2003 at a forest functional level of Windows 2000.

Given the replication meta data below, can anybody tell me what is the maximum number of users a AD-LDS group can hold ?
Getting 'CN=Member,CN=Schema,CN=Configuration,CN={67B333FE-ADB4-430D-AAEE-D4CCE4B98A2E}' metadata...
23 entries.
 AttID     Ver   Loc.USN                      Originating DSA            Org.USN         Org.Time/Date
 =====     ===   =======                      ===============        =======         =============
     0       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
     3       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 20001       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 20002       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 2001e       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 20020       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 20021       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 20032       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 200a9       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 200c2       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 200da       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 200e2       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 200e7       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 20119       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 2014e       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 201cc       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 90001       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 90094       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 90095       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 900aa       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 90177       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 9027f       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49
 9030e       1        95    8ba30efb-9aa4-4e55-8f7c-268e3dcc536b          95    2012-07-17 14:25:49

A: I did not find a valid, clear answer, so wrote some code to create 1 milion users, and add them to a single group.
On a 1vCPU, 2G RAM virtual machine running Windows Server 2008 R2, we found that :

*

*AD-LDS has no problem holding that much data.

*Adding a user to the directory or to the group is done in constant time, regardless of group membership size

*ADSIEdit has a hard time listing users when the count goes over 5k. It works but the mmc.exe process consume a lot of CPU time and the whole thing slows to a crawl

*LDP virtual list view works, but you have to tell it what you are looking for. Listing all values is too slow to work

*Apache Directory Studio was stable and fast, with good support for paging.


text:
Q: Parsing to Free Monads Say I have the following free monad:
data ExampleF a
  = Foo Int a
  | Bar String (Int -> a)
  deriving Functor

type Example = Free ExampleF  -- this is the free monad want to discuss

I know how I  can work with this monad, eg. I could write some nice helpers:
foo :: Int -> Example ()
foo i = liftF $ Foo i ()

bar :: String -> Example Int
bar s = liftF $ Bar s id

So I can write programs in haskell like:
fooThenBar :: Example Int
fooThenBar =
  do
    foo 10
    bar "nice"

I know how to print it, interpret it, etc. But what about parsing it?
Would it be possible to write a parser that could parse arbitrary
programs like:
foo 12
bar nice
foo 11
foo 42

So I can store them, serialize them, use them in cli programs etc.
The problem I keep running into is that the type of the program depends on which program is being parsed. If the program ends with a foo it's of
type Example () if it ends with a bar it's of type Example Int.
I do not feel like writing parsers for every possible permutation (it's simple here because there are only two possibilities, but imagine we add
Baz Int (String -> a), Doo (Int -> a), Moz Int a, Foz String a, .... This get's tedious and error-prone).
Perhaps I'm solving the wrong problem?
Boilerplate
To run the above examples, you need to add this to the beginning of the file:
{-# LANGUAGE DeriveFunctor #-}

import Control.Monad.Free
import Text.ParserCombinators.Parsec

Note: I put up a gist containing this code.

A: Not every Example value can be represented on the page without reimplementing some portion of Haskell. For example, return putStrLn has a type of Example (String -> IO ()), but I don't think it makes sense to attempt to parse that sort of Example value out of a file.
So let's restrict ourselves to parsing the examples you've given, which consist only of calls to foo and bar sequenced with >> (that is, no variable bindings and no arbitrary computations)*. The Backus-Naur form for our grammar looks approximately like this:
<program> ::= "" | <expr> "\n" <program>
<expr> ::= "foo " <integer> | "bar " <string>

It's straightforward enough to parse our two types of expression...
type Parser = Parsec String ()

int :: Parser Int
int = fmap read (many1 digit)

parseFoo :: Parser (Example ())
parseFoo = string "foo " *> fmap foo int

parseBar :: Parser (Example Int)
parseBar = string "bar " *> fmap bar (many1 alphaNum)

... but how can we give a type to the composition of these two parsers?
parseExpr :: Parser (Example ???)
parseExpr = parseFoo <|> parseBar

parseFoo and parseBar have different types, so we can't compose them with <|> :: Alternative f => f a -> f a -> f a. Moreover, there's no way to know ahead of time which type the program we're given will be: as you point out, the type of the parsed program depends on the value of the input string. "Types depending on values" is called dependent types; Haskell doesn't feature a proper dependent type system, but it comes close enough for us to have a stab at making this example work.

Let's start by forcing the expressions on either side of <|> to have the same type. This involves erasing Example's type parameter using existential quantification.†
data Ex a = forall i. Wrap (a i)

parseExpr :: Parser (Ex Example)
parseExpr = fmap Wrap parseFoo <|> fmap Wrap parseBar

This typechecks, but the parser now returns an Example containing a value of an unknown type. A value of unknown type is of course useless - but we do know something about Example's parameter: it must be either () or Int because those are the return types of parseFoo and parseBar. Programming is about getting knowledge out of your brain and onto the page, so we're going to wrap up the Example value with a bit of GADT evidence which, when unwrapped, will tell you whether a was Int or ().
data Ty a where
    IntTy :: Ty Int
    UnitTy :: Ty ()

data (a :*: b) i = a i :&: b i

type Sig a b = Ex (a :*: b)
pattern Sig x y = Wrap (x :&: y)

parseExpr :: Parser (Sig Ty Example)
parseExpr = fmap (\x -> Sig UnitTy x) parseFoo <|>
            fmap (\x -> Sig IntTy x) parseBar

Ty is (something like) a runtime "singleton" representative of Example's type parameter. When you pattern match on IntTy, you learn that a ~ Int; when you pattern match on UnitTy you learn that a ~ (). (Information can be made to flow the other way, from types to values, using classes.) :*:, the functor product, pairs up two type constructors ensuring that their parameters are equal; thus, pattern matching on the Ty tells you about its accompanying Example.
Sig is therefore called a dependent pair or sigma type - the type of the second component of the pair depends on the value of the first. This is a common technique: when you erase a type parameter by existential quantification, it usually pays to make it recoverable by bundling up a runtime representative of that parameter.
Note that this use of Sig is equivalent to Either (Example Int) (Example ()) - a sigma type is a sum, after all - but this version scales better when you're summing over a large (or possibly infinite) set.
Now it's easy to build our expression parser into a program parser. We just have to repeatedly apply the expression parser, and then manipulate the dependent pairs in the list.
parseProgram :: Parser (Sig Ty Example)
parseProgram = fmap (foldr1 combine) $ parseExpr `sepBy1` (char '\n')
    where combine (Sig _ val) (Sig ty acc) = Sig ty (val >> acc)

The code I've shown you is not exemplary. It doesn't separate the concerns of parsing and typechecking. In production code I would modularise this design by first parsing the data into an untyped syntax tree - a separate data type which doesn't enforce the typing invariant - then transform that into a typed version by type-checking it. The dependent pair technique would still be necessary to give a type to the output of the type-checker, but it wouldn't be tangled up in the parser.
*If binding is not a requirement, have you thought about using a free applicative to represent your data?
†Ex and :*: are reusable bits of machinery which I lifted from the Hasochism paper

A: So, I worry that this is the same sort of premature abstraction that you see in object-oriented languages, getting in the way of things. For example, I am not 100% sure that you are using the structure of the free monad -- your helpers for example simply seem to use id and () in a rather boring way, in fact I'm not sure if your Int -> x is ever anything other than either Pure :: Int -> Free ExampleF Int or const (something :: Free ExampleF Int).
The free monad for a functor F can basically be described as a tree whose data is stored in leaves and whose branching factor is controlled by the recursion in each constructor of the functor F. So for example Free Identity has no branching, hence only one leaf, and thus has the same structure as the monad:
data MonoidalFree m x = MF m x deriving (Functor)
instance Monoid m => Monad (MonoidalFree m) where
    return x = MF mempty x
    MF m x >>= my_x = case my_x x of MF n y -> MF (mappend m n) y

In fact Free Identity is isomorphic to MonoidalFree (Sum Integer), the difference is just that instead of MF (Sum 3) "Hello" you see Free . Identity . Free . Identity . Free . Identity $ Pure "Hello" as the means of tracking this integer. On the other hand if you have data E x = L x | R x deriving (Functor) then you get a sort of "path" of Ls and Rs before you hit this one leaf, Free E is going to be isomorphic to MonoidalFree [Bool].
The reason I'm going through this is that when you combine Free with an Integer -> x functor, you get an infinitely branching tree, and when I'm looking through your code to figure out how you're actually using this tree, all I see is that you use the id function with it. As far as I can tell, that restricts the recursion to either have the form Free (Bar "string" Pure) or else Free (Bar "string" (const subExpression)), in which case the system would seem to reduce completely to the MonoidalFree [Either Int String] monad.
(At this point I should pause to ask: Is that correct as far as you know? Was this what was intended?)
Anyway. Aside from my problems with your premature abstraction, the specific problem that you're citing with your monad (you can't tell the difference between () and Int has a bunch of really complicated solutions, but one really easy one. The really easy solution is to yield a value of type Example (Either () Int) and if you have a () you can fmap Left onto it and if you have an Int you can fmap Right onto it.
Without a much better understanding of how you're using this thing over TCP/IP we can't recommend a better structure for you than the generic free monads that you seem to be finding -- in particular we'd need to know how you're planning on using the infinite-branching of Int -> x options in practice.


text:
Q: JPA 2 Many-To-One with Formula Derived Foreign Key Migrating an application from Hibernate 3, trying to map this relation in JPA 2 and not sure how it's handled.  In the original application there are these two objects:
TemplateCourse.java
CourseCatCode.java
The TemplateCourse has a many-to-one reference to CourseCatCode.  There is no foreign key in TemplateCourse, instead a formula is used to select an ID from a 3rd table based on some criteria, and the corresponding CourseCatCode is joined.
In the hibernate 3 application, the mapping looks like this:
    <many-to-one name="courseCatCode" class="CourseCatCode" not-null="false" insert="false" update="false" lazy="false">
        <formula><![CDATA[
            (
                select
                    smdp_asbch_course.cat_code_id
                from
                    smdp_asbch_course smdp_asbch_course,
                    smdp_template_requirement smdp_template_requirement,
                    smdp_template smdp_template,
                    smdp_degree smdp_degree
                where
                    smdp_degree.degree_id = smdp_template.degree_id
                    and smdp_template.template_id = smdp_template_requirement.template_id
                    and smdp_template_requirement.requirement_id = requirement_id
                    and smdp_asbch_course.school_id = smdp_degree.school_id
                    and smdp_degree.degree_type_code = smdp_asbch_course.degree_type_code
                    and smdp_asbch_course.before_date > SYSDATE
                    and translate(upper(smdp_asbch_course.course_number), 'A-/ ', 'A') = translate(upper(course_number), 'A-/ ', 'A')
            )
        ]]></formula>
    </many-to-one>

Can we do something similar in JPA 2 to map this relation?  Our JPA 2 provider is also Hibernate, so if it requires something hibernate specific that is okay.

A: Have you tried
@JoinFormula(referencedColumnName="cat_code_id", value="(select smdp_asbch_course.cat_code_id " +
                                                       "from smdp_asbch_course " +                                                            smdp_asbch_course, " +
                                                       "smdp_template_requirement smdp_template_requirement, " +
                                                       "smdp_template " +
                                                       "smdp_template, " +
                                                       "smdp_degree smdp_degree " +
                                                       "where smdp_degree.degree_id = smdp_template.degree_id " +
                                                       "  and smdp_template.template_id = smdp_template_requirement.template_id " +
                                                       "  and smdp_template_requirement.requirement_id = requirement_id " +
                                                       "  and smdp_asbch_course.school_id = smdp_degree.school_id " +
                                                       "  and smdp_degree.degree_type_code = smdp_asbch_course.degree_type_code " +
                                                       "  and smdp_asbch_course.before_date > SYSDATE " +
                                                       "  and translate(upper(smdp_asbch_course.course_number), 'A-/ ', 'A') = translate(upper(course_number), 'A-/ ', 'A'))")