text:
Q: (Unix/Linux) How would I execute a C program from another C program that requires an input file?
In the picture above, the code can simply be run from the terminal. pipeclient and pipeserver files are run. pipeclient file takes command.txt as an input using the < symbol.
Now, if I don't want to run the pipeclient file from the terminal, but want to run from a C program, how would I go about it? Will the exec set of functions help me? How would I run the pipeclient file with the command.txt input file from a C program ?

A: The low-level way to run a program with input taken from a file is to:

*

*open the file for reading using open

*use the dup2 system call to duplicate the open file handle over top of the handle for standard input (always handle 0)

*close the old handle (the copy duplicated on top of handle 0 will stay open)

*use execve or another function from the exec family to switch to the new program, which will now have its standard input opened to the file.

This is the same way the shell itself implements the < file input redirection.
Here's an example that runs /usr/bin/rev using input from a commands.txt file in the current directory:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

extern char **environ;

#define ERROR(msg) do { perror(msg); exit(1); } while(0)

int main()
{
    // open the input file
    int fd = open("commands.txt", O_RDONLY);
    if (fd == -1)
        ERROR("open");

    // "dup" the handle to standard input (handle 0)
    if (dup2(fd, 0) == -1)
        ERROR("dup2");

    // close the old handle
    close(fd);

    // exec the program
    char *args[] = {"rev", NULL};
    execve("/usr/bin/rev", args, environ);

    // the program never gets here, unless the exec fails
    ERROR("execve");
    return -1;
}

You can also use the system command which executes a shell command including redirection, so the program:
#include <stdio.h>
#include <stdlib.h>

#define ERROR(msg) do { perror(msg); exit(1); } while(0)

int main()
{
    if (system("/usr/bin/rev <commands.txt"))
        ERROR("system");

    // this *will* return after completion
    return 0;
}

will work as well.  Here, the system call is actually invoking a copy of a shell ("/bin/sh") to process the command line as if it was a shell command.
This is more convenient, but you have less control over the process of invoking the child program (e.g., setting up its environment, cleaning its argument list, etc.).  There are also complex potential security issues with using system that can be a problem if your program will run as root, though that may not be an issue here.

A: you can use system function to call your 2nd program for 1st c program.like
1st.c
#include <stdio.h>
#include<ctype.h>
#include <stdlib.h>
int main()
{
    printf("I m 1st program");
    system("./2nd.out\n");
}

2nd.c
#include <stdio.h>
#include<ctype.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
        printf("Hello there i m 2nd program\n")

}


text:
Q: how to use a toast library with html I'm using a toast library called js-snackbar with django templates, after a call is being made to the messages, I get Snackbar is not defined on console, am I missing something?
{% if messages %}
    {% for message in messages %}
        {% if message.tags == 'success'%}
            <script>
                new Snackbar({
                    message: "{{ message }}",
                    status: "success",
                    position: "bl"
                });
            </script>
        {% elif message.tags == 'info' %}
            <script>
                new Snackbar({
                    message: "{{ message }}",
                    status: "info",
                    position: "bl"
                });
            </script>
        {% endif %}
    {% endfor %}
{% endif %}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to delay jquery animation? I can't seem to delay the showing of a div. I want to delay the animation by about 20 seconds is this possible???
$("#microcharcounter").delay(10000).show();

A: Try this:
$("#microcharcounter").delay(10000).show(0);

or this:
$("#microcharcounter").delay(10000).queue(function(n) {
    $(this).show();
    n();
});

The reason for this is that .delay() will only delay items in an animation queue. So you can make .show() a short animation by adding a duration of '0', or add it to the queue with .queue().

A: You can do it like this:
setTimeout(function() {
  $("#microcharcounter").show();
}, 20000);

The problem with .delay() and .show() (without a duration), is that .show() isn't an animation, it's an immediate effect that's not on the fx queue at all.  You could however give it a duration, like this:
$("#microcharcounter").delay(20000).show("fast");


text:
Q: Проблема в регулярном выражение Не могу сделать так, чтобы работало. Вот простое выражение:
var re = new RegExp('\[img*\]abcde\[/img\]','gim');
alert(re.test('[img=600x399]abcde[/img]'));

Пишет false. Jsfiddle. Что нужно исправить?
A: var re = /\[img=.*?\]abcde\[\/img\]/gim;
alert(re.test('[img=600x399]abcde[/img]'));

var re = new RegExp("\\[img=.*?\\]abcde\\[\\/img\\]", "gim");
alert(re.test('[img=600x399]abcde[/img]'));

JsFiddle, JsFiddle 2


text:
Q: Updating a manually installed Rocket.Chat instance Documentation on updating Rocket.Chat (found here) only says:

Usually you can upgrade Rocket.Chat without much effort,
There might be some major changes when we introduce big new features or modifications, you can always take a look on the releases page to see what has been changed, broken or added to Rocket.Chat.

My question: Does anyone have experience in updating/upgrading a manually installed Rocket.Chat deployment & what did you do other than redeploy latest code?
Here is the procedure for a manual install on Ubuntu, we're using 16.04 LTS.
At the moment we're on 0.58.2 & I want to update to 0.62.0 (latest), however there's no indications on how to update the database, and the only way to update the code I've seen is to download it & deploy it as a new install on the same server. Will the code handle MongoDB migration to latest?
All I've found so far are dev questions and implementations not directly related to this type of installation of Rocket.Chat, and would love to craft a procedure to update in the future, if it's not so simple as just redeploying on top of an existing installation. I will update this with information as it comes in, and if I find a solution in the meantime I will also come back and update for anyone looking to google for an answer in the future.
Thanks

A: You are asking a lot of varying questions here.
Upgrading between versions of Rocket.Chat typically the only factor is the nodejs version.  In your case definitely make sure you upgrade to node.js 8.x
Database migrations are handled in the Rocket.Chat code base.
Also if MariaDB is involved in your installation.  It's not being used by Rocket.Chat(or if so please share the code ;) ) because Rocket.Chat uses MongoDB.


text:
Q: Reindex a group of products programmatically I'd like to know if it's possible to re-index not all product data, but just a group of them, based on their id. Something like this:
foreach($collection as $product){
     reindexSingleProduct($product->getID());
}


text:
Q: Error: 'sh: c:/Rtools/mingw_32/bin/gcc: No such file or directory', while it does exists When I run
    R CMD INSTALL CopulaModule

in the correct folder I get the following error
#sh: c:/Rtools/mingw_32/bin/gcc: No such file or directory

But this specific location does exists. What can be the problem? I installed RTools corresponding to my version of R (3.5.0).


text:
Q: ERROR! Converting Keras model to Tensorflow lite I have a simple classification model built with feature columns. I want to convert it to Tensorflow lite format. I'm using the Keras conversion code. But it gives the following error;
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

# Save the model.
with open('model.tflite', 'wb') as f:
  f.write(tflite_model)

error message;
InvalidArgumentError: Cannot convert a Tensor of dtype resource to a NumPy array.
Why am I getting this error message?
Thank you.


text:
Q: Extending dynamic and mapped data in Knockout Using Knockout.JS, I'm trying to determine how to best extend objects in the view model when they will be both loaded via the mapping plugin and dynamically added. In this example, I'm adding a method addChild to the Person object.
Extending during mapping:
    var myPersonModel = function (data) {
        ko.mapping.fromJS(data, {}, this);

        this.addChild = function () {
            this.children.push(new Child());
        } .bind(this);
    }

    var mapping = {
        'people': {
            create: function (options) {
                return new myPersonModel(options.data);
            },
        }
    }

    var viewModel = ko.mapping.fromJS(data, mapping);

Extending during dynamic creation:
    function Person(id, name, children) {
        this.id = ko.observable(id);
        this.name = ko.observable(name);
        this.children = ko.observable(children);
        this.addChild = function () {
            this.Forms.push(new Child());
        } .bind(this);
    }

But it seems to me there must be an easier way to do so such that I don't need to repeat myself, and both mapped and new objects get the addChild method.

A: Take a look at this answer, especially the live example on JSFiddle.
It looks like your code is close to what it needs to be.
I think you just need to fold mapping and ko.mapping.fromJS into your Person constructor.


text:
Q: How can I use Conga plugin outside Salesforce? I would like to prepare the REST request to conga API page similar to this one:
https://conductor.appextremes.com/apps/Conga/Conductor/LaunchCC.aspx?sessionId={!$Api.Session_ID}&serverUrl={!$Api.Partner_Server_URL_160}&ReportId={!someReportId}&QueryId={!someQueryId}
But my wish is to prepare this request outside the Salesforce application. So I can't use these two application parameters like they are used in documentation:

*

*$Api.Session_ID

*$Api.Partner_Server_URL_160
Because I'm using enterprise Salesforce connector library I must some how find these two parameters in the enterprise API.
Can anyone help me to find those parameters in the enterprise API?
The Session_ID I think is here: enterpriseConnection.getSessionHeader().getSessionId() but I'm not sure if I can use this one. To Partner_Server_URL_160 I have no idea where can I find this.
It will be also good if someone will paste the final REST query, because I have no idea how these parameters should looks like.

A: The $Api documentation defines $Api.Partner_Server_URL__xxx as:

*

*{!$Api.Partner_Server_URL__xxx}: The Partner WSDL SOAP endpoint where xxx represents the version of the API. {!$Api.Partner_Server_URL_250} is the expression for the endpoint for version 25.0 of the API.

So $Api.Partner_Server_URL_160 is the version 16.0 URL for the Partner API, which will be something like: https://na1.salesforce.com/services/Soap/u/16.0/00DE0000000ABCD - note the instance hostname at the start, /u/ in the path, indicating the Partner API, and the org ID at the end. It looks like you're on a sandbox, so your instance hostname will be something like cs9.salesforce.com.
Going by your comments, you're using version 29.0 of the Enterprise API, so, after you set up a ConnectorConfig and create an EnterpriseConnection with it, config.getServiceEndpoint() will return something like https://cs9.salesforce.com/services/Soap/c/29.0/00DE0000000ABCD. You can simply replace the /c/ and /29.0/ to get a version 16.0 Partner URL thus:
String partnerServerUrl160 = config.getServiceEndpoint().replace("/c/", "/u/").replace("/29.0/", "/16.0/");


text:
Q: jQuery AJAX success callback not firing in IE I'm pretty new to javascript and I have been searching around for a solution to this problem all day. I found many questions/answers but nothing has worked.
I have a page that has a file upload in it, I would like to run this file through a server-side validation routine and then display the validation result on the page. I have this working great in everything but IE (Safari, Chrome & Chromium, Firefox).
In order to make the file upload work on IE, the user needs to submit the form via a submit button. So I use a conditional comment in HTML to add it onto the page. In javascript I use an IE-detection function I found here. This part works fine.
Here is the function that makes the ajax request:
function handleUpload()
{
    showSpinner();

    var dFile = new FormData(document.getElementById("devConsValidate")); // this works in IE but only if called by a submit method

    $.ajax(
    {
        cache: false,
        async: false,
        url: 'validator.php',
        type: 'POST',
        data: dFile,
        dataType: 'JSON',

        processData: false, // this is key for formdata
        contentType: false, // so is this

        success: function(response)
        {
            var result = response.result;
            var validationCode = response.validation_code;
            var errors = response.errors;

            var htmlCode = '
';

            if (result == 'SUCCESS')
                htmlCode += '';
            else
            {
                htmlCode += '';
            }

            htmlCode += 'Validation ' + result + '
';

            if (result == "FAIL")
            {
                htmlCode += '';
                for (var i in errors)
                    htmlCode += errors[i] + '
';

                htmlCode += '
Validator Help    ';
            }
            else
            {
                htmlCode += 'Please use the following code when submitting your request.

' + validationCode + '';
            }

            // make some beautiful html
            $('#resultsArea').html(htmlCode);
        },

        error: function (XMLHttpRequest, textStatus, errorThrown)
        {
            alert('error: ' + errorThrown);
        }
    });
}

the function handleUpload() is called either on the file change event or on the form being submitted. validator.php returns a json_encoded array of values.
The issue is when using IE, the ajax success callback is never fired and the browser just displays a raw JSON string on a blank page, so the ajax call is working and returning expected data. On other browsers, the success callback fires and the json is parsed and the appropriate code is inserted into a div on the page.
Full javascript file: http://pastebin.com/G9MYBis5
Any ideas?

A: OK, so the solution for me was to make this line the first line in my head tag:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

This got IE10 working, for IE9 and below I just had to make static pages since I am able to upload the file without FormData and just get at it from a basic html form submission instead of AJAX. For this I added submit buttons using conditional comments for IE users.


text:
Q: Apache Netbeans changing default delimiter Despite having changed the pcs regional delimiter to a "." Netbeans 12 is still using a ",". I have tried adding the following to the netbeans.conf file but it has no effect:
-J-Duser.language=en -J-Duser.country=US
How do you force netbeans to use a particular local via the conf file?

A: I had changed the delimiter on win 10 but not the entire format for the pc. By changing the whole format to English UK, Netbeans honours the change.


text:
Q: How to retrieve value in javascript I am returning a json as shown below,
{
    "entities": {
        "permissions": {
            "77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
                "id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
                "role": "ADMIN",
                "permissions": null,
                "canAccessAllAccounts": true,
                "allowedAccounts": null,
                "createdAt": "2022-01-30T18:20:46.901Z",
                "updatedAt": "2022-01-30T18:20:46.901Z",
                "deletedAt": null
            }
        },
        "users": {
            "9bba4c96-781b-4012-9a48-071c1cb5ec24": {
                "id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
                "username": "246e6555eb16e3c8@ator.com",
                "activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
                "enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
                "permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
                "firstName": "a48d1eb7270bb404",
                "lastName": "e0aaa6d09e19",
                "avatarUrl": null,
                "sendBookingRequestEmail": true,
                "isSSO": false,
                "createdAt": "2022-01-30T18:20:46.999Z",
                "updatedAt": "2022-01-30T18:20:46.999Z",
                "deletedAt": null,
                "permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
            }
        }
    },
    "result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}

I am trying to get permissionsid value (it is occurred three places in the JSON), also forgot to mention in the original comment that these alphnumeric values in permissionid and userid are dynamics
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser['permissionId'];

When I am using the following, I am getting Cannot read properties of undefined (reading 'id')
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0].id;

When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0];

When I am using the following, I am getting [object%20Object]
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions;

What I am missing here, couldn't find same kind of question

A: Why stringify and parse?
Anyway, it is more complex than you think

const obj = JSON.parse(str)

console.log(Object.values(obj.entities.users)[0].permissionId)
<script>
const str = `{
    "entities": {
        "permissions": {
            "77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
                "id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
                "role": "ADMIN",
                "permissions": null,
                "canAccessAllAccounts": true,
                "allowedAccounts": null,
                "createdAt": "2022-01-30T18:20:46.901Z",
                "updatedAt": "2022-01-30T18:20:46.901Z",
                "deletedAt": null
            }
        },
        "users": {
            "9bba4c96-781b-4012-9a48-071c1cb5ec24": {
                "id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
                "username": "246e6555eb16e3c8@ator.com",
                "activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
                "enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
                "permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
                "firstName": "a48d1eb7270bb404",
                "lastName": "e0aaa6d09e19",
                "avatarUrl": null,
                "sendBookingRequestEmail": true,
                "isSSO": false,
                "createdAt": "2022-01-30T18:20:46.999Z",
                "updatedAt": "2022-01-30T18:20:46.999Z",
                "deletedAt": null,
                "permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
            }
        }
    },
    "result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}`</script>

A: I see only 2 places, but in any cases remove this from your code
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);

since your response data is parced already automatically
Since you can have several permissions or users , you can not get your data just using [0] or [1] since you don' t know how many users can be in the response. So try this code ( it was tested and working properly)
var permissionIds=[];
 Object.values(response.entities.permissions).forEach(element => {
   permissionIds.push(element.id)
 });

var userIds=[];
 Object.values(response.entities.users).forEach(element => {
   userIds.push(element.id)
 });


text:
Q: CSS Multiple Animations on single element, no javascript I am trying to create an image slideshow using only CSS and no Javascript.
I have an ALMOST working example here: http://codepen.io/k/pen/Dkhei .
The problem is that the animation for the 'Previous' functionality won't pause when I stop hovering over its element.
I am defining two animations on a single element, whose class name is 'imageContainer'. I am curious to know whether my syntax is wrong or if what I am trying to do is not possible.
HTML:

Previous

Next

CSS:
.carouselContainer{
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  border: 1px solid grey;
  width: 450px;
  height: 300px;
  position: relative;
  background-color: grey;
  margin: auto;
  overflow: hidden;
}

.directionSelector{
  width: 60px;
  height: 1.5em;
  line-height: 1.5em;
  top: 150px !important;
  position: absolute;
  cursor: pointer;
  background-color: rgba(1,1,1,.7);
  color: white;
  text-align: center;
  border-radius: 5px;
}
.previous{
  top: 0;
  left: 5px;
}
.next{
  top: 0;
  right: 5px;
}
img{
  width: 100%;
  height: 300px;
  float: left;
}
.imagesContainer{
  width: 100%;
  background-color: yellow;
  -webkit-animation-name: showImagesPrev,showImagesNext;
  -webkit-animation-duration: 5s,5s;
  -webkit-animation-play-state: paused,paused;
  -webkit-animation-fill-mode: forwards,forwards;

  -moz-animation-name: showImagesPrev,showImagesNext;
  -moz-animation-duration: 5s,5s;
  -moz-animation-play-state: paused,paused;
  -moz-animation-fill-mode: forwards,backwards;

  animation-name: showImagesPrev,showImagesNext;
  animation-duration: 5s,5s;
  animation-play-state: paused,paused;
  animation-fill-mode: forwards,backwards;

}
.previous:hover ~ div.imagesContainer{
  -webkit-animation-name: showImagesPrev;
  -webkit-animation-play-state: running;

  -moz-animation-name: showImagesPrev;
  -moz-animation-play-state: running;

  animation-name: showImagesPrev;
  animation-play-state: running;
}
.next:hover ~ div.imagesContainer{
  -webkit-animation-name: showImagesNext;
  -webkit-animation-play-state: running;

  -moz-animation-name: showImagesNext;
  -moz-animation-play-state: running;

  animation-name: showImagesNext;
  animation-play-state: running;
}
@-webkit-keyframes showImagesPrev{
  from{
    margin-top: 0px;
  }
  to{
    margin-top: -1200px;
  }
}
@-moz-keyframes showImagesPrev{
  from{
    margin-top: 0px;
  }
  to{
    margin-top: -1200px;
  }
}
@keyframes showImagesPrev{
  from{
    margin-top: 0px;
  }
  to{
    margin-top: -1200px;
  }
}
@-webkit-keyframes showImagesNext{
  from{
    margin-top: -1200px;
  }
  to{
    margin-top: 0px;
  }
}
@-moz-keyframes showImagesNext{
  from{
    margin-top: -1200px;
  }
  to{
    margin-top: 0px;
  }
}
@keyframes showImagesNext{
  from{
    margin-top: -1200px;
  }
  to{
    margin-top: 0px;
  }
}

Thank you for your help :)

A: As per W3C animation-name property Link

If multiple animations are attempting to modify the same property, then the animation closest to the end of the list of names wins.

In your example showImagesPrev is referred first and showImagesNext was the last one, so it worked correctly as per W3C. If you interchange these two reference, Previous will work fine, while Next button reproduce the issue. A working Example


text:
Q: How to Store Audio into buffer and then reading it byte by byte I can make wav file by MediaRecord of android ...but I am interested to put the audio data in a buffer and read it byte by byte...I have to send audio chunks byte wise over TCP channel....Can any one help me please...thanks in advance,
szaman from austria

A: You can use AudioRecord to read the audio data byte by byte, here is some sample code.
// calculate the minimum buffer
int minBuffer = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);

// initialise audio recorder and start recording
AudioRecord mRec = new AudioRecord(AUDIO_SOURCE, SAMPLE_RATE,
                CHANNEL_CONFIG, AUDIO_FORMAT,
                minBuffer);
mRec.startRecording();
byte[] pktBuf = new byte[pktSizeByte];
boolean ok;
// now you can start reading the bytes from the AudioRecord
while (!finished) {
    // fill the pktBuf
    readFully(pktBuf, 0, pktBuf.length);
    // make a copy
    byte[] pkt = Arrays.copyOf(pktBuf, pktBuf.length);
    // do anything with the byte[] ...
}

Since a single call to read() might not get enough data to fill the byte[] pktBuf, we might need to read multiple times to fill the buffer. In this case, I use an auxiliary function "readFully" to ensure the buffer is filled. Depending what you want to do with your code, different strategy can be used...
/* fill the byte[] with recorded audio data */
private void readFully(byte[] data, int off, int length) {
    int read;
    while (length > 0) {
        read = mRec.read(data, off, length);
        length -= read;
        off += read;
    }
}

Remember to call mRec.stop() to stop the AudioRecorder after finished. Hope that helps.


text:
Q: how to manage 'TabBarView' in flutter? I tried to make TabBarView in TabBar, but When I put the code below, It became white screen totally and there's nothing  and not specific error.. How Çan I solve it? please advice me and appreciate it.

class Buttons extends StatefulWidget  {
  const Buttons({Key? key}) : super(key: key);

  @override
  State<Buttons> createState() => _ButtonsState();
}

class _ButtonsState extends State<Buttons> with TickerProviderStateMixin {   //  다중 AnimationController를 사용할 때..???
  @override
  Widget build(BuildContext context)  {
    TabController _tabController   = TabController(length: 3, vsync: this);

    return Container(
      child: Column(
      children: [
        Container(
          child: TabBar(
          controller: _tabController,
          tabs: [
            Tab(icon: ClipRRect(child: Text("Shop"),),),
            Tab(icon: ClipRRect(child: Text("Donate"),),),
            Tab(icon: ClipRRect(child: Text("BId"),),)
          ],
      ),
        ),
         Container(
         // width: double.maxFinite,
         height: 300,
         child: TabBarView(
          controller: _tabController,
          children: [
            ShopPage(),
            DonatePage(),
            BidPage()
          ],
        )
         )
      ])
    );
  }
}

In children, Each pages are in other file and I imported those.

A: I have checked your code there are some corrections in it I have made it so please try the below code. I have checked with the below code and it works well.
class Buttons extends StatefulWidget  {
  const Buttons({Key? key}) : super(key: key);

  @override
  State<Buttons> createState() => _ButtonsState();
}

class _ButtonsState extends State<Buttons> with TickerProviderStateMixin {   //  다중 AnimationController를 사용할 때..???
  late TabController _tabController;

  @override
  Widget build(BuildContext context)  {

    @override
    void initState() {
      // TODO: implement initState
      super.initState();
      _tabController = TabController(length: 3, vsync: this);
    }

    return Scaffold(
        appBar: AppBar(
          centerTitle: false,
          title: Text(
            'Tabbar Demo',
            style: TextStyle(
                fontSize: 20
            ),
          ),
          bottom: PreferredSize(
            preferredSize: Size.fromHeight(50),
            child: Container(
              child: TabBar(
                controller: _tabController,
                tabs: [
                  Tab(icon: ClipRRect(child: Text("Shop", style: TextStyle(color: Colors.white),),),),
                  Tab(icon: ClipRRect(child: Text("Donate", style: TextStyle(color: Colors.white)),),),
                  Tab(icon: ClipRRect(child: Text("BId", style: TextStyle(color: Colors.white)),),)
                ],
              ),
            ),
          ),
        ),
        body: SafeArea(
          child: Container(
              child: Column(
                  children: [

                    Expanded(
                      child: Container(
                          child: TabBarView(
                            controller: _tabController,
                            children: [
                              Container(color: Colors.red,),
                              Container(color: Colors.black87,),
                              Container(color: Colors.yellow,)
                            ],
                          )
                      ),
                    )
                  ])
          ),
        )
    );
  }
}

Here is the out put from the above code
Let me know if any query


text:
Q: when to add a dependency vs custom solution in project Finding myself wondering which method of accomplishing a task is better and how to test (for "betterness").
better = lighter, faster, less expensive (page load-wise).
Task: close an open menu when the user clicks outside the menu.
Option 1: add a dependency to the project. Probably would go with this
https://www.npmjs.com/package/vue-click-outside
Option 2: custom solution. Basically copy @MadisonTrash's solution here
Detect click outside element

A: This is a highly opinionated question, but in my opinion, if the functionality you want to add is pretty simple, it would be better to add it to your solution.
The main problem that I have on always depending on external libraries (specially npm ones) is the potential issues that they might bring, e.g.:
https://www.theregister.co.uk/2016/03/23/npm_left_pad_chaos/
https://hackernoon.com/im-harvesting-credit-card-numbers-and-passwords-from-your-site-here-s-how-9a8cb347c5b5
So I would recommend keeping your libraries at minimum and use only the essential and from known/mature ones.


text:
Q: scipy.minimize -- get cost function vs iteration? Is there any way to access the cost function on a per-iteration basis with scipy.minimize without using the callback and re-executing the cost function?
options.disp seems to be intended to do this, but only causes the optimizer to print the termination message.
It would be fine to print it to stdout and use contextlib.redirect_stdout with io.StringIO to gather it and parse through the data after, but I can't find a way to efficiently access the cost function on each iteration.

A: The method least_squares does that with parameter verbose=2. However, it is not a general-purpose minimizer, its purpose to to minimize the sum of squares of the given functions. Example:
least_squares(lambda x: [x[0]*x[1]-6, x[0]+x[1]-5], [0, 0], verbose=2)

For other methods, like minimize, there is no such option. Instead of using callback and re-evaluating the cost function, you may want to add some logging to the function itself. For example, here fun appends the computed values to global variable cost_values:
def fun(x):
  c = x[0]**2 - 2*x[0] + x[1]**4
  cost_values.append(c)
  return c

cost_values = []
minimize(fun, [3, 2])
print(cost_values)

In this example there are 4 similar function values for each iteration step,  as the minimization algorithm looks around, computing the approximate Jacobian and/or Hessian. So, print(cost_values[::4]) would be the way to get one value of the cost function per step.
But it's not always 4 values per step (depends on dimension and the method used). So it's better to use a callback function to log the costs after each step.  The current cost should be stored in a global variable, so it does not have to be recomputed.
def fun(x):
  global current_cost
  current_cost = x[0]**2 - 2*x[0] + x[1]**4
  return current_cost

def log_cost(x):
  cost_values.append(current_cost)

cost_values = []
minimize(fun, [3, 2], callback=log_cost)
print(cost_values)

This prints
[3.5058199763814986, -0.2358850818406083, -0.56104822688320077, -0.88774448831043995, -0.96018358963745964, -0.98750765702936738, -0.99588975368993771, -0.99867208501468863, -0.99956795994852465, -0.99985981414137615, -0.99995446605426996, -0.99998521591611178, -0.99999519917089297, -0.99999844105574265, -0.99999949379700426, -0.99999983560485239, -0.99999994662329761, -0.99999998266175671]

A: I figured out a sort of hack using stdlib features, it uses a "deep" redirect of sys.stdout.  Note that this does not work with jupyter since IPython hijacks sys.stdout, which removes the .fileno attribute.
It may be possible to patch Jupyter using a tempfile.SpooledTemporaryFile in this way, removing this issue.  I don't know.
I believe because this uses OS-level file descriptors, it is also not threadsafe.
import os
import sys
import tempfile

class forcefully_redirect_stdout(object):
    ''' Forces stdout to be redirected, for both python code and C/C++/Fortran
        or other linked libraries.  Useful for scraping values from e.g. the
        disp option for scipy.optimize.minimize.
    '''
    def __init__(self, to=None):
        ''' Creates a new forcefully_redirect_stdout context manager.

        Args:
            to (`None` or `str`): what to redirect to.  If type(to) is None,
                internally uses a tempfile.SpooledTemporaryFile and returns a UTF-8
                string containing the captured output.  If type(to) is str, opens a
                file at that path and pipes output into it, erasing prior contents.

        Returns:
            `str` if type(to) is None, else returns `None`.

        '''

        # initialize where we will redirect to and a file descriptor for python
        # stdout -- sys.stdout is used by python, while os.fd(1) is used by
        # C/C++/Fortran/etc
        self.to = to
        self.fd = sys.stdout.fileno()
        if self.to is None:
            self.to = tempfile.SpooledTemporaryFile(mode='w+b')
        else:
            self.to = open(to, 'w+b')

        self.old_stdout = os.fdopen(os.dup(self.fd), 'w')
        self.captured = ''

    def __enter__(self):
        self._redirect_stdout(to=self.to)
        return self

    def __exit__(self, *args):
        self._redirect_stdout(to=self.old_stdout)
        self.to.seek(0)
        self.captured = self.to.read().decode('utf-8')
        self.to.close()

    def _redirect_stdout(self, to):
        sys.stdout.close() # implicit flush()
        os.dup2(to.fileno(), self.fd) # fd writes to 'to' file
        sys.stdout = os.fdopen(self.fd, 'w') # Python writes to fd

if __name__ == '__main__':
    import re
    from scipy.optimize import minimize

    def foo(x):
        return 1/(x+0.001)**2 + x

    with forcefully_redirect_stdout() as txt:
        result = minimize(foo, [100], method='L-BFGS-B', options={'disp': True})

    print('this appears before `disp` output')
    print('here''s the output from disp:')
    print(txt.captured)
    lines_with_cost_function_values = \
        re.findall(r'At iterate\s*\d\s*f=\s*-*?\d*.\d*D[+-]\d*', txt.captured)

    fortran_values = [s.split()[-1] for s in lines_with_cost_function_values]
    # fortran uses "D" to denote double and "raw" exp notation,
    # fortran value 3.0000000D+02 is equivalent to
    # python value  3.0000000E+02 with double precision
    python_vals = [float(s.replace('D', 'E')) for s in fortran_values]
    print(python_vals)


text:
Q: Como validar tags tr em uma tabela com React Eu possuo dois componentes. O primeiro é o pai e o segundo é renderizado no pai como tags tr, como linhas em uma tabela, as mesmas precisam de validação. Pois as tags tds contem inputs que precisam ser validados antes do pai gravar as informações deles(essa parte ainda não foi implementada). Qual a melhor maneira de fazer isso usando React? Como validar vários componentes filhos?
Segue o código do componente pai:
Vou omitir algumas partes do código no geral para facilitar a visualização
import React from "react";
import  ComboAjax  from "../Componentes/ComboAjax/comboAjax";
import  Row  from "../Componentes/Table/Row";
import  RowVazia  from "../Componentes/Table/RowVazia";
import { webServiceUrl } from "../constants/web-service";
import { authHeader } from "../helpers/headerAutenticacao";

class Timesheet extends React.Component {

    constructor() {
        super();

        this.state = {
            rows: [],
            rowsNovas: ['row']
        }

        this.leituraSolicitacao = this.leituraSolicitacao.bind(this);
        this.inserRowNova = this.inserRowNova.bind(this);
    }
    leituraSolicitacao() {
        fetch(webServiceUrl + '/solicitacoes/' + localStorage.getItem("id") + "/201804", authHeader("POST"))
        .then(response => {
            if (response.ok) {
                return response.json();
            }
        }).then(resposta => {
            this.setState({
                rows: resposta
            })
        })
        .catch(error => {
            console.error("Erro na leitura de solicitacoes.")
        })
    }

    inserRowNova() {
        this.setState((prevState, index) => ({
            rowsNovas: [...prevState + 'row' + index]
        }));
    }

    componentDidMount() {
        this.leituraSolicitacao();
    }

    render() {
        return(

                        {
                            this.state.rowsNovas.map((index) => {
                                return(
                                    <RowVazia key={index}/>
                                )
                            })
                        }

    )}
}

export default Timesheet

Segue o código do componente que é renderizado no map do componente pai:
import React from "react";
import InputMask from 'react-input-mask';
import ComboAjax from "../ComboAjax/comboAjax";
import { validaData } from "../../helpers/validaData";

class RowVazia extends React.Component {

    constructor() {
        super();

        this.state = {
           valorBotaoControle: 'SOLJAVA',
           idInputData: Math.random()
        }

        this.trocaControle = this.trocaControle.bind(this);
        this.validaData = this.validaData.bind(this);
    }

    trocaControle() {
        switch (this.state.valorBotaoControle) {
            case "SOLJAVA":
                this.setState({
                    valorBotaoControle: 'SOLMESTRA'
                })
                break;
            case "SOLMESTRA":
                this.setState({
                    valorBotaoControle: 'NÃO POSSUI'
                })
                break;
            default:
                this.setState({
                    valorBotaoControle: 'SOLJAVA'
                })
                break;
        }
    }

    validaData() {
       validaData(this.state.idInputData)
    }

    render() {
        return(

                    <InputMask style={{fontSize: '13px'}} onBlur={() => this.validaData(this.state.idInputData)}  className="form-control" id={this.state.idInputData} mask="99/99/9999">
                    </InputMask>

                    <button style={{fontSize: '13px'}} onClick={() => this.trocaControle()} className="btn btn-info btn-md btn-block"
                    value={this.state.valorBotaoControle}>{this.state.valorBotaoControle}</button>

                    <InputMask mask="9999/99-99999" className="form-control">
                    </InputMask>

                    <ComboAjax url="/projetos" valorId="id" nomeObjeto="descricao" classe="form-control" />

                    <InputMask maxLength="60" className="form-control" >
                    </InputMask>

                    <InputMask maskChar="99:99" className="form-control">
                    </InputMask>

                    <button onClick={() => this.validaData} className="btn btn-danger">

                    </button>

        )
    }

}

export default RowVazia;


text:
Q: How to install or set up Ext JS 5 or 6 in Eclipse Luna or Juno... Need detailed process to make Ext JS work I have found a video link with Ext JS 4 set up. But I also found two different videos on youtube... One explained with help of pre installed XAMPP and the other video using spket IDE plugin. So Iam bit confused. Whats the difference? Can I use Ext JS without installing XAMPP ( I already have tomcat server integrated with my Eclipse ). Please help me with step by step process to set up Ext JS 5 or 6 on my eclipse.

A: Even I recently started with extjs 5 and 6, it was a bit of a pain to understand the complete folder structure but Its not that though.
Yes you can use it with a pre-installed Apache Tomcat.
Create a normal dynamic web project, in its WebContent folder add the required extjs dependencies(ex. ext-all.js, etc)
Although i would suggest you to maintain the heirarchy while copying the dependencies.
And now all remains is for you to create a html or jsp file and start coding and giving the proper path for your dependencies.

A: The two videos you mentioned seem to address two compeltely different issues.
You need a server application to run your ExtJs applications properly, and you need IDE integration to be able to use Inellisense/Autocomplete while writing code in your IDE.
You need both:
1) Use your tomcat server to run the application.
2) Spket is the best option for Eclipse Integration I ever used.I I highly recommend it.


text:
Q: Meteor 1.2 share files between packages Is there a way in Meteor 1.2 to share files between packages?
What I'm trying to do is have a /private/bower_components/* folder which is shared by all packages in the project. This achieves 2 things:

*

*Eliminates the need to do bower install for each package

*Eliminates duplicates if packages share the same libraries

I would appreciate any ideas or suggestions about how I can achieve the above 2 stated goals.
What I was previously able to do in Meteor 1.1
In my package.js files I would have:
api.addFiles([
    '../../private/bower_components/bootstrap/dist/js/bootstrap.min.js',
],'client');

However, in Meteor 1.2 this produces the error Error: Path contains forbidden segment '..' as discussed here
Notes
I am specifically using bower & not meteor packages because I don't want to include all the files from the libraries. E.g. for bootstrap I use a custom bootstrap.less file and as such I only need the bootstrap.js file from that library.
The Hard Way
The only other ways I can think of doing this are by:

*

*Creating a custom meteor package for each library and reference those from the other packages. This then means I have to maintain a package per dependency which is just horrible.

*Referencing the files directly in the head part of my meteor html templates. That then means I need to references files for package dependencies in the project files which will create a spider web of dependencies; which is not ideal.

[EDIT] Detailed explanation below
I simplified my question above to highlight my problem; however the following adds clarity to the replies I have received.
Current structure
private
  └ bower_components
      └ bootstrap
      └ jquery
      └ ...
packages
  └ boilerplate
      └ boilerplate.less
  └ ...

I put bower_components under private so that all the files don't automatically get bundled into the meteor build causing unnecessary bloat.
boilerplate.less
...
@bootstrap-root: "/private/bower_components/bootstrap";
@import "@{bootstrap-root}/less/mixins.less";
@import "@{bootstrap-root}/less/buttons.less";
...

This does not work immediately because according to the latest meteor less package documentation** I need to specifically include less files for imports in my package.js file api.addFiles('x.less', 'client', {isImport: true}) otherwise I get the error:
While processing files with less (for target web.browser):
packages/boilerplate/boilerplate.less:6: Unknown import:
/private/bower_components/bootstrap/less/buttons.less

...and this leads me to my problem that I need to be able to do this to make it work...
...
api.addFiles([
    '../../private/bower_components/bootstrap/less/buttons.less',
],'client',{isImport: true});
...

** Yes, there are 2 other methods of including import less files but I don't want to have to run grunt just to change the files installed via bower to include import in the filename or group the less files into an "imports" folder. As I said in Meteor 1.1 this just worked without the headache of grunt - it feels like Meteor is going backwards here.

A: After more than a day of trying to get this to work, including:

*

*Using gulp to pull files out of the private directory into the app project root, only to find that I still needed to import them in the package. When this didn't work I tried putting them in an imports directory as described in the documentation but that also did not work.

*Unsuccessfully moving the bower_components into the package directory to reference them within the package & then hopefully expose them via imply() in package.js

*Starting down the path of using api.addFiles('x.less', 'client', {isImport: true}) to import the less files for use in my package. Giving up after realising that I would have to do this for over 50 files because of the number of less imports bootstrap, etc use; and I had no idea what impact this would have in future each time I would do an update to bower packages.

*Using an imports folder so that "import only" less files are automatically imported without needing to use api.addFiles('x.less', 'client', {isImport: true}). I could not get this to work as described in the documentation.

I stumbled across the following links:

*

*Determine why LESS import from /packages/ directory causes build error on Meteor 1.2 branch #513; which references:

*What's blocking you from updating to meteor 1.2?
These links along with the problems I have been having getting this working would lead me to believe that Meteor 1.2 isn't quite ready for dev let alone prod.
For this reason I have decided to downgrade back to Meteor V1.1. Hopefully I can revisit this again in the not-so-distant future.


text:
Q: Bash scripting, read two files line by line I would like to print the first value (in file2) greater than a value of file1. To achieve that, I have the following code:
file1="valueA.txt"
file2="valueB.txt"

while IFS= read -r line
  do
  printf '%s \n' "$line"
  while IFS= read line1 && (( $(echo "$line > $line1" |bc -l ) ));
     do
     printf '%s \n' "$line1"
     done <"$file2"

     done <"$file1"

Here is an example for valueA.txt:
6.40693
14.2077
14.2829
50.7346

Here is an example for valueB.txt:
5.89669
28.4962
35.7508
36.2576
43.2666
93.3357
102.845
106.821
115.623

My code is expected to do this:

*

*print the first value of valueA.txt: "6.40693"

*print the first value greater than 6.40693 in valueB.txt: "28.4962"

*print the second value of valueA.txt: "14.2077"

*print the first value greater than 14.2077 in valueB.txt: "28.4962"
and so on.
However, I'm not getting any result inside the second While loop.

A: I suspect this is what you want: read lines from the 2 files simultaneously:
while read -r a <&3 && read -r b <&4; do
    if [[ $(bc -l <<< "$a > $b") == 0 ]]; then
        printf "%f\n" "$b"
        break
    fi
done 3<valueA.txt 4<valueB.txt

A: Use awk to get the minimum value of file 1, then use awk again to get the first value greater than that minimum.
min_file1=$(awk 'NR == 1 { smallest=$1 }; NR > 2 && $1 < smallest { smallest=$1 }; END {print smallest}' file1)
awk -v x=$min_file1 '$1 > x {print $1; exit}' file2

A: with awk
Input files are always sorted. You can modify the print statements as you wish, I print more to demonstrate how it works (and you have not added yet the exact sample output). Variable resume is used to ensure time complexity remains linear to file length. Usage: awk -f tst.awk file2 file1.
> cat tst.awk
BEGIN { resume=1 }
NR==FNR { a[NR]=$0; next }
{
    for (i=resume;i in a;i++) {
        print("i=" i)
        if (a[i]>$0) { print "First number found >=", $0, "is",a[i]
            resume=i
            break
        }
    }
}

Testing:
> cat file1
6.40693
14.2077
14.2829
50.7346
100000

I have added a final number greater than all numbers, it prints nothing for it.
> cat file2
5.89669
28.4962
35.7508
36.2576
43.2666
93.3357
102.845
106.821
115.623

.
> awk -f tst.awk file2 file1
i=1
i=2
First number found >= 6.40693  : 28.4962
i=2
First number found >= 14.2077  : 28.4962
i=2
First number found >= 14.2829  : 28.4962
i=2
i=3
i=4
i=5
i=6
First number found >= 50.7346  : 93.3357
i=6
i=7
i=8
i=9


text:
Q: UIView Block-Animation Completion Always True I have had an animation that I have recently caught to be not working
//time is a variable used in my code
UIView.animate(withDuration: time, delay: 0, options: [.curveLinear, .allowUserInteraction], animations: {

                //this class is ofType UIScrollView
                self.setContentOffset(CGPoint(x: self.contentSize.width-self.frame.width, y: 0), animated: false)

            //Completion Handler
            }, completion: { finished in

                    //It's always true, not sure a way to fix this
                    if(finished ) {

But, later in my code, I have a method to remove certain animations, specifically from this scrollView.
self.layer.removeAllAnimations()

It gets called, and I would assume it is suppose to make the above
if(finished ) { //Here

return false, therefore it should not go inside the finished. But, finished is ALWAYS true. Whether I cancel this animation, continue the animation, doesn't matter what I do to the animation, the completion handler is always true. Any tips on this matter?

A: Your call to setContentOffset specifies animated:false, if that is the only property you are changing, then there are no actual animations going on, so the call to .animate(...) will always complete with a value of true.  If you set this property (or another one) with animated:true and your duration is too short for the animation to finish, then it could complete with a false value for the parameter.


text:
Q: take order even out of stock I'm working on this
website. In that one the customer must be made to give orders even it is out of stock. The delivery will be delayed a bit. Please help me. I'm new to this magento.

A: You can enable that under System > Configuration. There you go to Catalog > Inventory and set Backorders to Alw Qty below 0


text:
Q: Serve html files and run python script in google app engine I am trying to set up a website with many static html files. Currently I am serving the html files as static files with an app.yaml handler of
 - url: /(.*)
static_files: www/\1
upload: www/(.*)
secure: always

What I need to do now is the ability to run some python code whenever someone is redirected to one of these html files.
Is there some way to both serve html files as static files, and run a python script when it is called? Besides javascript, of course.
My initial thought was to have a handler for html files that would run a script, and then that script would do the backend task it needs to do and then serve the html file as a template using webapp2 or jinja. My html files are stored a few directories down from my python file, in several sub-directories:
-app.yaml
-main.py
-www
   -version1
       --sub directories stored here

Currently my test handler to try and get this to work looks like this:
class testHandler(BaseHandler):

   def get(self, url):

      tplPath = self.request.url
      parseURL = urlparse(tplPath)

      path = "www" + dirname(parseURL.path)
      filename = basename(parseURL.path)

      return jinja2.Environment(
      loader=jinja2.FileSystemLoader(path)
      ).get_template(filename).render()

This gets url or the html file that the requested, adds the www part of the path (side-note, I removed the www part from the served url to keep it consistent with an old website layout), and then tries to render the html file located in the path folder.
When I try to run this, say by accessing https:// AppID.appspot.com/version1/product1/index.html, I get the error
TemplateNotFound: index.html

I checked the path that is being sent to the loader, and it is the correct path to the directory that contains the index.html file.
Is there something obvious i'm missing here? Keep in mind my experience using jinja2 is very limited. Alternatively, is there any other way I could run a python script and still serve the html files? Any help is appreciated.

A: You are using a relative path to the templates, and Jinja2 needs an absolute path according to this post. So instead of path = "www" + dirname(parseURL.path), do this:
# assuming that dirname is os.path.dirname:
path = os.path.join(dirname(__file__),"www" + dirname(parseURL.path))

What this line does is it gets the directory name of __file__, and __file__ is the full, absolute path of the current *.py file that you are running. So, dirname(__file__) is your working directory. After replacing that one line, the rest of your code should work.


text:
Q: Getting the size of a minimized window I never knew this, but apparently:

By default, the system reduces a
  minimized window to the size of its
  taskbar button and moves the minimized
  window to the taskbar. A restored
  window is a window that has been
  returned to its previous size and
  position, that is, the size it was
  before it was minimized or maximized.

In an application, we want to save the position/size of various windows at exit. This leads to a problem for minimized windows. Our solution is to restore all windows before running the save-state logic, but that just seems hacky. Is there a better way?

A: How about using GetWindowPlacement?
That returns a WINDOWPLACEMENT structure that contains information about the window's coordinates in the restored position.
Remember that (as Leo Davidson points out in the comments) that you must respect the difference between workspace and screen coordinates. As the WINDOWPLACEMENT documentation explains:

The coordinates used in a
  WINDOWPLACEMENT structure should be
  used only by the GetWindowPlacement
  and SetWindowPlacement functions.
  Passing workspace coordinates to
  functions which expect screen
  coordinates (such as SetWindowPos)
  will result in the window appearing in
  the wrong location. For example, if
  the taskbar is at the top of the
  screen, saving window coordinates
  using GetWindowPlacement and restoring
  them using SetWindowPos causes the
  window to appear to "creep" up the
  screen.

Or, the simpler solution that I've no doubt used before is just to check if the window is minimized before saving the state, and if it is, skip saving any state information.

As far as explaining why a window changes its size when it gets minimized, Raymond Chen's blog entry (and the linked entry as well) on the subject is mandatory reading. They don't really change to their taskbar button's size, but rather to a pre-defined size of 160x31. He explains that you can see this by minimizing a MDI child window into its parent—that's really its size.

A: Handle WM_SIZE message. If wParam is not SIZE_MAXIMIZED or SIZE_MINIMIZED, keep window size and position in some varibles. Use these variables when window is closed.


text:
Q: ErrorException in Mailer.php line:242 Undefined offset using php laravel i have a problem while sending the mail ErrorException in Mailer.php line:242 Undefined offset 1. This is my Controller
    class ContactController extends Controller
{

     function store(Request $request){

        $data= array(
            'name'=>$request->name,
            'email'=>$request->email,
            'subject'=>$request->subject,
            'comment'=>$request->comment,
            );

Mail::send(['emails.contact'], $data, function ($m) use ($data) {
            $m->from($data['email']);
            $m->to('neeraj.karki17@gmail.com');
            $m->subject($data['subject']);

    });
}

A: Use 'emails.contact' instead of ['emails.contact'].
Or
$template = 'emails.contact';

Mail::send($template, $data, function ($m) use ($data) {
            $m->from($data['email']);
            $m->to('neeraj.karki17@gmail.com');
            $m->subject($data['subject']);

    });

A: you can check syntax in invoice.blade.php file
it might be a div or html error
i was facing the same issue and found this was the problem


text:
Q: Express js does not return data after success to Ajax call I am trying to store the data from client end javascript to server end express js after storing returning some data. I can receive the data at express API userdetail function but unable to return to ajax. Please can I get help?
 $.ajax({
                url: "http://localhost:8080/api/save_user/",
                type: "POST",
                crossDomain: true,
                data: { name: 'Justin', number: '662***' },
                dataType: "json",
                contentType: "application/json",
                success: function (response) {
                    var resp = JSON.parse(response)

                },
                error: function (xhr, status) {
                    alert("error");
                }
            });

Express Js server side

const express = require('express');
const path = require('path')
const os = require('os');
const app = express();
var bodyParser = require('body-parser')
app.use(bodyParser.json())

app.post('/api/save_user', (req, res) => {
   Usermodel.saveData(req.body.name,req.body.number)
        .then(function (userdetail) {
            res.send({ success: true, data: userdetail });
        })
        .catch(next);
})


text:
Q: How to add text/label to my map in angular -typescript without using marker? I am using agm-map in angular. I need to add one label/text to the centre of my polygon in map.
How can I implement that in Typescript without using marker?
I've tried to do it using MapLabel Utility. Take a look at below code.
label: new MapLabel({
    text: result[index].name,
    position: new google.maps.LatLng(object.lat, object.lng),
    fontSize: 10,
    fontColor: #000,
    labelInBackground: true,
    strokeColor: #000,
    map: map
})

I have also referred below link
https://codepen.io/adg29/pen/reGaPd
Thank you in Advance.

A: You need to get first the coordinates of the center of the polygon and use that as the value for your label coordinates. To get the center of the polygon, I followed the answer from this SO post then used the coordinates as the value of  ll in the labelOverlay.
To explain:
First, I noticed that you created the labelOverlay before the polygon. So to get the coordinate of the center of the polygon, you need to move the polygon before the labelOverlay.
Then, you will add the code snippet from the SO post to pass each point of the polygon to a LatLngBounds object through the extend() method.
Get the center of the bounds and used it as the value of the ll in your labelOverlay.
The following is a snippet of how the code should look like. You can also see the working fiddle here.
 // Define the LatLng coordinates for the polygon's path.
  var triangleCoords = [
    {lat: 25.774, lng: -80.190},
    {lat: 18.466, lng: -66.118},
    {lat: 32.321, lng: -64.757},
    {lat: 25.774, lng: -80.190}
  ];

  // Construct the polygon.
  var bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  bermudaTriangle.setMap(map);
  var bounds = new google.maps.LatLngBounds();
  for (i = 0; i < triangleCoords.length; i++) {
  bounds.extend(triangleCoords[i]);
}

var polygonCenter = bounds.getCenter();

var overlay1 = new LabelOverlay({
    ll      : polygonCenter,
    //minBox    : box,

    minBoxH     : 0.346,
    minBoxW     : 1.121,

    maxBoxH     : 0.09,
    maxBoxW     : 0.3,

    //className : 'small',

    debugBoxes  : true,
    debugVisibility : true,

    maxZoom     : 10,
    minZoom     : 6,
    label       : "Hello world",
    map     : map
});


text:
Q: Copy database to a new server Is it possible to copy a database to a new server? I just want to have the database on a new server because I need to make some tests. I didn't have much experience with servers.

A: Follow this steps :

*

*Run your SSMS

*Right click on the database you want to copy

*In the Popup menu , go to Taches , then click Offline

*Right click on the Database again in the popup menu  , Taches -> Detach

*Open the folder ..\MSSQL\DATA , copy Yourdb.MDF and YourDB_log.LDF files to the folder of the new Instance.

*Now you can Attach both Databases and work on it in both instance.
Another way:

*

*Run Your SSMS

*Right click on the Database you want to copy

*In the popup menu , Taches -> Copy the database...

*Follow the steps on the Wizard
You can select option if you want to keep the database ONLINE when it is being copied.
You can also select option of MOVE or COPY database as well.
When the process is over it will show the success message and database will be copied to another server.
Note:
1- The Copy Database Wizard is not available in the Express edition.
2- The Copy Database Wizard cannot be used to copy or move databases that are/have:

*

*System.

*marked for replication.

*marked Inaccessible, Loading, Offline, Recovering, Suspect, or in Emergency Mode.

*data or log files stored in Microsoft Azure storage.
Also , a database cannot be moved or copied to an earlier version of SQL Server.
Updtae:
If there is no Copy database option , then you can Copy Databases with Backup and Restore.
For more information about it MSDN.

A: No experience? No problem, backup the database.
Copy it into the target machine.
Restore DB from device >> open the DB backup file.
At this point you have the entire DB without missing any schema objects such as foreign keys.
Finally delete all sql logins that the DB came with and recreate them manually as you test access.
Once you are comfortable with this operation you can go ahead and get more experience using some of the techniques describe above which are recommended if you have a large DB to restore and so on.
How to restore the DB on SQL Server Management Studio
Steps:
1.  On "Object Explorer" panel right-click on "Databases" and selected Restore Database

*Select "Device" and browse database location.
note: Copy the .bak file locally before restoring.

*The DB information will auto-populate the window, you can edit the name of the DB to be restored.

*Go to the "Files" page and check the "Relocated all files…" box.
Select existing folder locations for Data and Log files.

*HIT OK


text:
Q: Validation errors are not output and fields with previous Form data are not returned Laravel 5.2
view where the form of sending data ('blade'):
@if( count($errors) > 0 )

                @foreach( $errors->all() as $error )
{{ $error }}
 @endforeach

    @endif

    <form method="POST" action="{{  route('contact') }}">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">

            Name:
            <input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}" placeholder="Enter Name">

            Email address:
            <input type="email" class="form-control" id="email" name="email" value="{{ old('email') }}" placeholder="Enter E-mail">

            Site:
            <input type="text" class="form-control" id="site" name="site" value="{{ old('site') }}" placeholder="Enter Site">

            Text:
            <textarea class="form-control" id="text_area" name="text_area" rows="3" placeholder="Some text....."> {{ old('text_area') }} </textarea>

            <input type="checkbox" name="checkbox"> Remember me

        <button type="submit" class="btn btn-default">Submit</button>
    </form>

ContactController.php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ContactController extends Controller {

    public function show( Request $request, $prm=false ){

        $my_array = ['title1'=>'This variable `$title1` content', 'title2'=>'This variable `$title2` content', 'title3'=>'This variable `$title3` content']; //массив
        $my_array2 = ['one'=>array('param1'=>'This variable `param1` content', 'param2'=>'This variable `param2` content', 'param3'=>'This variable `param3` content'),
            'two'=>array('param4'=>'This variabl e `param4` content', 'param5'=>'This variable `param5` content', 'param6'=>'This variable `param6` content')
        ];

        $my_array3 = array(
            'title'=>'Contact',
            'data'=>[ 'one'=>'list 1',
                'two'=>'list 2',
                'three'=>'list 3',
                'four'=>'list 4',
                'five'=>'list 5',
            ],
            'dataI'=>['list-1','list-2','list-3','list-4','list-6','list-6'],
            'bvar'=>true,
            'script'=>""
        );

        /** VALIDATION on Request */
        if( $request->isMethod('post') ) {

            $rules = [
                'name' => 'required|max:10',
                'email' => 'required|email',
                //'site'=>'required',
                //'text_area'=>'required',
            ];

            $messages = [
                'required' => 'The :attribute field is required.',
            ];

            $this->validate($request, $rules, $messages);
                dump( $request->all() );
                dump( $request->session()->all() );
        }

        if( view()->exists('default.contact') ){
            return view('default.contact')
                ->withMydata($my_array2)
                ->withMydata2($my_array)
                ->withMydata3($my_array3);
        }
        else { abort(404); }

    }

}

/app/Http/Kernel.php
   /**
 * The application's global HTTP middleware stack.
 *
 * These middleware are run during every request to your application.
 *
 * @var array
 */
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];

How can I see that validation fulfills and its rules are in effect,
But I do not see the display of validation errors when it is not passed and the data in the input fields when the Form is filled when redirecting back.

A: Let me show you my method which also uses validation on Laravel 5.2 and find out what the difference you have with this code:
The Controller which handles the request:
$validator = \Validator::make($request->all(), [
        'data1' => 'required',
        'data2' => 'required|in:bla1,bla2,bla3',
        'data3' => 'required|array',
        'data3.*' => 'required|json',
        'data4' => 'required_if:data2,bla2',
    ]);

    if ($validator->fails()) {
        $request->flash();
        return \Response::make(\View::make('theform')
            ->withErrors($validator)
            ->withInput($request->all())
            ->render()
        , 406);
    }

The form which contains the form which has been submitted and redrawn with error logs, named 'theform':
<input type="text" class="form-control" name="trip_name" id="trip_name"
    placeholder="Gezi ismi" value="{{ old('trip_name') }}">
@if ($errors->has('trip_name'))

        {{ $errors->first('trip_name') }}

@endif

This is one way to show it. You can also view it your way as:
@if( count($errors) > 0 )

            @foreach( $errors->all() as $error )

{{ $error }}

            @endforeach

@endif

A: Well, the problem did not stop there ))
I create the validation through my own class Request and divide routes for GET and POST and defined separate methods for them in my Controller.
1. app/Http/routes.php
Route::get('/contact_form/{prm?}', ['uses'=>'Admin\ContactformController@show_form_get'])->name('contact_form');

Route::post('/contact_form', ['uses'=>'Admin\ContactformController@show_form_post']);

2. app/Http/Requests/ContactRequest.php - my custom Request class with validation rules:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;

class ContactRequest extends Request
{

    public function authorize()
    {
        return true;  //false
    }

    public function rules()
    {
        return [
            'name' => 'required|max:10',
            //'name' => 'exists:users,name',
            'email' => 'required|email',
            'site'=>'required',
        ];
    }

}  //__/class ContactRequest

3. app/Http/Requests/ContactRequest.php - my Controller with POST and GET handling:
<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\ContactRequest; //custom Request class with validation rules
use App\Http\Controllers\Controller;
use \Illuminate\Support\Facades\Validator;

class ContactformController extends Controller {

    public $show_controller_method = array(__METHOD__);

    /** Method handler http-request with GET
    */
    public function show_form_get( ){

        $this->show_controller_method[] = 'showform()';
        if( view()->exists('default.contact_form') ){
            return view('default.contact_form')->withInfoMethodController($this->show_controller_method);
        }
        else { abort(404); }

    }  //__/public function show_form_get()

    /** Method handler http-request with POST
    */
    public function show_form_post( ContactRequest $request ){

        if( $request->isMethod('post') ):
            dump( $request->all() );
        endif;
    }

3. The view remained the same and there is a return of data "old inputs":
value="{{ old('name') }}"  value="{{ old('email') }}"   and so on...

and errors of validation if they exist:
@if( count($errors) > 0 )

            @foreach( $errors->all() as $error )
{{ $error }}
 @endforeach

@endif

*

*Now the validation works (if it passes successfully - I see a dump() the POST.

*

*If the validation falls, then a redirect occurs, but there are no validation errors and there are no old inputs.

Tell me please what I'm doing is not right?


text:
Q: Understanding recursion without base case in Julia This snippet is from the implementation of Rational Numbers in Julia:
# Rational.jl
# ...
Rational{T<:Integer}(n::T, d::T) = Rational{T}(n,d)
Rational(n::Integer, d::Integer) = Rational(promote(n,d)...)
Rational(n::Integer) = Rational(n,one(n))

//(x::Rational, y::Integer) = x.num // (x.den*y) <--- HERE!

# ...

See how the // function is implemented and then used with infix notation? How does this actually return a value?
When I saw this code I interpreted it like this:

*

*The // function is called with a Rational and an Integer.

*But then it makes a recursive call with no other arguments.

#2 is the one that really confuses me. Where does the recursion within data structure end? How does // return a value if it is constantly evaluating nothing?
Please help me understand this.

A: This works because of one of the most fundamental features of Julia: multiple dispatch. In Julia, functions can have many methods which apply to various combinations of argument types, and when you call a function, Julia invokes the most specific method which matches the type of all the arguments that you called it with. The // call in the method definition you posted defines rational-integer // in terms of integer-integer // – so it isn't actually recursive because the method doesn't call itself, it calls a different method that is part of the same "generic function".
To understand how multiple dispatch works in this case, let's consider the evaluation of the expression (3//4)//6. We'll use the @which macro to see which method each function call invokes.
julia> @which (3//4)//6
//(x::Rational{T<:Integer}, y::Integer) at rational.jl:25

Since 3//4 is a Rational{Int} <: Rational and 6 is an Int <: Integer, and no other more specific methods apply, this method is called:
//(x::Rational, y::Integer) = x.num // (x.den*y)

The current version of the method is actually slightly more complicated than what you posted because it's been modified to check for integer overflow – but it's essentially the same, and it's easier to understand the older, simpler version, so I'll use that. Let's assign x and y to the arguments and see what method the definition calls:
julia> x, y = (3//4), 6
(3//4,6)

julia> x.num
3

julia> x.den*y
24

julia> x.num // (x.den*y)
1//8

julia> @which x.num // (x.den*y)
//(n::Integer, d::Integer) at rational.jl:22

As you can see, this expression doesn't call the same method, it calls a different method:
//(n::Integer,  d::Integer) = Rational(n,d)

This method simply calls the Rational constructor which puts the ratio of n and d into lowest terms and creates a Rational number object.
It is quite common to define one method of a function in terms of another method of the same function, in Julia. This is how argument defaults work, for example. Consider this definition:
julia> f(x, y=1) = 2x^y
f (generic function with 2 methods)

julia> methods(f)
# 2 methods for generic function "f":
f(x) at none:1
f(x, y) at none:1

julia> f(1)
2

julia> f(2)
4

julia> f(2,2)
8

The default argument syntax simply generates a second method with only onee argument, which calls the two-argument form with the default value. So f(x, y=1) = 2x^y is exactly equivalent to defining two methods, where the unary method just calls the binary method, supplying a default value for the second argument:
julia> f(x, y) = 2x^y
f (generic function with 1 method)

julia> f(x) = f(x, 1)
f (generic function with 2 methods)


text:
Q: ticket availability Javascript I'm trying to count how many ticket sold and how many available using javascript and html.
I need a user to be able to select a number of tickets they need. Base on user's selections the system should be able to let the user know if ticket has run out . If ticket available the system can than alert a thank you message. Simple as it sound but I just can't get my head around it.
Anyone out there willing to help. I appreciate a lot.
Here is what I have so far.
<script language="javascript">

  var ticket = ["q_available": 20,"q_sold": 0 ];

  if (q_sold >= q_available){

       alert("ticket sold out. Sorry");

       }else
            {
                 alert("Thank you.");
        }

      </script>

       <select name="ticketing" id="ticketing">
            <option value="1">1<option>
            <option value="2">2<option>
            <option value="3">3<option>
            <option value="4">4<option>
            <option value="5">5<option>
       </select>

A: Here is a working solution.  You had several typos (<option> as a closing tag instead of </option>, for example) but your code was a good start.
I added functionality to check the current number of tickets, compare to the number requested, and buy them if they are available.  The code also resets the <select> value back to a non-selectable default so that it will run the function when the user picks a number.

var q_available = 20;
var q_sold = 0;

function buyTicket(num) {
  var soldOut = false;
  if (q_sold >= q_available) {
    alert("Tickets sold out. Sorry.");
    return;
  }
  for (var i = 1; i <= num; i++) {
    // loop through # of tickets to see if sold out
    q_sold++;
    if (q_sold >= q_available) {
      if (i < num) {
        alert("You can only buy " + i + " tickets... Sorry.");
        soldOut = true;
        break;
      }
    }
  }
  if (!soldOut) {
    alert("Thank you. We have " + (q_available - q_sold) + " tickets left.");
    document.getElementById('ticketing').value = 0;
  }
}
<select name="ticketing" id="ticketing" onchange="buyTicket(this.value);">
    <option value="0" disabled selected>Please select</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>


text:
Q: How many ellipsoids can be maximally inside a circle? This discussion is related to this discussion here where I want to deduce the area difference between such two circles filled with ellipsoids.
Actually, to understand this difference is the main target.
The shape of the ellipsoid can vary if you want or not.
I am thinking how much empty space can be left next to the borders of the circle.
I know how to prove and/or derive similar cases for hexagons etc, but ellipsoid is more challenging.
Example of ellipsoid

You can use an arbitrary given closed area, with freedom to copy, scale, rotate and translate to cover the circle and converge.
In other words, an arbitrary region with piecewise smooth boundary.
How much of the circle area can non-overlapping ellipsoids fill maximally?

A: I assume you're trying to fill a circle with non-overlapping ellipses.
If you allow an arbitrary number of ellipses of arbitrary sizes and any fixed shape and orientation, you can get arbitrarily close to the area of the circle.
For simplicity, first do a linear transformation so the ellipses become circles, and the original circle becomes an ellipse.  Now, given any region
$R$ (with boundary composed of elliptical arcs), start by overlaying a square grid of spacing $\delta$.  For sufficiently small $\delta > 0$, more than $2/\pi$ of the area of $R$ consists of complete squares that are subsets of $R$.  In each such square, you take a disk of radius $\delta/2$ centred at the centre of the square.  This has area $\pi/4$ times the area of the square.  Thus our disks total more than half the area of $R$.  Replace $R$ by the region not covered by those disks, and repeat...


text:
Q: How to get the profilepic path after login with facebook Here i am doing Login with facebook,and also it is working fine,now my question is after login i need the profile pic path,i don't how can get the path,if any one knows please update your answer.as od now i am getting the values like id,name,email but i don't the profilepic path

window.fbAsyncInit = function() {
          FB.init({appId: '1990039811315283', status: true, cookie: true, xfbml: true});

      };
      (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
          '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
      }());

    function fetchUserDetail()
    {
      FB.api('/me?fields=id,name,email', function(responseFromFB){
                //console.log("Name: "+ response.name + "\Email: "+ response.email + "ID: "+response.id);
    console.log(JSON.stringify(responseFromFB));
     var userName = responseFromFB.name;
    var userEmail = responseFromFB.email;
    var profilePic = '1.png';
    var registerFrom = 'Web';
    var FCM_Token = '';
      $.ajax({
     url:'admin/rest/registerFB',
     type:'POST',
     data: {userName: userName, userEmail: userEmail, profilePic: profilePic, registerFrom: registerFrom, FCM_Token: FCM_Token},
     success:function(loginResponse){
        if(loginResponse['status']=='success'){
        window.location.href = "index.php";
        }

     },
    });
            });

    }

    function checkFacebookLogin()
    {
        FB.getLoginStatus(function(response) {
          if (response.status === 'connected') {
            fetchUserDetail();
          }
          else
          {
            initiateFBLogin();
          }
         });
    }

    function initiateFBLogin()
    {

      FB.login(function(response) {
    fetchUserDetail();
   }, {scope: 'email'});
    }

<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">

  <input type="button" class="btn btn-lg btn-fb" value="Sign in using Facebook" scope="public_profile,email" onclick="checkFacebookLogin();"/>

A: When you get the response from FB, you'll get the id of the user for your registered App. You can use this id and get the image of the user.
The below code creates an image tag dynamically and adds to the body. add this to your fetchUserDetail() response handler.
let image = document.createElement("img");
image.src = `https://graph.facebook.com/v2.12/${responseFromFB.id}/picture`;
document.body.appendChild(image);

API docs here


text:
Q: Pythonic way to re-apply a function to its own output n times? Assume there are some useful transformation functions, for example random_spelling_error, that we would like to apply n times.
My temporary solution looks like this:
def reapply(n, fn, arg):
    for i in range(n):
        arg = fn(arg)
    return arg

reapply(3, random_spelling_error, "This is not a test!")

Is there a built-in or otherwise better way to do this?
It need not handle variable lengths args or keyword args, but it could.  The function will be called at scale, but the values of n will be low and the size of the argument and return value will be small.
We could call this reduce but that name was of course taken for a function that can do this and too much more, and was removed in Python 3.  Here is Guido's argument:

So in my mind, the applicability of reduce() is pretty much limited to
  associative operators, and in all other cases it's better to write out
  the accumulation loop explicitly.

A: reduce is still available in python 3 using the functools module. I don't really know that it's any more pythonic, but here's how you could achieve it in one line:
from functools import reduce

def reapply(n, fn, arg):
    return reduce(lambda x, _: fn(x), range(n), arg)

A: Get rid of the custom function completely, you're trying to compress two readable lines into one confusing function call. Which one do you think is easier to read and understand, your way:
foo = reapply(3, random_spelling_error, foo)

Or a simple for loop that's one more line:
for _ in range(3):
    foo = random_spelling_error(foo)

Update: According to your comment

Let's assume that there are many transformation functions I may want to apply.

Why not try something like this:
modifiers = (random_spelling_error, another_function, apply_this_too)
for modifier in modifiers:
    for _ in range(3):
        foo = modifier(foo)

Or if you need different amount of repeats for different functions, try creating a list of tuples:
modifiers = [
    (random_spelling_error, 5),
    (another_function, 3),
    ...
]

for modifier, count in modifiers:
    for _ in range(count):
        foo = modifier(foo)

A: some like recursion, not always obviously 'better'
def reapply(n, fn, arg):
    if n:
        arg = reapply(n-1, fn, fn(arg))
    return arg

reapply(1, lambda x: x**2, 2)
Out[161]: 4

reapply(2, lambda x: x**2, 2)
Out[162]: 16


text:
Q: Excel to compare parameter values of XML table I am Excel newbie and I have two (Book1, Sheet1 and Book2, Sheet1) XML table in Excel as below example -
Book1, Sheet1 (Column - O (value, it can be numeric/alphanumeric/alphabets) & P (parameter name), total 12000 row):

EMERALD Name
2   ForPS
10  InitWait
11  1stInterv
20  Interv
10  UL_DLcapacity
2   ChangeOrigin
0   LCSfunct305
70  TraceVertAccur

Book2, SHeet1 (Column - O & P, total 12000 row):

11  1stInterv
26  Interv
0   LCSfunct305
RUBY    Name
2   ForPS
10  InitWait
10  UL_DLcapacity
2   ChangeOrigin

Excel needs to do as below (I am not sure macro or formula will be better to do this) -

*

*For the parameter value in column O (Book1, Sheet1) find the
corrosponding value of that parameter in book2, sheet1, column O and
then if the values are different, change the color (for example -
Pink) of the cell of that parameter name in Book1, Sheet1 Column P.

*If any of the parameter name in book1&sheet1&column P is not found in
Book2&Sheet1&column P then change the color (for example - red) of
that corrusponding parameter cell in book1&sheet1&column P.

Anyone could help me? Thanks in advance.

A: Ok this is what you need to do

*

*In both book1 and book2 interchange the columns as discussed
earlier (Value will move to column P and Parameter Name will move to
Column O)

*In book2 in columnQ insert the following formula
=P1-VLOOKUP($O1,[book1.xlsx]Sheet1!O$1:P$8,2,0) what this will basically do is find the corresponding value from book1 for each Parameter Name and then substract itself from the value in book2. If the value is not found it will return an error (#N/A)

*Now to change the color of Parameter Name we need to use Conditional Formatting like this

*Select the first Item on column o in book2

*Click on Conditional Formatting on home tab menu and Click on New rule

*Click on Use a formula to determine which cell to format

*On the Edit the Rule Description use this formula =ISERROR($Q1) and format the font/background to your desired Color. This will highlight any values that are not found from the book1

*Again Click on Conditional Formatting on home tab menu and Click on New rule

*On the Edit the Rule Description use this formula =$Q1<>0
and format the font/background to your desired Color. This will
highlight any values that is not same as in book1

*Finally you need to copy the formatting from first item to rest of the item in book2 column o. For copy the first item and use paste special and paste only the format in rest of the items (or whole column O if you so desire). For paste special you can also copy the first item and use short cut key (ALT->E->S->T) to pate the format only


text:
Q: Org-mode: Limit number of entries in a LOGBOOK drawer I have a number of repeating tasks set up in my org-mode file. I also have org-log-into-drawer set to t (see here). This works nicely so that after a while I have something like this:
* TODO My repeating task
  SCHEDULED: <2016-06-27 Mon .+1d>
  :LOGBOOK:
  - State "DONE"  from "TODO"  [2016-06-26 Mon 16:34]
  - State "DONE"  from "TODO"  [2016-06-25 Mon 16:32]
  - State "DONE"  from "TODO"  [2016-06-24 Mon 15:34]
  - State "DONE"  from "TODO"  [2016-06-23 Mon 12:34]
  :END:

However, the :LOGBOOK: drawer continues to be filled with new entries ad infinitum. Eventually this becomes unwieldy and I have to manually prune out the older entries.
Is it possible to limit the maximum number of entries in a :LOGBOOK: drawer so that older entries are discarded when new ones are added?


text:
Q: Is there any suitable data structure or optimisation for this problem? I've got a Node.JS server and I have a dictionary(hash/map) in it (key is a Number, value - Array). Each element of a dictionary is an Array of IDs(strings) and has many elements. Each element of an Array is unique within it's array. For example:
let map = {2333:['id1', 'id2', 'id3', 'id4'], 1234:['id3', 'id4', 'id5'], 123213:['id4', 'id5', 'id77']}
There are queries to the server, which add new elements to arrays or to the dictionary. This happens really often. And there is another type of query, with a set of several keys from our dictionary as a parameter. I need to iterate through that set, find all arrays in the dictionary by the keys from the set and count the number of times each ID occurred. Here is my straightforward solution:
let queryArray = [1234, 123213];
let result = {};//Resulting hash of ID's occurrences
for(let i=0; i<queryArray.length; i++){
    let key = queryArray[i];
    if(!key) continue;
    let array = map[key];
    for(let j=0; j<array.length; j++){
        let id = array[j];
        if(!result[id]) result[id] = 0;
        result[id]++;
    }
 }
//result = {'id3':1, 'id4':2, 'id5':2, 'id77':1};

This operation happens really often on the server and I need to optimize it somehow. Do you have any ideas? The programming language of the answer does not matter.

A: You can create a meta data object just for your counting query.
If you can afford to duplicate the size of data you have, you can apply this method.

const map = {
  2333: ["id1", "id2", "id3", "id4"],
  1234: ["id3", "id4", "id5"],
  123213: ["id4", "id5", "id77"]
};

const counts = {
  2333: { id1: 1, id2: 1, id3: 1, id4: 1 },
  1234: { id3: 1, id4: 1, id5: 1 },
  123213: { id4:1, id5: 1, id77: 1 }
}

// queryArray 1234, 123213
function getQuery(queryArray) {
  let result = {}; //Resulting hash of ID's occurrences
  queryArray.forEach(query => {
    const count = counts[query]
    Object.keys(count).forEach(id => {
      result[id] = (result[id] || 0) + count[id]
    })
  })
  return result
}

console.log(getQuery([1234,123213]))

This approach will get rid of counting id occurrences but increase your memory usage. However I think you need speed more than memory.
One more thing to implement is how to maintain counts object. But this depends on how you add ids to your map. Whenever you add/remove something, you need to update counts object.

A: Just create a second map to serve as the reverse dictionary:
let map = {
    2333: ['id1', 'id2', 'id3', 'id4'],
    1234: ['id3', 'id4', 'id5'],
    123213: ['id4', 'id5', 'id77']
}

let idcounts = {
    'id1': 1,
    'id2': 1,
    'id3': 2,
    'id4': 3,
    'id5': 2,
    'id77': 1
}

Increment idcounts[id] when adding a new id, and decrement when removing.
If you have a lot of overlapping IDs, consider creating a separate map to map ID strings to integer keys, and then work with ints in the dictionaries.

Having said that, Node.JS is really not well-suited for CPU- or memory-intensive work, due to its single-threaded architecture. You might want to consider offloading the lookup work to an external service like Redis, or use a language like Go or C++ with a mutex around the maps to allow for parallel lookup access.


text:
Q: Accuracy of Orbital parameter calculations I'm working on a program that calculates the orbital parameters of orbital bodies, and have run into an issue:
I'm looking up and comparing my programming results with the orbital parameters of Earth and the Sun, and realised that different equations seem to give me different results:
To elaborate, take the following parameters:
rmin or Periapsis: 147.09 x10^9 metres
rmax or Apoapsis: 152.10 x10^9 metres
ε or Eccentricity: 0.0167
a or Semi-major axis: 149.60 x10^9 metres
If I apply the following equation from here to obtain the Semi-minor axis, or b:
$$b = a\sqrt{1 - \epsilon^{2}}$$
I receive the following value:
149600000000 * sqrt(1 - (0.0167^2)) = 149579137573 (On Google calculator)
However if I obtain the Semi-minor axis using the Semi-latus rectum, or p from here:
$$ b = \frac{p}{\sqrt{1 - \epsilon^{2}}} $$
I obtain the following value:
149548054813 / sqrt(1 - (0.0167^2)) = 149568912904
When we look at the difference between these two numbers, there is a highly noticeable difference of 10224670 between them! I know this is based from Earths approximated orbital values, which we don't know the true values for, (I grabbed them from here)
My question is, which of these two equations are more accurate, WHY??, and are there any other equations that find the Semi-minor axis, also explaining  the accuracy of them.
I saw the same thing for a few of the other properties (I think it was Semi-major) and I ended up with bizarre differences. I am calculating this right (according to the page) but seem to be getting huge error margins. Any ideas?
NOTE:
I obtained the Semi-latus rectum, or p using the equation from here:
$$ p = \frac{r_{min} \cdot r_{max}}{a} $$
(152100000000 * 147090000000) / 149600000000 = 149548054813
Please bare in mind, I'm only in Year 11, so I may not understand everything you throw at me, also acknowledging that this is a pretty massive task for me to undertake to begin with; this also isn't any form of homework (thankgod), I'm doing this under my own taking.

A: When you are given a number with only 3 significant figures (eccentricity of 0.0167 - only the 1, 6 and 7 are "significant") then you know the number is not 0.0168 or 0.0166 -- and that gives you an approximate range of accuracy you can expect.
Each of your methods gives you $1.496 \times 10^9 ~\rm{m}$ - accurate to 4 significant digits. That's better than you should expect.
The accuracy of your result is only ever as good as the accuracy of the inputs. Some of the data you have is given to 5 significant digits - that will give you the "more accurate" results.
I recommend that you learn about error propagation. There are millions of resources online for this - a relatively basic introduction can be found here

A: $a = 149598023$
$e = 0.0167086$
$p = a(1-e^2)$
$p = a(0.99972082268604) = 149,556,258.62576513369892$
$b = \frac{p}{ \sqrt{1-e^2}}$
$ = \frac{p}  {0.99986040159916324190990908617052}$
$ = 149,577,139.35522085944399314340085$
$b = \sqrt{p*a}$
  = 149,577,139.35522085944399314340085
$pa = rmax * rmin$
$22,373,320,617,691,160.86368910923516 =  rmax * rmin$
$rmax = \frac{p}{(1-e)}  = \frac{p}{0.9832914}    =152,097,596.5270978$
$rmin = \frac{p}{(1+e)}  = \frac{p}{1.0167086}    =147,098,449.4729022$
$152,097,596.5270978 * 147,098,449.4729022 = 22,373,320,617,691,160.86368910923516$


text:
Q: TypeSafeConfig and PureConfig - load a Map[String, Any] value from config I'm trying to load up a Map[String, Any] from the config file. It's currently written like this
map-name {
   stringValue = "firstValue"
   intValue = 1
   booleanValue = true
  }

Pureconfig is having trouble reading this config as a Map[String, Any]. It only works if replace Any with some strict type but I want more flexibility than this.
Is there any way around this?

A:
Is there any way around this?

Yes there is. You can use this type: Map[String, ConfigValue]
ConfigValue from its Scala Doc:

An immutable value, following the JSON type schema.

But then you can use ConfigObject instead of Map[String, ConfigValue], as this is the same thing.
You can handle this now like a JSON-Object structure.
Here are some examples: java-api-usage-examples.

A:
I just want to replace values of an existing config. If I read in the whole config from the config file, I'll have to specify all the other values, even the ones I don't want to change.

This is newConfig.withFallback(oldConfig).

A: You can have something like this:
import scala.collection.JavaConverters._
implicit val mapReader = pureconfig.ConfigReader[ConfigObject].map(co => co.unwrapped().asScala.toMap)


text:
Q: Where is Visual Studio 2015 local help for System.Web.MVC? I installed everything remotely relevant to C#/ASP.Net development in my local help content. However, when I edit CSHTML files, put cursor on Label in @Html.Label and press F1 the help topic that comes up is an online content. When I open it in the browser it becomes clear this help topic is under System.Web.Mvc.Html >LabelExtensions Class > LabelExtensions Methods
When I look at Contents tab in local help under .NET Framework 4.6 and 4.5.NET Framework Class Library()\System.Web Namespaces() System.Web.MVC doesn't exist there. What I have is System.Web.ModelBinding and the one below is System.Web.Profile namespace
Can anyone explain this? Can Visual Studio 2015 local help for MVC be downloaded locally at all?
Note that I did find 2 posts about this issue but neither has an answer:
MVC 6 integrated help missing in visual studio 2015
https://social.msdn.microsoft.com/Forums/vstudio/en-US/5d79acd8-9b42-47a0-9bd5-50ca721e62c8/visual-studio-2015-f1-help-doesnt-work?forum=visualstudiogeneral


text:
Q: How to grep "\n" in file Sample file : abc.ksh
echo "This is a sample file." >> mno.txt
echo "\nThis line has new line char." >> mno.txt

I want
echo "\nThis line has new line char." >> mno.txt

as output.

A: Easiest way is using REGEX:
grep "$" filename  # this will match all lines ending with "\n" (often all lines)
grep "PATTERN$"    # this will match all lines ending with "PATTERN\n"

In REGEX language, $ means EOL (end of line), so it will often match "\n" (cause is very common as the end of line).
WARNING: be careful to use versions of grep that support REGEX!.

A: Simply escape the backslash with another backslash and put the regex in single quotes so the shell does pass it to grep without handling the backslashes itself:
grep '\\n' abc.ksh

A: Regular expression pattern search
grep -P '\n' mno.txt

A: Use -F to match fixed strings:
$ grep -F "\n" file
echo "\nThis line has new line char." >> mno.txt

From man grep:

-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines,
  any of which is to be matched.  (-F is specified by POSIX.)

A: You may try like this by escaping the backslash with another backslash:
grep '\\n' xyz.ksh

A: grep -zoP '[^\n]*\n[^\n]*' file

*

*-z - change all \n to zero byte

*-o - show only diff (because whole file is one line for grep now)

*-P - perl regexp

find \n and line before and after


text:
Q: Linear Programming Constraint Formulation so we're working on a project where the goal is to have a system that automatically defines the optimal solution to the following problem:
Managers can offer tasks to a group of workers, without giving direct assignments. Instead, each worker can "apply" for the task he would like to perform. Therefore, a web application should be created where:

*

*Managers can offer tasks

*Workers can select tasks with priorities (most preferable task = priority 1 and so on)

*The objective is to give as many workers as possible their highest priority task

*Furthermore, Managers have to manage the workes who fulfill the task, therefore, each manager should be equally utilized to avoid "overloading" of a manager

*The set of possible priorities should be configurable, therefore the mathematical solution should be scalable. (E.g. Admin can allow priorities 1 to 3 or 1 to 5).

The question is. How can i formulate my problem mathematically as a linear program?
I have come to the conclusion so far that the objective function would look something like this:
$$P = 1x+2y+3z $$ $$P-> min$$ Where $P$ is the sum of priorities given and $x$ $y$ and $z$ are the respective amounts for priorities 1 2 and 3.
I think minimizing the objective function is the correct way here. Adding more priorities would mean adding more variables, e.g. $P = 1x+2y+3z+4a+5b......$
However, I cannot form my linear constraints, as i cannot identify how my priorities that I identified as my variables can be used in said constraint.
Can someone give me a hint in the right direction? Am I on the right path?
Thanks!

A: I would say, the objective is more like: $$\max \sum_{w,t} \mathit{pref}_{w,t} x_{w,t} $$ where $$ x_{w,t} = \begin{cases} 1 &\text{if worker $w$ is assigned to task $t$} \\ 0 & \text{otherwise}\end{cases}$$ and $\mathit{pref}_{w,t}$ measures the preferences. Here I use: preferences increase when an assignment is more preferred (opposed to the scale you suggested). The reason is technical. I want a value of $0$ not to mean: this is a good assignment.


text:
Q: How to find the packet lost in veins omnet++ In veins example of omnetpp I changed the value of alpha and tried to analyse the total lost packet, but for the different values of alpha.
The packet lost remains zero even the SNIR lost packets remains zero. Can any one help me with that?

A: I just tried running the example scenario that comes with Veins 4a2. Other than you, I am seeing lost packets (0 for many nodes, but up to 14 for some nodes). Something might be wrong with the way you are collecting statistics.

For Veins 3.0, statistics are very similar (though notably not exactly the same, due to changes in the radio model):