text:
Q: Extract a sentence from a text based on another sentence that lacks some words So, for my university graduation thesis I chose to build a web app that extracts the main idea from an article(summarization app). It's build in PHP.
But I have reached a situation to which I see no possible solutions, maybe you guys can give me an idea or a solution to the problem.
So basically the app relies on extractive algorithms, what I do:
Firstly, I "sanitize" the text, which means I remove all stop words, I stem the words, remove any abbreviation or initials that may contain a '.' that can alter my text from not being broken into sentences correctly.
After that I break the text into sentences by exploding the text by . token and I get all sentences in an array.
Now comes the process in which I "give" the sentences a rating, basically this is how I spot the most relevant sentence in the article, the one that has the highest rating is usually the one that contains the article's main idea.
But my problem starts now, the sentences that I have rated are the ones on which I applied all the 'sanitization' and are not in their original form. I want to take the highest rated sentence and based on that I want to extract the original sentence from the text to which this rated sentence matches. I have tried matching it with regex but it doesn't always work. I need a 100% working method that extracts the original sentence from the article based on the highest rated sentence.
I have no idea how to achieve this, since the rated sentence misses words from it.
I hope you understand my point. Thank you.
EDIT:
This is the function that I now use to match the original sentence in the article but I doesn't always work:
private function get_original_sentence($s, $t)
    {
        $s = preg_replace("/[^A-Za-z0-9 ]/", '', $s);
        $s = trim($s);

        $arr = explode(" ",$s);
        $f_word = $arr[0];
        $l_word = $arr[count($arr)-1];

        preg_match('~(?<=\.)([a-zA-Z ]*)'.$f_word.'(.*?)'.$l_word.'([a-zA-Z ]*)(?=\.)~i', $t, $matches);

        if(empty($string))
        {
            preg_match('~(?<=\.)([^\.]*)'.$f_word.'(.*?)'.$l_word.'([^\.]*)(?=\.)~i', $t, $matches);
        }

        return $matches[0] ? $matches[0] : false;
    }

The $s parameter is the rated sentence after the summarization and $t is the full original article.
EDIT 2: The abbreviation removal function, which practicaly sanitizes the whole text not just abbreviations.
static private function _remove_abbrev($subject)
    {
        $domains = '\.ro|\.com|\.edu|\.org|\.gov';

        foreach(self::$abrv as $abrv)
        {
            $not.= strtolower(str_replace('.', '\.', $abrv)).'|';
            $not.= strtolower(trim(str_replace('.', '\.', $arbv))).'|';
        }

        $not = substr($not, 0, -1);

        //$subject = preg_replace('~(\".*?\")~u', '', strtolower($subject));//replaces " " from text.
        $subject = preg_replace('~(?<=\.|^)(?![^\.]{60,})[^\.&]*\&[^\.]*\.?~u', '', strtolower($subject));
        $subject = preg_replace('~\b\s?[\dA-za-z\-\.]+('.$domains.')~u', '', strtolower($subject));
        $subject = preg_replace('~\s*\(.*?\)\s*~u', '', strtolower($subject));
        $subject = preg_replace('~\b('.$not.')~u', '', strtolower($subject));
        $subject = preg_replace('~(?<=[^a-z])[A-Za-z]{1,5}+\.[\s\,]*(?=[a-z]|[0-9])~u', '', strtolower($subject));
        $subject = preg_replace('~(?<=[\s\,\.\:])([A-Za-z]*(\.)){2,}+(.)(?=.*)~u', '', strtolower($subject));
        $subject = preg_replace('~(\d)+\.(\d)*(\s)~u', '', strtolower($subject));

        return $subject;
    }

This is the abbreviation array collection:
static public $abrv = array(
        ' alin.', ' art.', ' A.N.P', ' A.V.A.B', ' A.V.A.S.', ' B.N.R', ' c.', ' C.A.S', ' C.civ.', ' C.com.', ' C.fam.', ' C.pen.', ' C.pr.civ.', ' C.pr.pen', ' C.N.C.D', ' C.N.V.M', ' C.N.S.A.S', ' C.S.M', ' C.S.J', ' D.G.F.P', ' D.G.P.M.B', ' D.N.A', ' D.S.V', 'Ed.', ' etc.', ' H.G.', ' I.G.P.F', ' I.G.P.R', ' I.N.M.L.', ' I.P.J', ' I.C.C.J', ' lit.', ' M.Ap.N.', ' art.', ' M.J.', ' M.Of.', ' nr.', ' O.G.', ' O.U.G.', ' p.', ' P.N.A.', ' par.', ' pct.', ' R.A.A.P.P.S.', ' subl. ns.', ' S.C.', ' S.A.', ' S.P.P.', ' S.R.I.', ' S.R.L.', 'U.N.B.R.', ' urm.', ' str.', ' sec.', ' pag.', ' a.c.', ' dv.', ' dvs.', ' prof.', ' conf.', ' dr.', ' drd.', ' mrd.', ' s.a.m.d'
    );

A: How about this approach:

*

*You extract all the matches with preg_match_all first into an array with numerical indexes $substitutions

*Then you replace them with a unique marker utilizing the 4 variable of preg_replace: $count whose value points to the $substitutions array

A rough code sketch:
$count = 0;
$substitutions = array();
foreach ($patterns as $pattern) {
    $matches = array();
    preg_match_all($pattern, $subject, $matches);
    preg_replace($pattern, $subject, '__'.$count.'__', -1, $count);

    foreach ($matches[???] as $match) {
        $substiutions[] = $match;
    }
}

I'm not sure if i messed up the syntax for referring to $count as call by reference ( e.g. &$ in the documentation).
I think the crux of this approach is to extract the right value from the $matches array. There are some options, how the matches are extracted.  Maybe another approach could be not to use $count from preg_replace but from the according sub-array of $matches

A: The _remove_abbr function doesn't seem to work very well. It removes words like "art" at the end of sentences but doesn't remove abbreviations like "C.A.S." (because it has already removed "c."). It also has at least one typo ($arbv) and doesn't define $not before concatenating to it.
Nevertheless, how about instead of removing the abbreviations, URLs, and so on, you replace them with space characters? That way, when you split the text into sentences, they would still have the same length as in the original text so you could store the position the sentences start and end at. If necessary, you could convert multiple spaces to a single space at this point but you'd still know where they came from in the original text.
You just need a callback function to achieve this:
    $f = function($m){ return str_repeat(" ", strlen($m[0])); };
    $subject = preg_replace_callback('~(?<=\.|^)(?![^\.]{60,})[^\.&]*\&[^\.]*\.?~u', $f, strtolower($subject));
    $subject = preg_replace_callback('~\b\s?[\dA-za-z\-\.]+('.$domains.')~u', $f, $subject);
    $subject = preg_replace_callback('~\s*\(.*?\)\s*~u', $f, $subject);
    $subject = preg_replace_callback('~\b('.$not.')~u', $f, $subject);
    $subject = preg_replace_callback('~(?<=[^a-z])[A-Za-z]{1,5}+\.[\s\,]*(?=[a-z]|[0-9])~u', $f, $subject);
    $subject = preg_replace_callback('~(?<=[\s\,\.\:])([A-Za-z]*(\.)){2,}+(.)(?=.*)~u', $f, $subject);
    $subject = preg_replace_callback('~(\d)+\.(\d)*(\s)~u', $f, $subject);


text:
Q: Good file manager replacement in Linux / Windows? I like to use Windows and Linux (Ubuntu) and I'm constantly disappointed at the lack of power in the file managers.
What uber-powerful all inclusive awesomesauce solution do you use?
/yes, I know about the terminal
//yes, I'm lazy

A: Total Commander to the rescue!

I don't use it anymore actually, but I do remember using the dos-version, and knowing all the hotkeys... I could really do things a lot faster!
I even remember still using that old dos-version under windows 3.11 because it was so much better than the windows explorer.
Edit: Just been searching, and it was actually Norton Commander which I used in dos (from which total commander is a clone):

A: sunflower-fm is a GNOME file manager currently in alpha. I just started reading about it on reddit this morning but it looks promising.

A: An old fart replies: I use the old File Manager from Windows NT4 (or was it 3.51?). It dosn't have the right clickery that Explorer does, but it's much faster, much better at file copies and file deletes and doesn't hang up every time a network drive won't reconnect.
I've tried just about every File Manager replacement out there but they're all just too slow or too fussy to use. Mind you my idea of anawesomesauce solution is the command prompt :-)
Not a solution for unix of course.
JR

A: midnight commander is very good and highly tweakable. It is also very light and is perfect for remote ssh session as it is console based.

A: xplorer2 is good, however I'm still looking for a file browser that integrates with the run dialog for easy launching.

A: You appear to be talking about Orthodox file managers.  Nikolai Bezroukov has a whole WWW site about them, that includes some user commentary.

A: i like to open rox filer windows from the terminal

redpajama_set_name: RedPajamaStackExchange


text:
Q: correcting computed table cell height by programmatically scrolling I am computing the height of my tavleview cells individually myself.
While this works well when I scroll, sometimes when the table appears it looks wrong.
Then if I scroll up and down it looks correct.
Therefore I need to programmatically scroll the table.
Now the problem is that sometimes I only have 3 lines so I cannot scroll programmatically - but manually one can "scroll" the view even if there are no more cells. In this case I still need to "scroll" the view programmatically since this corrects the computation of the tablecell height,
So this code does not work:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:10 inSection:0];
[self.theTable scrollToRowAtIndexPath:indexPath
                      atScrollPosition:UITableViewScrollPositionTop
                              animated:YES];

So the question is, how can I scroll the view programmatically?
*EDIT*
I checked the computed heights and they are all correct - even after scrolling they compute to exactly the same as when initially displayed.
So I gave the frame a red background to see the difference between the display right after view did appear compared to after the scrolling.
And in fact the frames ALL after the viewDidAppear are of the same (wrong) height, which is not the height with which they are set like this:
-(void) layoutSubviews {
[super layoutSubviews];

//                              x     y   width height
float h = expectedLabelSize.height;
[imageView setFrame:CGRectMake(    8.0, 10.0,  20.0, 20.0)];
[t1 setFrame:CGRectMake(          40.0,  4.0, 280.0, h)]; //total width 320
[t1 setBackgroundColor:[UIColor redColor]];
[t2 setFrame: CGRectMake(        235.0, h+4, 85.0, 15.0)];
NSLog(@"-layoutSubviews--> h:%f w:%f",h,expectedLabelSize.width);

}
After the scrolling the height is computed to exactly the same value AND now finally the frame has the height as assigned here.

A: In viewWillAppear:
[self.tableView beginUpdates];
[self.tableView endUpdates];

A: I used to have the exact same problem with resizing a cell dynamically to accomodate the contents of a UITextView. I ended up using the free Sensible TableView framework, which amongst many other things, automatically calculates the height for all my cells.


text:
Q: Node.js event driven paradigm = messy code? I am coming from a PHP background and am now trying to get used to the event driven paradigm of Node.js. However, my code quickly get messy. Below I compare procedural code with actual Node.js Redis code. Am I doing this right?
PROCEDURAL (pseude code)
if(!client.get("user:name:koen")) {
    client.set("user:name:koen", "user:id:" + client.incr("count:users"));
}

EVENT DRIVEN (actual code)
client.get("user:name:koen", function(err, res) {
  if(!res){
    client.incr("count:users", function(err, count){
      client.set("user:name:koen", "user:id:" + count, function (err, res) {
        callback(err, res);
      });
    });
  }
});

A: Callback hell, mentioned in the question, is greately explained here, as well as how to write the code to avoid it:
http://callbackhell.com/


text:
Q: Download speed from S3 and EC2 storage, request from Node js and browser Me and my team are creating a mobile game in which a map is available. We store json  information in multiple files - each file represents a tile on the map. To render the map, we download the files and process them to create streets, buildings etc.
I want to choose the best way to download tile files to the mobile devices but I didn't have the possibility to do this test on the mobile devices so i used a browser and node js scripts.
I used a 100KB json file. Uploaded it on an S3 bucket and on EC2 storage. I wrote a few node scripts to connect to the S3 or EC2:

*

*GET request from Node js local script to S3 bucket (bucket.zone.amazonaws.com/file) - ~650ms

*GET request from Node js local script to Node js server run on EC2 instance which connects to S3 - ~1032ms

*GET request from Node js local script to Node js server run on EC2 instance which loads the file from local storage - ~833ms

The difference between the last two values is actually the time added for EC2 instance to access the file from the bucket. And the reason for making a request to S3 from EC2 is that I know that connections between AWS services is really fast.
The other test I made was from the browser (Firefox):

*

*Directly accessed the S3 bucket (bucket.zone.amazonaws.com/file) - ~624ms with values between 400ms and 1000ms

*Through the Apache server on EC2 (domain/file) - ~875ms with values between 649ms and 1090ms

*Through Node js server which connects to S3 bucket (run on EC2) (domain:port) - ~1014ms with values between 680ms and 1700ms

*Through Node js server which loads the file from local storage (run on EC2) (domain:port) - ~ 965ms with values between 600ms and 1700ms

My question is why is such a big difference between accessing the file from the browser and accessing it through Node script?
For logging the times, I made each request for 10 times and I did the mean of times.
EC2 instance is micro, in Ireland. The bucket is situated in Ireland too.

A: I propose several clue that may help you to profile.

*

*Cache, when you use script to get the json data. The cache mechanism would not work. While in browser, it will honor the cache header and may fetch from the cache, thus decrease the speed.

*GZip header, I think you would not enable gzip to compress your data in nodejs server. I am not sure if you configured such on Apache. Imagine a json file with 100k, if it is compressed, the transfer time would surely be decreased.
Thanks

A: So i think this question has no more sense since the times are more even after hard refreshing the page.


text:
Q: How to send email in windows 10 apps using C#? I am working on a Windows 10 store app project. In my project I need to send confirmation email to client using my app. How can I do it without using any confirmation dialogue to show to user?
Confirmation email is like
"You order no "xy" has been confirmed."

A: using System.Net.Mail;

...

MailMessage mail = new MailMessage("you@yourcompany.com", "user@hotmail.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.google.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

reference: Send email with C#
Also as mentioned in the comments see this : MSDN Docs Send Email


text:
Q: WCF Data services - Client is caching results I have a WCF data service, my client is a WPF app.
I have a service operation in my WCF data services. something like that
[WebGet]
public IQueryable<VSuppliersExtra> GetAllVSuppliers()
{
    List<VSuppliersExtra> lstVsup = new List<VSuppliersExtra>();
    // add some VSuppliersExtra entities to the list
    ........
    return lstVsup.AsQueryable<VSuppliersExtra>();
}

In my client I have
oCollection = new ObservableCollection<VSuppliersExtra>(jp.CreateQuery<VSuppliersExtra>("GetAllVSuppliers"));
//Open a new window Change collection and update the changes in the DB
.......
//run the same query again
.......
oCollection = new ObservableCollection<VSuppliersExtra>(jp.CreateQuery<VSuppliersExtra>("GetAllVSuppliers"));

Now, everything work just fine, BUT the 2nd call for the service operation will always get me the same results without the changes, until I restart my app.
I check the DB, all my changes are saved to the SQL server, I've checked the function in the service, and it does return the updated data... YET I get the same result set!!!!
Is there some caching in the client side????

A: Well,
I found some article http://msdn.microsoft.com/en-us/library/gg602811.aspx
I added a context.MergeOptions  = MergeOption.OverwriteChanges;
That did the Trick.
Thank you


text:
Q: indicating a related field in a xml file I have this xml fragment and it works
    <record id="expiry_alert" model="base.automation">
        <field name="name">XmlSend</field>
        <field name="model_id" ref="model_project_task"/>
        <field name="trigger">on_time</field>
        <field name="active" eval="True"/>
        <field name="trg_date_id" search="[('model','=','project.task'),('name','=','date_deadline')]" />
        <field name="filter_domain">['&',['date_deadline', '!=', False], ['stage_id.fold','=', False]]</field>
        <field name="state">code</field>
        <field name="code">record.expirations()</field>
        <field name="trg_date_range">5</field>
        <field name="trg_date_range_type">minutes</field>
    </record>

I say it works because it does insert a record in the base.automation model and such record does what I expected
Now, this version doesn't work
    <record id="expiry_alert" model="base.automation">
        <field name="name">XmlSend</field>
        <field name="model_id" ref="model_project_task"/>
        <field name="trigger">on_time</field>
        <field name="active" eval="True"/>
        <field name="trg_date_id" ref="date_deadline" />       <-- PLEASE NOTE THIS LINE !!
        <field name="filter_domain">['&',['date_deadline', '!=', False], ['stage_id.fold','=', False]]</field>
        <field name="state">code</field>
        <field name="code">record.expirations()</field>
        <field name="trg_date_range">5</field>
        <field name="trg_date_range_type">minutes</field>
    </record>

I tried with several variants of <field name="trg_date_id" ref="date_deadline" />,
like <field name="trg_date_id" ref="project_task.date_deadline" />
But I couldn't find a variant that works
Is it me ?
Is ref supported ?
How am I supposed to use it ?

A: To get the XML ID of the filed, activate developer mode and go to settings -> technical -> fields  and filter per Task model and search for date_deadline field, open it and from debug icon select view Metadata
The XML ID for date_deadline is project.field_project_task__date_deadline
So you can use it as below:
<field name="trg_date_id" ref="project.field_project_task__date_deadline" />


text:
Q: Select and count attribute for non-unique column I have a table of persons and activities - neither column is unique.
I need to rank every user by the count of distinct activities, e.g.:
_________________
|PERSON|ACTIVITY|
-----------------
|Lars  | Sleep  |
|James | Eat    |
|Lars  | Sleep  |
|Lars  | Sleep  |
|Kirk  | Shred  |
|James | Shred  |
-----------------

Lars appears thrice, but performs the same activity repeatedly.
Kirk appears once, so he is identical to Lars in number of activities.
James performs two distinct activities, so he should be ranked the highest.
The expected output:
James - 2
Kirk - 1
Lars - 1

(ordering of identical counts is irrelevant)
The solution I have come up with involves applying DISTINCT to the person column and iterating over the names, selecting the activities for each and applying DISTINCT followed by COUNT. It feels like there must be a better way.

A: I think you just want count(distinct):
select person, count(distinct activity) as num_activities
from t
group by person
order by num_activities desc;

A: You could use GROUP BY function.
SELECT PERSON, COUNT(DISTINCT ACTIVITY) AS count FROM YOUR TABLE GROUP BY PERSON ORDER BY count;

A: SELECT Person, COUNT(DISTINCT Activity) AS ActivityCount
FROM MyTable
GROUP BY Person
ORDER BY 2 DESC


text:
Q: which is the best algorithm to to find a image which is similar to the "input" image from a set of images I'm developing an android app for tourists. I need to display information about heritage buildings. I have to compare the photos taken by the tourist with my own database to check if I'm having the info related to that building.since photo taken by tourist may not be exactly same as the photo in my database so I'm looking for an algorithm to find similar images in real time. I have read about algorithms like SURF, SIFT, pHash but still i am confused about which to use.(Image comparison will be done at the server side and not by the application.)

A: Use an image hashing algorithm.

*

*Hash all your stored images

*Hash your incoming image

*Compare your incoming image' hash to your stored hashes.

For a simple image hash:

*

*Resize your image to a small standard size (like 16x16) so the hash doesn't take up too much space

*Convert your image to gray scale

*If a pixel value is greater than the average grayscale value, set it to 1 else set it to 0

Here's some code that hashes an already resized image
function imageHash(pixels) {
  var result = [],
    sum = 0,
    size = pixels.length,
    gray, r, g, b, c, avg, i;
  for (i = 0; i < size; i++) {
    r = (pixels[i] >> 16) & 0xFF;
    g = (pixels[i] >> 8) & 0xFF;
    b = (pixels[i]) & 0xFF;
    gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
    sum += gray;
    result[i] = gray;
  }
  avg = sum / size;
  for (i = 0; i < size; i++) {
    result[i] = result[i] > avg ? 1 : 0;
  }
  return result;
}


text:
Q: Why does WAS admin console queue configuration not accept asterisk (*) as Queue Manager entry? I am configuring WAS to connect to MQ via CCDT, and should be using a Queue Manager Name with wild cards, i.e *QMan.
It is accepted in the Queue Connection Factory Screen and in the Activation Spec Screen, but it is not accepted in the Queue Configuration Screen. As shown on the below image, I am forced to leave the Queue Manager field blank. And my application is not received MQ messages. I am suspecting this might be the reason.
Any ideas why I cannot configure the Queue Manager in Queue screen? And what is the common problem if message listener is not receiving, even if the MQPUT is working.
I had double checked my CCDT configuration in Activation Spec, and have check the jndi names, everything is configured correctly.
Also note that it is working if I connected directly to the MQ via host/port etc. But I have to use CCDT to utilize our MQ cluster.

A: The Queue Manager (or Queue Sharing Group) name on the JMS Queue panel defines where the queue is located and not how you connect to it. It is the Queue Manager name in the JMS connection factory or activation specification that defines which queue manager your application connections to.
So it is correct that you can't enter a * in this box.
If the connection is not working when using a CCDT then it is likely to be another problem that this Queue Manager name box. Note: you can't use an XA connection with CCDTs due to the fact that a CCDT won't guarantee you will connect back to the same queue manager in the event of XA recovery.


text:
Q: Minimum for varchar? I thought you could set varchar as varchar(min,max), but I must have mistaken. What's the syntax to set a min and max? Or do I have to use PHP to do that?
Update:
Let me add more context. I'm making a field for usernames, so I thought I could set the minimum and maximum for varchar in MySQL. Seems I can only set the length which is 0 to 255. I'm guessing this means I have to use PHP to add the minimum restriction

A: You cannot set a minimum length for a VARCHAR field in MySQL. Despite jspcal's answer, there is no such min length constraint.
The max is simply VARCHAR(max)
Yes, you must use PHP to limit the length. Personally, I use application code to perform all my constraint validations, and only rely on the DB as a last resort/failsafe.
It's better to detect invalid data in your application and return a useful error message, than to catch a DB exception and have to interpret/translate that into the appropriate error message.

A: better to do it in php, mysql would require some triggers to do the constraints.


text:
Q: Random gradient background color i'm trying to get a random gradient background (between 4 colours) on each section.
This is my code:

let colors = ["#ffd0d2","#fffdd0","#d0fffd","#d0d2ff"];
    $(".main").children('section').each(function(){
        let firstGradient = randomNumber(10,90);
        $(this).css(
            "background", "linear-gradient(141deg, "+colors[randomNumber(0,4)]+" "+firstGradient+"%, "+colors[randomNumber(0,4)]+" "+(100-firstGradient)+"%)"
        );
    });
    function randomNumber(min,max){
        return Math.floor((Math.random() * max) + min);
    }
section{
  display:block;
  height:400px;
}

It is so random. Sometimes i get results like this:

When result should be something like this:

A: If you dont try to calculate the remaining % then it seems to work as you expect

let colors = ["#ffd0d2","#fffdd0","#d0fffd","#d0d2ff"];
    $(".main").children('section').each(function(){
        let firstGradient = randomNumber(10,90);
        $(this).css(
            "background", "linear-gradient(141deg, "+colors[randomNumber(0,4)]+" "+firstGradient+"%, "+colors[randomNumber(0,4)] + ")"
        );
    });
    function randomNumber(min,max){
        return Math.floor((Math.random() * max) + min);
    }
section{
  display:block;
  height:200px;
}

A:

let colors = ["#ffd0d2","#fffdd0","#d0fffd","#d0d2ff"];
    $(".main").children('section').each(function(){
        let firstGradient = randomNumber(10,40);
        $(this).css(
            "background", "linear-gradient(141deg, "+colors[randomNumber(0,4)]+" "+firstGradient+"%, "+colors[randomNumber(0,4)]+" "+(100-firstGradient)+"%)"
        );
        "background", "linear-gradient(141deg, #0fb8ad 0%, #1fc8db 51%, #2cb5e8 75%)"
    });
    function randomNumber(min,max){
        return Math.floor((Math.random() * max) + min);
    }
section{
  display:block;
  height:400px;
}

If your first gradient position is bigger then 50%, the second is smaller then first.
for example gradient from red 60% to green 40% will be a straight line.
fixed your randomNumber to always be <50
And obviously you get no blur when gradient from and to are the same color


text:
Q: Is there any way to combine the Slf4jReporter with the metrics-json package to generate JSON in the logs Is there any way to combine the Slf4jReporter with the metrics-json package to generate JSON in the logs?
reporter = Slf4jReporter.forRegistry(registry)
                        .outputTo(logger)
                        .convertRatesTo(TimeUnit.SECONDS)
                        .convertDurationsTo(TimeUnit.MILLISECONDS)
                        .build();

Is there any example of registering the metrics-json with reporter/logger.


text:
Q: 2 lists with mismatch elements. Not sure what to assert and generate pytest cases for mismatched elements '''Here is what I am doing
elements that should be in list1 but NOT in list2 should be ['a']
Code that I have so far'''
list1 = ['a', 'b', 'c']
list2 = ['b', 'c', 'd']

@pytest.mark.parametrize("list1", list1())
@pytest.mark.parametrize("list2", list2())
def test_validation(list1, list2):
    mismatch=[]
    for i in list1:
        if i not in list2:
            mismatch.append(i)
    assert mismatch

'''I am not sure what to assert here such that pytest generates test cases for mismatches. Appreciate your #help please'''

A: Firstly, don't call lists, just specify it. Also you should pass extra argument like expected, to compare with actual result. This is how it should be written:

list1 = ['a', 'b', 'c']
list2 = ['b', 'c', 'd']

@pytest.mark.parametrize("list1, list2, expected", [list1, list2, ['a']])
def test_validation(list1, list2, expected):
    mismatch = []
    for i in list1:
        if i not in list2:
            mismatch.append(i)
    assert mismatch == expected


text:
Q: How to import txt data and replace empty row with null using PowerShell?
Date          Name    Age    Location

21-FEB-2016   Ramon          Makati

22-FEB-2016           17     Quezon

23-FEB-2016   Jose    19

From the above incomplete data, need to have output just like below.
Date,Name,Age,Location
21-FEB-2016,Ramon,Null,Makati
22-FEB-2016,Null,17,Quezon
23-FEB-2016,Jose,19,Null
Just to clarify. I need to have below result.
Date : 22-FEB-2016
Name : Empty(Null)
Age  : 17
Location : Quezon

A: Instead of -replace you can use -match to match any line that contains a expected character (e.g. a-z, A-Z, or 0-9).
(Get-Content -Path 'C:\tmp\CD.txt') -match '[a-zA-Z0-9]'

The output would be input without the empty rows (or without any row, that dows not contain at least one of the expected characters).

A: You say you are trying to import, but you are reading instead by the Get-Content cmdlet use.
You can do the 'Null' thing this way.
$TempFile = [System.IO.Path]::GetTempFileName()
@'
Date          Name    Age    Location

21-FEB-2016   Ramon          Makati

22-FEB-2016           17     Quezon

23-FEB-2016   Jose    19
'@ | Out-File $TempFile

ForEach ($line in (Get-Content -Path $TempFile))
{
    If ($line -eq '')
    {$line -replace $line,'Null'}
    Else{$line}
}

Results

Date          Name    Age    Location
Null
21-FEB-2016   Ramon          Makati
Null
22-FEB-2016           17     Quezon
Null
23-FEB-2016   Jose    19

Are you saying you want the nulls as part of the import?
Why would you want null lines on your working dataset?
Natively, with the true import cmdlet, nulls will simply get removed
Import-Csv -Path $TempFile

Resutls

Date          Name    Age    Location
-------------------------------------
21-FEB-2016   Ramon          Makati
22-FEB-2016           17     Quezon
23-FEB-2016   Jose    19

Remove-Item -Path $TempFile -Force


text:
Q: Timeout when reading response headers from daemon process even after setting WSGIApplication group to Global I am hosting a Django based webpage locally using Apache. However, I am getting the following error :
Timeout when reading response headers from daemon process 'office':var/www/office/office/wsgi.py.
I tried adding the line WSGIApplicationGroup %{GLOBAL} to the conf file, but still getting the same error.
This is my .conf file.
WSGIPythonPath /var/www/office

ServerName office.org
LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so
WSGIApplicationGroup %{GLOBAL}

<VirtualHost 0.0.0.0:80>

ServerAlias www.office.org

DocumentRoot /var/www/example.com/public_html

<Directory /var/www/example.com>
Require all granted
</Directory>
<Directory /var/www/office/office>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess office python-home=/var/www/venv python-path=/var/www/office
WSGIProcessGroup office
WSGIScriptAlias /verify /var/www/office/office/wsgi.py process-group=office

ErrorLog /var/www/logs/error.log
CustomLog /var/www/logs/custom.log combined
</VirtualHost>

This is wsgi.py file:
"""

WSGI config for office project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""

import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "office.settings")
application = get_wsgi_application()

A: I've got the same problem and after a lot of struggling and trying different things, this tutorial helped me to solve the problems.
I created and successfully run the demo project. The problem for me were the paths in the config file and also using the server python version instead of creating a virtual environment for the project.
I hope it will help you

A: I have got the same problem "Timeout when reading response headers" in Flask framework
I resolved it by adding TimeOut 600 in httpd.conf/app.conf
Reference : https://ubiq.co/tech-blog/increase-request-timeout-apache/

A: if this happened on a working server, You can try to force renew Your ssl certificate.
the reason could be found in apache error logs:
Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
helped for me.


text:
Q: Filling Undefined forms with Gradient color SWIFT I am new to programming and I have no idea how I can fill a undefined geometrical form with a gradient color...
I managed to do with a simple color like that:
 func fillRegion(pixelX: Int, pixelY: Int, withColor color: UIColor) {

    var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
    color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

    var newColor = (UInt32)(alpha*255)<<24 | (UInt32)(red*255)<<16 | (UInt32)(green*255)<<8 | (UInt32)(blue*255)<<0

    let pixelColor = regionsData.advanced(by: (pixelY * imageHeight) + pixelX).pointee

    if pixelColor == blackColor { return }

    var pointerRegionsData: UnsafeMutablePointer<UInt32> = regionsData
    var pointerImageData: UnsafeMutablePointer<UInt32> = imageData

    var pixelsChanged = false

    for i in 0...(imageHeight * imageHeight - 1) {
        if pointerRegionsData.pointee == pixelColor {
            pointerImageData = imageData.advanced(by: i)
            if pointerImageData.pointee != newColor {
//                    newColor = newColor + 1
                pointerImageData.pointee = newColor
                pixelsChanged = true
            }
        }
        pointerRegionsData = pointerRegionsData.successor()
    }

    if pixelsChanged {
        self.image = UIImage(cgImage: imageContext.makeImage()!)
        DispatchQueue.main.async {
            CATransaction.setDisableActions(true)
            self.layer.contents = self.image.cgImage
            self.onImageDraw?(self.image)
        }
        self.playTapSound()
    }
}

Pixel by pixel it fill the color (ignoring the black color) any ideas how to do that with Gradient color? thanks!

A: You can make a gradient layer and apply an image or a shape layer as its mask. Here is a playground.
    import PlaygroundSupport
    import UIKit

    class V: UIView {
        private lazy var gradientLayer: CAGradientLayer = {
            let gradientLayer = CAGradientLayer()
            gradientLayer.colors =  [UIColor.red.cgColor,
                                     UIColor.purple.cgColor,
                                     UIColor.blue.cgColor,
                                     UIColor.white.cgColor]
            gradientLayer.locations = [0, 0.3, 0.9, 1]
            gradientLayer.startPoint = CGPoint(x: 0, y: 0)
            gradientLayer.endPoint = CGPoint(x: 0, y: 1)
            gradientLayer.mask = self.strokeLayer
            self.layer.addSublayer(gradientLayer)
            return gradientLayer
        }()

        private lazy var strokeLayer: CAShapeLayer = {
            let strokeLayer = CAShapeLayer()
            strokeLayer.path = UIBezierPath(ovalIn: CGRect(x:0, y: 0, width: 100, height: 100)).cgPath
            return strokeLayer
        }()

        override func layoutSubviews() {
            super.layoutSubviews()
            strokeLayer.path = UIBezierPath(ovalIn: bounds).cgPath
            gradientLayer.frame = bounds

            layer.addSublayer(gradientLayer)
        }
    }
    let v = V(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    PlaygroundPage.current.liveView = v

A: I'm not 100% sure I understand the question, but it seems like you want to fill any-old shape with a gradient, right? If so, there are a couple of ways to do that, but the easiest is to make a gradient that's the same size as the boundary of the shape and then apply that as its color. I'm typing this on my PC so I'm sure there's syntax errors, but here goes...
let size = CGSize(width, height)
UIGraphicsRenderer(size, false, 0) // I KNOW I have this one wrong
let colors = [tColour.cgColor, bColour.cgColor] as CFArray
let colorSpace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors , locations: nil)

Set the colors array as needed and then send that into the UIImage. You can use locations: to change the orientation.


text:
Q: How to read zip file from S3 public bucket without Aws key and secret I have a use case where I have to read a ZIP file and pass it to the creation of lambda as a template.
Now I want to read zip file from a S3 public bucket. How can I read the file from the public bucket?
S3 bucket zip file where I am reading is https://lambda-template-code.s3.amazonaws.com/LambdaTemplate.zip
const zipContents = 'https://lambda-template-code.s3.amazonaws.com/LambdaTemplate.zip';

    var params = {
        Code: {
               // here at below I have to pass the zip file reading it from the S3 public bucket
               ZipFile: zipContents,
        },
        FunctionName: 'testFunction', /* required */
        Role: 'arn:aws:iam::149727569662:role/ROLE', /* required */
        Description: 'Created with tempalte',
        Handler: 'index.handler',
        MemorySize: 256,
        Publish: true,
        Runtime: 'nodejs12.x',
        Timeout: 15,
        TracingConfig: {
            Mode: "Active"
           }
      };
      lambda.createFunction(params, function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else     console.log(data);           // successful response
      });

The above code gives error Could not unzip uploaded file. Please check your file, then try to upload again
How can I read the URL file? And pass it in the params
Can anyone help me here

A: Using the createFunction docs and specifically the Code docs, you can see that ZipFile expects

The base64-encoded contents of the deployment package. AWS SDK and AWS CLI clients handle the encoding for you.

and not a URL of where it is. Instead, you need to use S3Bucket and S3Key.
It is not clear from the docs that public buckets are allowed for this purpose, but the docs do say

An Amazon S3 bucket in the same AWS Region as your function. The bucket can be in a different AWS account.


text:
Q: Proving a given formula for projection matrix In an $n$-dimensional inner product space $V$, I have $k$ ($k\le n$) linearly independent vectors $\{b_1,b_2,\cdots,b_k\}$ spanning a subspace $U$. The $k$ vectors need not be orthogonal. Then I was told that the projection of an arbitrary vector $c$ onto $U$ is given by
$$P_Uc=A(A^TA)^{-1}A^Tc$$
where $A$ is the $n\times k$ matrix with column vectors $\left((b_1)(b_2)\cdots(b_k)\right)$.
My questions are
(1) How to prove that it is the projection? (EDIT: which has been answered, thanks!)
(2) how can one be sure that the matrix $A^TA$ is invertible?

A: The image of $A$ is $U$ so any vector in $y\in U$ may be written as $y=Ax$ with $x\in {\Bbb R}^k$. The orthogonal projection of $c$ onto $y=Ax\in U$ is the one which minimizes the distance from $c$ to $U$, or equivalently such that $c-y$ is orthogonal to the image of $A$. This last condition may be written as:
  $$ A^T (c - y) = A^T(c - Ax)= 0  \ \ \Leftrightarrow \ \ x=(A^T A)^{-1} A^T c$$ from which you deduce
$$ y= A x=A(A^T A)^{-1} A^T c$$
Suppose that there is $x\in {\Bbb R}^k$ so that $A^TAx=0$ whence so that $|Ax|^2 = x^T A^T A x=0$ so we must have $Ax=0$  but the columns in $A$ are linearly independent so $x=0$. The kernel of $A^TA$ is thus trivial and the (square) matrix is invertible.

A: Note that $$P_U = B(B^T B)^{-1}B^T$$ as well, where $B  = [ b_1
\ldots b_k]$.
Since $B $ is full column rank (due to linearly independent vectors $b_i$), then $(B^T B)^{-1}$ exists.


text:
Q: Conditional non-equi join in data.table I have a dataset with some missing data (in reality <1%). We are going to use data from other sites to fill in the missing data. We have a data.table named dt1, which contains the data. We have another data.table named dt2 and this is an index of the sites that can be used to replace (rsite) the missing data from a site. In dt1 I would like to create a column in dt1 named UsedSite that records which site the data we end up using are from.
Create some data to use
dt1<-data.table(site=c("s1","s1","s2","s2"), x=c(NA, 1, NA,1))
dt2<-data.table(site=c("s1","s1","s2","s2"), rsite=c("s3","s3","s4","s4"))

Since only a small fraction of data are missing, start by setting the values of UsedSite to site
dt1[,UsedSite:=site]

The following is where I can't figure out how to do this. I want to just replace the UsedSite values with rsite where x is NA. Not at all surprisingly, the line below replaces everything - I don't want that. I don't understand how to instruct it to consider only lines where a condition (is.na(x)) is being met.
dt1[dt2,UsedSite:=rsite, on=.(site)]

My natural impulse is to try dt1[dt2&is.na(x),UsedSite:=rsite, on=.(site)], but that doesn't work. Thoughts? I would like to stick with the data.table paradigm in this.

A: We may use fcoalesce here to replace the NA values with the corresponding values of 'rsite'  If it is a non-NA, it won't get replaced as fcoalesce will return the first non-NA for each row
library(data.table)
dt1[dt2, UsedSite := fcoalesce(as.character(x), rsite), on = .(site)]

-output
> dt1
   site  x UsedSite
1:   s1 NA       s3
2:   s1  1        1
3:   s2 NA       s4
4:   s2  1        1

Update
dt1[dt2, UsedSite := fifelse(is.na(x), rsite, site), on = .(site)]

-output
> dt1
   site  x UsedSite
1:   s1 NA       s3
2:   s1  1       s1
3:   s2 NA       s4
4:   s2  1       s2


text:
Q: How to add JAR files to a Liberty java web application in Bluemix with WEB-INF missing? i need to add a jar file to a Liberty application in Bluemix. The WEB-INF folder is missing. How can i do that ? Thank you.

A: The WEB-INF folder shouldn't be missing, it should include at least your web.xml configuration file and your lib directory, where the liberty runtime is expecting to find the libraries you want to upload along with your application

A: Your java web application must have a WEB-INF directory.
See http://docs.oracle.com/javaee/6/tutorial/doc/bnadx.html
If you can't find it in your project, you can double click in your liberty in the bluemix console and inspect the liberty instance files, like this

WEB-INF should be at
app->wlp->usr->servers->defaultServer->apps->myapp.war->WEB-INF->libs


text:
Q: Sinusoid and derivative function I have some object whish moves by sinusoid. I have to animate it each time it reaches the top (or the bottom) of the "wave". I want to do this with derivative function: as we know it changes the value (from positive to negative  or contrary) at that points. So the code is:
// Start value
int functionValue = +1;

// Function
float y = k1 * sinf(k2 * Deg2Rad(x)) + y_base;

// Derivative function
float tempValue = -cosf(y);

// Check whether value is changed
if (tempValue * functionValue < 0)
{
   animation = true;
}
functionValue = tempValue;

if I will output the tempValue it shows strange numbers:
0.851513
0.997643
0.0242145
0.690432
0.326303
-0.614262
0.892036
0.1348
0.709843
0.968676
0.0454846
0.920602
-0.423125
0.692132
-0.960107
0.0799654
-0.747722
-0.635241
0.148477
-0.98611
0.900912
-0.877801
0.811632
-0.362743
-0.233856
0.35512
-0.994107
0.885184
-0.468005
0.982489
0.675337
0.661048
0.870765
0.0312914
-0.319066
-0.602956
-0.996169
-0.95627

And animation is strange too. Not only at the top of wave. What's wrong is there?

A: You have
y = a * sin(b * x) + c

derivative of that is
y' = a * b * cos(b * x)

not
y' = -cos(y)

A: You're doing your math wrong. Derivative of sin(x) is cos(x), not cos(sin(x)).
should be
float tempValue = cosf(k2 * Deg2Rad(x));


text:
Q: UISearchBar inside a NavigationBar Get Deferenced When Keyboard Shows Up I'm putting a search bar inside a navigation bar. here is the code
self.navigationBar =[[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 64)];
[self.view addSubview:self.navigationBar];

self.doneButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                           target:self
                                                           action:@selector(doneButtonPressed)];
self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 64)];
self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
self.searchBar.placeholder = @"Name of City";
self.searchBar.delegate = self;

self.searchController = [[UISearchDisplayController alloc]initWithSearchBar:self.searchBar contentsController:self];
self.searchController.delegate = self;
self.searchController.searchResultsDelegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsTitle = @"Add Location";
self.searchController.displaysSearchBarInNavigationBar = YES;
self.searchController.navigationItem.rightBarButtonItems = @[self.doneButton];
self.navigationBar.items = @[self.searchController.navigationItem];

but the search bar behaves incorrectly.

I'm expecting it would look like this

A: I've fixed this by bring the navigationBar to front after setting searchBar as the first responder
[self.searchController setActive:YES animated:NO];
[self.searchController.searchBar becomeFirstResponder];
[self.view bringSubviewToFront:self.navigationBar]; //this is the line I add


text:
Q: Create a dynamic buddupress tab I am trying to create a dynamic buddypress tab linked to a dynamic url that looks like this localhost/wordpress/slug/username
this tab should appear to any user visiting another user's profile,, and when clicked it should redirect to the user visited and not the user visiting , I mean that the username at the end of my URL should be replaced by the username of the current profile visited
I am using the wp_redirect function to redirect the user to this url but the probleme is that i don't know how to write this url ?
I've tried to create a variable like so $user = wp_get_current_user(); to includ it like so wp_redirect( "http://localhost/wordpress/slug/$user->display_name" ); but the final result is http://localhost/wordpress2/slug/ i'm not even sure i should call this function current user so please someone help me
keep in mind that i'm writing my code in the function.php file in my theme folder
thats the code i added
$user = wp_get_current_user();

add_action( 'bp_setup_nav', 'create_tab3', 303 );
function create_tab3() {
    global $bp;
    bp_core_new_nav_item(
        array(
            'name'                    => 'my name',
            'slug'                    => 'slug',
            'position'                => 21,
            'default_subnav_slug'     => 'mySlug', // We add this submenu item below
            'screen_function'         => 'redirect_user_to_tab3',
        )
    );

}
function redirect_user_to_tab3(){
    global $bp;
    wp_redirect( "http://localhost/wordpress2/slug/$user->display_name" );
    exit;
}

Thanks

A: You can't use an object variable, $user->display_name, in a string.
And why would you want a tab that links back to the member being viewed? You're already viewing that member.
This will provide the url of the displayed member: bp_displayed_user_domain()
So you could do this:
function redirect_user_to_tab3(){
    bp_core_redirect( bp_displayed_user_domain() );
}

If you just want the user name for the currently displayed user so that you can build an url, you could do this:
function redirect_user_to_tab3(){
    $url = site_url() . '/slug/' . bp_get_displayed_user_username();
    bp_core_redirect( $url );
}


text:
Q: Android alert dialog good usage I couldn't find anything usefull on the internet about my problem. So my question is how do you do a good usage of Android's alert dialogs. Here is an example of code creating and showing an alert dialog just with the title "error", the text "you can't do that" and a "Ok" button :
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setTitle("Error");
    alertDialogBuilder.setMessage("You can't do that");
    alertDialogBuilder.setCancelable(true);
    alertDialogBuilder.setPositiveButton(
            getResources().getString("ok"),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    alertDialogError = alertDialogBuilder.create();
    alertDialogError.show();

But now, if I have many of this alert dialogs in my application, what should I do ?
Should I set the alertDialogBuilder as an attribute so each time I want to display an error message I can call his function setMessage() and then create() and then show() ?
Should I keep an already configured alertDialog for every single error message I have so I can just call theRightAlertDialog.show() to display my message ?
Something else ?
What's the good usage/cleanest way to do this for you ?

A: You could do this one of two ways. The first is to create a static method, which you can place in a final utility class:
public final class AlertUtil {

    public static void showErrorDialog(Context context, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        builder.setTitle("Error");
        builder.setMessage(message);
        builder.setCancelable(true);
        builder.setPositiveButton(
                getResources().getString("ok"),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        builder.show();
    }
}

Or you can use a DialogFragment which you can create with:
getSupportFragmentManager().beginTransaction().add(ErrorDialogFragment.newInstance(message), "tag").commit()`

I will say though, as a side note; if you are looking to change more than just a few fields for each of the dialogs (i.e. adding more parameters to the showErrorDialog method), then you probably should just stick to the Builder pattern. Considering that is what the Builder pattern is meant for.

A:
Should I set the alertDialogBuilder as an attribute so each time I want to display an error message I can call his function setMessage() and then create() and then show() ?

If the title and the button functionality are the same for all of your alerts, than this would be the best strategy. Create a variable for the alertDialogBuilder, or even just the alertDialog itself, then change the message and show it each time.
Alternatively, you could create a method that builds the dialog, and takes in a string for the message text.


text:
Q: Stokes' Theorem - Vector Field I am having problems trying to verify Stokes' theorem (below) as part of a question.
$$\iint_{S} \text{curl} \vec F \cdot d\vec S=\oint_{c} \vec F \cdot d\vec r$$
The vector field in question is $\vec F=(xy,z^3,xz^2)$ and I am looking over a triangle plane that joins $(0,0,1)$ , $(0,4,1)$ and $(4,0,1). $
Computing the surface integral (over the triangle plane) does not seem to yield the same answer as the closed line integral (taking around the edge of the triangle) so I know I am making a mistake somewhere!
My working is below:
Surface Integral:
Function of plane: $$f(z) = z-1$$
Unit normal to plane:
$$\vec n = \frac{\nabla f}{\mod{(\nabla f)}} = (0,0,1)$$
Also,
$$dS =  dA(0,0,1) \cdot \vec n = dA = dxdy$$
Curl of vector field:
$$ \text{curl} \vec F = (-3z^2,-z^2,-x)$$
Working out the surface integral:
$$ \int \int _ S  \text{curl} \vec F \cdot d\vec S = \int \int _ S  (-3z^2,-z^2,-x) \cdot (0,0,1) dxdy$$
$$ = \int \int _ S  -x dxdy $$
Limits are $x = [0,4]$,$y=[4-x,4]$
$$ = \int^4_0\int^{4-x}_4  -x dydx $$
$$ = \int^4 _0 x^2 dx=\frac{64}{3}$$
Line Integral
Traversing the edges in an anticlockwise direction, I have split the triangle into three lines. $l_1$ from $(0,0,1)$ to $(0,4,1)$ , $l_2$ from $(0,4,1)$ to $(4,0,1)$ and $l_3$ from $(4,0,1)$ to $(0,0,1)$ .
Also,
$$d\vec r = (dx,dy,dz)$$
$l_1$
$$ \int_{l_1}\vec F \cdot d\vec r = \int_{l_1} (xy,z^3,xz^2) \cdot (dx,dy,dz)$$
$$ = \int_{l_1} xydx+z^3dy+xz^2dz $$
Across $l_1$ $x=0$ $dx=0$ $z=1$ $dz=0$ ($y$ varies).
$$ = \int_{l_1} dy $$
$$ = \int_{0}^4 dy $$
$$ = 4 $$
$l_3$
$$ \int_{l_3}\vec F \cdot d\vec r = \int_{l_3} (xy,z^3,xz^2) \cdot (dx,dy,dz)$$
$$ = \int_{l_3} xydx+z^3dy+xz^2dz $$
Across $l_3$ $y=0$ $dy=0$ $z=1$ $dz=0$ ($x$ varies).
$$ = 0 $$
$l_2$
$$ \int_{l_2}\vec F \cdot d\vec r = \int_{l_1} (xy,z^3,xz^2) \cdot (dx,dy,dz)$$
$$ = \int_{l_2} xydx+z^3dy+xz^2dz $$
Across $l_2$ $x$ and $y$ vary, $y=4-x$ $dy=-dx$ $z=1$ $dz=0$ .
$$ = \int_{l_3} x(4-x)dx - \int_{l_3} dx$$
$$ = \int_{0}^4 4x-x^2-1dx $$
$$ = 32-\frac{64}{3}-4 $$
$$ = \frac{20}{3} $$
And so
$$\oint_{c} \vec F \cdot d\vec r = 4 + \frac{20}{3} = \frac{32}{3}$$
Can anyone see where I am going wrong? Hopefully, I am missing something relatively simple!
Thanks!

A: The surface associated to your triangle is defined by: $\lambda_1\in[0,1],\ \lambda_2\in[0,1]$ such that $\lambda_1+\lambda_2\le 1$
$$
t(\lambda_1,\lambda_2)=\lambda_1(v_2-v_1)+\lambda_2(v_3-v_1)+v1=(4\lambda_2,4\lambda_1,1)
$$
the Curvilinear abscissa are:
$$
\gamma_1(\lambda_1,\lambda_2)=\frac{\partial t}{\partial_{\lambda_1}}=(0,4,0)
$$
$$
\gamma_2(\lambda_1,\lambda_2)=\frac{\partial t}{\partial_{\lambda_2}}=(4,0,0)
$$
Thus surface element $dS$ is
$$
dS=\gamma_1\wedge \gamma_2 d\lambda_1d\lambda_2=(0,0,-16) d\lambda_1d\lambda_2
$$
So
\begin{align}
\int\int curl F.dS&=\int_{\lambda_1=0}^1\int_{\lambda_2=0}^{1-\lambda_1} \underbrace{(-3z^2,-z^2,-x)\circ t(\lambda_1,\lambda_2)}_{(-3,-1,-4\lambda_2)} \cdot \underbrace{dS(\lambda_1,\lambda_2)}_{(0,0,-16) d\lambda_1d\lambda_2} \\
&=\int_{\lambda_1=0}^1\int_{\lambda_2=0}^{1-\lambda_1}64\lambda_2d\lambda_1d\lambda_2 \\ &=64\int_{\lambda_1=0}^1\frac{1}{2}(1-\lambda_1)^2d\lambda_1\\&=\frac{32}{3}
\end{align}


text:
Q: Python pandas scatterplot of year against month-day So I have a dataframe with a date column.

date

2021-06-17

2020-06-20

What I want to do is to do a scatterplot with the x-axis being the year, and the y-axis being month-day. So what I have already is this:

What I would like is for the y-axis ticks to be the actual month-day values and not the day number for the month-day-year. Not sure if this is possible, but any help is much appreciated.

A: Some Sample Data:
import pandas as pd
from matplotlib import pyplot as plt, dates as mdates

# Some Sample Data
df = pd.DataFrame({
    'date': pd.date_range(
        start='2000-01-01', end='2020-12-31', freq='D'
    )
}).sample(n=100, random_state=5).sort_values('date').reset_index(drop=True)

Then one option would be to normalize the dates to the same year. Any year works as long as it's a leap year to handle the possibility of a February 29th (leap day).
This becomes the new y-axis.
# Create New Column with all dates normalized to same year
# Any year works as long as it's a leap year in case of a Feb-29
df['month-day'] = pd.to_datetime('2000-' + df['date'].dt.strftime('%m-%d'))

# Plot DataFrame
ax = df.plot(kind='scatter', x='date', y='month-day')
# Set Date Format On Axes
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))  # Year Only
ax.yaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))  # No Year
plt.tight_layout()
plt.show()


text:
Q: Reset a function PHP I have a function which I have to loop it a few times but I'm getting an error of Cannot redeclare function(), is it not possible to loop a function like this, or is it just a problem in my function,
Thanks for your help.
while($i=0){
function gbFunc1($elem){ return (string)$elem['companyCode'][0]; }
    function gbFunc2($elem){ return (string)$elem['locationType'][0][0]->locationDescription->name; }
    function gbFunc3($elem){ return (string)$elem['vehicleRentalPrefType'][0]; }
    function gbFunc4($elem){ return (string)$elem['customerReferenceInfo'][0]->referenceQualifier; }
    function gbFunc5($elem){ return (string)$elem['customerReferenceInfo'][0]->referenceNumber; }
    function vFunc3($elem){ return (float)$elem['rateAmount'][0][1]->rateAmount; }

    $new = Fx::GroupBy($results_array, array('func:gbFunc1', 'func:gbFunc2', 'func:gbFunc3', 'func:gbFunc4', 'func:gbFunc5'), array(null, null, null, null, 'func:vFunc3',));
}

A: You need to declare your functions outside of the loop, otherwise each time the loop iterates it will re-declare the functions again.
function gbFunc1($elem){ return (string)$elem['companyCode'][0]; }
function gbFunc2($elem){ return (string)$elem['locationType'][0][0]->locationDescription->name; }
function gbFunc3($elem){ return (string)$elem['vehicleRentalPrefType'][0]; }
function gbFunc4($elem){ return (string)$elem['customerReferenceInfo'][0]->referenceQualifier; }
function gbFunc5($elem){ return (string)$elem['customerReferenceInfo'][0]->referenceNumber; }
function vFunc3($elem){ return (float)$elem['rateAmount'][0][1]->rateAmount; }

while($i=0){
    $gbF1 = gbFunc1($elem);
    $gbF2 = gbFunc2($elem);
    $gbF3 = gbFunc3($elem);
    $gbF4 = gbFunc4($elem);
    $gbF5 = gbFunc5($elem);
    $vF3 = vFunc3($elem);

    $new = Fx::GroupBy($results_array, array($gbF1, $gbF2, $gbF3, $gbF4, $gbF5), array(null, null, null, null, $vF3,));
}

A: Here are two snippets:
1)
for($i=0; $i<10; $i++)
{
    function squared($a)
    {
        return($a * $a);
    }
    $foo[$i] = squared($bar[$i]);
}

2)
function squared($a)
{
    return($a * $a);
}

for($i=0; $i<10; $i++)
{
    $foo[$i] = squared($bar[$i]);
}

Snippet 1 will generate the "cannot redeclare..." error.  Since, on every iteration you're redeclaring your function squared().
Snippet 2 only declares the squared() function once.
Both snippets call the function 10 times, the difference is in how many times it is declared -- this can only happen once.

A: Or simply:
function groupBy($elem){
    return array('companyCode'=>$elem['companyCode'][0],
                  'locationType'=>$elem['locationType'][0][0]->locationDescription->name,
                  'vehicleRentalPrefType'=>$elem['vehicleRentalPrefType'][0],
                  'referenceQualifier'=>$elem['customerReferenceInfo'][0]->referenceQualifier,
                  'referenceNumber'=>$elem['customerReferenceInfo'][0]->referenceNumber,
                  'rateAmount'=>$elem['rateAmount'][0][1]->rateAmount);
}
$gb=groupBy($elem);
while($i=0){
    $new = Fx::GroupBy($results_array, array($gb['companyCode'],
                                             $gb['locationType'],
                                             $gb['vehicleRentalPrefType'],
                                             $gb['referenceQualifier'],
                                             $gb['referenceNumber'],
                                             $gb['rateAmount']),
                                       array(null, null, null, null, $gb['rateAmount']));
}


text:
Q: jQuery UI Accordion fail in IE8, IE9, and IE10 Pretty strange bug here with jQuery UI Accordion....
Version Info

*

*Internet Explorer 8, 9, and 10 --> with "Compatibility View" turned on.

*jQuery UI 1.10.1

*jQuery Core 1.9.1

Problem Scenario
I have multiple separate accordions vertically stacked.  When I click the header to collapse or expand the accordion on top, the elements below slide up and down like you would expect to make room for the appearing/disappearing content.  However, the header for the accordion directly below stays hovering in place while everything else slides down.  Looks really bad.  When you hover your mouse cursor over this rogue floating header, it snaps back into place where it should have been.
Code
Hopefully I can put up a jsFiddle later, if/when my work unblocks the site (rolls eyes).
For now, here is a simplified version of the code:

Accordion Header 1

                                Some content here 1

Accordion Header 2

                                Some content here 2

Reproduce Bug
To reproduce the bug, simply try to collapse the top accordion by clicking on the header, and you will immediately see the issue.
I have narrowed it down...
I have been able to narrow down the precise issue that is causing this.  If you remove the whitebackground CSS class, the problem vanishes.  Why in the world is this occurring?  Does this seem like a bug to you guys?
Please Read This Last Part
Yes, I need to keep my HTML structure the way it is.  I have greatly simplified it for this example while still maintaining the bug.  Suffice it to say that I do indeed want to keep the TABLE element in place.  No need to suggest removing it.  And I need to have the DIV immediately containing the TABLE be able to specify a CSS background-color as well.  Also, I cannot have users turn off "Compatibility View" in IE, because our AD group policy forces it on for everyone when accessing internal web apps.
Any ideas?

A: This seems to be caused by the position:relative css rule applied to the .ui-accordion-header. Commenting it out seems to fix the issue in IE compatibility mode.
.ui-accordion .ui-accordion-header {
    display: block;
    cursor: pointer;
    /*position: relative;*/
    margin-top: 2px;
    padding: .5em .5em .5em .7em;
    min-height: 0; /* support: IE7 */
}

However, this causes the header icons to show up in the wrong place. You'll have to tweak their css to compensate. There could be other side-effects as well.


text:
Q: Issues while streaming on MediaPlayer SDK8 I'm streaming a live radio url directly through Mediaplayer in a service (SDK 8 and above). Some clients are saying that they are hearing some blips and bloops in between the stream. I'm not doing anything different here and just allowing the MediaPlayer to play the audio. Can someone tell me why is this happening?
-Hari

A: i'm not sure if it's gonna help, but i can tell you the way i play using http streaming for a mp3, for example:
1: the code
mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
mediaPlayer.start();

2: the .pls file
This URL is from BBC just as an example. It was an .pls file that on linux i downloaded with
wget http://foo.bar/file.pls

and then i opened with vim (use your favorite editor ;) and i've seen the real URLs inside this file. Unfortunately not all of the .pls are plain text like that.
tested with android 1.6 and 2.2.


text:
Q: Find the non existing values in an array and inserting them to the array I have the following array
var array = {"week1":[{"id":1,"name":"x","mark":"20"},{"id":2,"name":"y","mark":"30"}],"week2":[{"id":1,"name":"x","mark":"40"},{"id":2,"name":"y","mark":"60"},{"id":3,"name":"z","mark":"10"}]}

and I also have an array of student Ids as follows
var studentId = ["1","2","3"]

I want to iterate through array and insert the missing student ids into each week and set mark as zero.
var keys = Object.keys(array);
                for(var x =0; x<studentId .length; x++)
                    {
                        var boolFlag = false;
                        for(var i=0; i<keys.length;i++)
                        {
                            for(var j=0; j=array [keys[i]].length; j++ )
                            {

                                if(studentId [x].id == array [keys[i]][j].id)
                                {
                                    boolFlag = true;
                                    break;

                                }
                            }
                        if(!boolFlag )
                            {
                                array [keys[i]].push({id:studentId [x].id, mark:0});
                            }
                        }
                    }

This works if all the weeks don't contain a studentId completely. But if any of the weeks contain the studentId then this is not inserting the id correctly.What is wrong in my code?
expected result:
var result =   {"week1":[{"id":1,"name":"x","mark":"20"},{"id":2,"name":"y","mark":"30"},{"id":3,"mark":"0"}],"week2":[{"id":1,"name":"x","mark":"40"},{"id":2,"name":"y","mark":"60"},{"id":3,"name":"z","mark":"10"}]}

UPDATE
var studentId = [{id:"1", name:"x"},{id:"2", name:"y"},{id:"3", name:"z"}]

A:

var array = {
  "week1":[
    {"id":1,"name":"x","mark":"20"},
    {"id":2,"name":"y","mark":"30"}
  ],
  "week2":[
    {"id":1,"name":"x","mark":"40"},
    {"id":2,"name":"y","mark":"60"},
    {"id":3,"name":"z","mark":"10"}
  ]
};
var studentId = [
  {id:"1", name:"x"},
  {id:"2", name:"y"},
  {id:"3", name:"z"}
]

for(var week in array){
    for(var stId of studentId){
        var weekVal = array[week];
        if(!weekVal.filter(function(st){ return st.id == stId.id; })[0])
            weekVal.push({id:stId.id, name: stId.name, mark:"0"});
    }
}

console.log(array);


text:
Q: How to add a button dynamically in collection view and name it dynamically from user input (Swift 4)? I am trying to create a notes app
In which there will be a collection view and user can type category name and click ok, and it will be added to the array and listed as last item in collection view.
How do I implement button in collection view and make it clickable to display tableview (To list sub item list)


text:
Q: Express Validator - dynamic form field validation <input name="foo[]" ... >

I've used these before, but I'm wondering what it is called and results in various Google results only call it an "array" but I want to validate multiple fields in Express API which have dynamically added from the frontend side.
Frontend HTML:
<form>

            <title>Person 1:</title>
            First name
            <input name="first_name[]">

            Last name
            <input name="last_name[]">

            Email
            <input name="email[]">

            <title>Person 2:</title>
            First name
            <input name="first_name[]">

            Last name
            <input name="last_name[]">

            Email
            <input name="email[]">

    <button type="button">Add new person</button>
    <button type="submit">Submit</button>
</form>

In Express API, I am using express-validator to validate my fields. I want to validate request object on Express API where all fields must have equal number of elements on each array (first_name,last_name,email, etc..), and also each array have a different type of datatype like email should be validated as Email and other should be as String.
Request Object on Backend:
{
    "first_name[]": [
        "foo1",
        "foo2",
    ],
    "last_name[]": [
        "foo1",
        "foo2",
    ],
    "email[]": [
        "foo1",
        "foo2",
    ]
}


text:
Q: What is the response received by IE for a duplicate post? If you visit an aspx web form, and click the submit button causing a POST to the server, then click submit again causing a second POST before receiving a response from the first POST, what happens in terms of the response? Does the server process both requests simultaneously or serially? Does the server send both responses? Does the browser ignore one of the responses? This may be self explanatory after an answer to the previous questions, but if I were to call Response.Clear(); Response.End(); for the second request, what would happen on the browser end?

A: If there are no special means at the server side to handle multiple POSTs, the server will handle both requests independently. Whether or not the processing is concurrent - it depends:

*

*if your first POST causes the whole page to reload then it is impossible to trigger the second POST before the page is processed at the server side (because your second click is made from the page which is already at the client side)

*if your first POST causes an AJAX POST to the server and the processing takes some time at the server then it is possible that you end up with two POSTS from the same page processed concurrently at the server side

The server always sends responses and browsers do not ignore them. It is your code, at the server side or at the client side, to prevent such unintended multiple POSTs, for example by 302ing the response to another location which doesn't allow the user to rePOST the form.
Specifically, if you just clear the response (send an empty content) and the content type is text/html then the browser will render an empty page.

A: I would say just about any of those things could happen, depending on the exact timing.
I believe calling Response.Clear(); Response.End(); on the second request would cause an empty response which the browser would receive, possibly after receiving the results of the first request.


text:
Q: Integration of code generators in CI / CD pipeline In my company, I'm currently working on a project with some (REST) web services involved. The development is based on the OpenAPI specification and the Swagger tooling. The target platform is an internal cloud platform based on OpenShift.
As we make use of an CI/CD pipeline in our software development process (more or less the whole Atlassian Toolchain, Artifactory, etc) the question rises whether is possible to neatly integrate a code generation step in the pipeline.
The API development process right now is basically like this:

*

*Write / Modify API specification

*Commit changes into SCM

*Validate spec and generate API documentation

The process to develop (e.g. the server) against the API spec is like this:

*

*Local generation / update of server stubs

*Commit into SCM

*Server code is then implemented against the generated and checked in stubs

The question is, whether this is the go to solution to work with a code generator in general. I have the subtle feeling that the local generation of code is not the best solution here, as one have to update the SCM on a regular basis with newly generated stubs to be up to date with changes in the API specification.
One idea that came in to my mind is to make e.g. use of an artifact repository manager (like Artifactory). The build process could then create a server stubs library based on the API spec which is pushed into the artifact manager. Developers can than make use of their local build system to update the dependency. However, this process might be an overkill.
As I could not find good resources about the integration of code generators in a software development process using CI/CD pipelines, I'm very interested in best practices here (or maybe there is a good specific solution for my previously described example?).

A:
Should the local build environment of a developer be responsible to do code generation?

Yes.  Where else would you do it?  If you don't do it there, your program won't run properly in the IDE.  If your program doesn't run properly in the IDE, you can't test and debug it locally.
As an example, we use Fody.PropertyChanged to code-generate an INotifyPropertyChanged implementation for our View Model classes.  The code generation is kicked off as part of the IDE's build process.
Our build server repeats this code generation process when it does its build and tests.

Should generated code be part of the project's code repository?

No.  You didn't write it.  The purpose of a code repository is to store, maintain and keep track of code that you write.  Code that is generated from a tool is not interesting in this way.  Code that generates code might be.
We don't store the code that Fody generates, because the whole point of that code generation is to abstract away those details.  The [AddINotifyPropertyChangedInterface] attribute that triggers this code generation is stored in source control instead.
Assuming that the generated code "takes care of itself" there is no need to store it in source control, but there are exceptions.  For example, you might still store SQL scripts that you generated from a tool such as Sql Server Management Studio in the code repository, if you don't have an automated step that synchronizes database changes for you.


text:
Q: Can't select points with a rectangle (ArcMap) I am using ArcGIS 10.2, ArcMap and I have a shapefile point layer in which I can't select any points.  (I'm having the same problem this person describes but none of the suggested solutions work:
Why is select by drawing a rectangle not working in ArcGIS?)
To simplify things, I have removed all other layers from the map.  I have highlighted the layer in the table of contents.  I have also done: right-click > Selection > 'Make this the only selectable layer in the table'.  I have tried lasso, rectangle, polygon, with no luck.  When I add a polygon layer to the map, I'm able to select polygons with these tools. I also added a different point layer to the map and was able to select those points.  But there's something about this point layer. It's in GCS_WGS_1984, not that that should have anything to do with it (also the polygon layer that I can select is in in GCS_WGS_1984 too).
Any additional suggestions?

A: This sounds like it could be one of many things.  One thought though is to go into the settings of your interactive selection settings menu in the MXD  (Selection > Interactive Selection Method) and within that sub-menu make sure the correct option is selected, you'd most likely want Create New Selection.  If that got changed it could be actually working correctly by not selecting anything, if for example it was set to remove from current selection, then every time you try and select features it would be trying to unselect those features.
Also, again, I don't know if this is your particular problem or not, but you may want to go to Selection > Selection Options and make sure the the settings there make sense for your use case.  One thing of particular note I think for you would be, if your points are actually multi-point features, then you definitely need to check that it is set to select features partially or completely within the box or graphic.  If you don't have this set correctly and it's multi-point features, you may be having issues because not all of the points for each feature are within the selection area.
I know these aren't the only two possible causes by any means, and from the steps you say you took checking with other datasets I doubt these are it, but, as I don't know the specifics of your situation, it doesn't hurt to try anyway.
Definitely listen to the two comments on your question though, do run the check geometry tool and, if necessary, the repair geometry.  Also, do try viewing it in another MXD; and I do not mean dragging/copying the layer from your current MXD and dragging/pasting it into a new MXD, I mean actually opening a new MXD and going to add data and adding the data from source.
Also, if none of this works, just for testing purposes at least, try converting/exporting the dataset in question to a different format and test it there (ex: if it is currently a shapefile, export to a FileGDB feature class, if it is a FileGDB feature class, export to a shapefile.  This way you can at least tell if it is a problem with the data it self, or if it is a problem with just that file.

A: Same thing happened to me and it was because the shapefile was joined to an excel table. It seems like the "Select by Location" tool does not work over a shapefile that has a join. once I removed the join, the selection tool worked as expected.

A: I'm sure this was solved already one way or the other, but I was having the same problem.  I imported an XY Event layer and was unable to select any of the points from that layer.  The data was all there and the points located correctly, so it was a puzzler.
My solution was to reproject the new XY layer into the coordinate system being used in the current map. That solved it for me.

A: Same thing happened to me, and the same solution worked.  I am in ArcMap 10.3.1 and both running Select by Location in a model in Model Builder, and running a Select by Location manually would only select some of the features that fell within the parameters.
Closing ArcMap and reopening did the trick!


text:
Q: Ideal transformer output voltage I know that the output voltage and current of an ideal transformer depends on the number of wounding of the coils. It means that no matter how many resistors I put in a series in my secondary loop, the current would not change and it depends only on N (Number of turns in coil).
I have been thought that resistors define the current that flow through them and it is hard to look at the current independent of the load.
Could someone explain the physics behind v1/v2=N1/N2
So is it safe to assume that the current in secondary coil acts as an ideal current source because if I know the source current I can get the secondary loop current no matter what the load of the secondary circuit is

A: Could someone explain the physics behind v1/v2=N1/N2
In a transformer electric energy is converted into magnetic energy and then back to electric energy.
The formula V1 / V2 = N1 / N2
applies to this process without any losses.
Losses can occur due to:

*

*Resistance of the transformer wires

*Saturation of the magnetic core of the transformer

*Inductance of the transformer (a transformer is also a coupled inductor)

*frequency of the AC signal fed to the transformer
So the formula V1 / V2 = N1 / N2  does apply but it only applies to an ideal transformer.
Also an ideal transformer does not lose any power nor will it add any. So that means:
P1 = P2 and also V1 * I1 = V2 * I2
If you would connect a current source to one side of the transformer then the relation will still hold however you must make sure that the current on the other side of the transformer can flow so you must apply a load or short it.
This is the opposite of connecting a voltage source at the primary side, you are expected to have a load at the secondary side or leave it open, but you're not allowed to short the V2 side !


text:
Q: What is difference between httpS and http/2? I'm trying to understand what is the difference between HTTPS and http/2?
If I'm going to build a Node.js/express app, what should I use?
Can I use HTTPS with http/2?
Maybe if I use HTTPS, I don't need http/2 because it's the same, or HTTPS use http/2 under the hood?
I'm confused.
Someone is linked to me "difference between HTTP 1.1 and HTTP 2.0 [closed]", but I understand the difference between HTTP and HTTP2. I'm asking about HTTPS and HTTP/2

A: HTTP - A protocol used by clients (e.g. web browsers) to request resources from servers (e.g. web servers).
HTTPS - A way of encrypting HTTP. It basically wraps HTTP messages up in an encrypted format using SSL/TLS. The web is moving towards HTTPS more and more and web browsers are starting to put more and more warnings when a website is served over unencrypted HTTP. Unless you have a very good reason not to, use HTTPS on any websites you create now.
Digging into HTTP more we have:
HTTP/1.1 - this was the prevalent format of HTTP until recently. It is a text-based protocol and has some inefficiencies in it - especially when requesting lots of resources like a typical web page. HTTP/1.1 messages can be unencrypted (where web site addresses start http://) or encrypted with HTTPS (where web site address start with https://). The client uses the start of the URL to decide which protocol to use, usually defaulting to http:// if not provided.
HTTP/2 - a new version of HTTP released in 2015 which addresses some of the performance issues by moving away from a text based protocol to a binary protocol where each byte is clearly defined. This is easier to parse for clients and servers, leaves less room for errors and also allows multiplexing. HTTP/2, like HTTP/1.1, is available over unencrypted (http://) and encrypted (https://) channels but web browsers only support it over HTTPS, where it is decided whether to use HTTP/1.1 or HTTP/2 as part of the HTTPS negotiation at the start of the connection.
HTTP/2 is used by about a third of all websites at the time of writing (up to 50% of websites as of Jan 2020, and 67% of website requests). However not all clients support HTTP/2 so you should support HTTP/1.1 over HTTPS and HTTP/2 over HTTPS where possible (I believe node automatically does this for you when using the http module). I do not believe HTTP/1.1 will be retired any time soon. You should also consider supporting HTTP/1.1 over unencrypted HTTP and then redirect to HTTPS version (which will then use HTTP/1.1 or HTTP/2 as appropriate). A web server like Apache or Nginx in front of Node makes this easy.
HTTP/3 - the next version of HTTP, currently under development. It is expected to be finalised in 2020 though it will likely be late 2020 or even 2021 before you see this widely available in web servers and languages like node. It will be built on top of a UDP-based transport called QUIC (rather than the TCP-based protocol that HTTP/1.1 and HTTP/2 are based on top of). It will include part of HTTPS in the protocol so HTTP/3 will only be available over HTTPS.
In short you should use HTTP/1.1 over HTTPS, should consider HTTP/2 as well if easy to implement (not always possible as not quite ubiquitous yet - but getting there) and in future you might be using HTTP/3.
I suggest you get a firm understanding of all of these technologies (except maybe HTTP/3 just yet) if you want to do web development. It will stand you in good stead.


text:
Q: jquery submit with function does not work on the on-click button event binded to an object Using the normal $(selector).submit(), but when I added a function inside the submit method it does not execute the codes inside.
Here is the snippet of the code:
onCreated: function() {
    this.footer = jQuery('
');
    this.submitButton = jQuery('<button class="jBox-btn jBox-btn-lg jBox-btn-save btn btn-primary btn-md"/>')
      .html("Login ").appendTo(this.footer);
    this.footer.appendTo(this.container);
  },
  onOpen: function() {
    this.submitButton.off('click.jBox-Modal' + this.id).on('click.jBox-Modal' + this.id, function() {

      $("#bulk-login").submit(function(e) {
        alert('test');
      });

    }).bind(this);
  }

I'm not sure what causes the problem why it's not executing the inner code for the sumbit. Could anyone tell me what might be the problem?

A: You will need to set the button type to submit in order for it to trigger a submit event on your bulk-login form:

this.submitButton = jQuery('<button type="submit" class="jBox-btn jBox-btn-lg jBox-btn-save btn btn-primary btn-md"/>')
      .html("Login ").appendTo(this.footer);


text:
Q: Failure in changing node content + JavaScript I wrote this code for create menu with div tag
HTML:

choose▼

JavaScript:

This code creates the menu, but when I click on the menu items code breaks.
The error is:

"parent is null"

A: To pass the id to the function you need to ensure that you put quotes around the id:
node.setAttribute("onclick","select('"+id+i+"')");
// note the single quotes ----------^--------^

Demo: http://jsfiddle.net/QK5Wh/1/
But you don't need to use the id to get the element when you can pass a direct reference to the element itself:
node.setAttribute("onclick","select(this)");

And then:
function select(p) {
    p.style.backgroundColor="red";
    var t = p.innerHTML;
}

Demo: http://jsfiddle.net/QK5Wh/

A: I'll suggest to avoid the inline event binding. Here is a working example:
http://jsfiddle.net/H4S2f/1/
function ccc() {

 var id="firstMenu";
 var cls="firstMenuList";
 var ar=new Array("hi","there","hello","world");
 var node=document.createElement("div");
 var parent=document.getElementById("menulist");
 var nodeData="";

 for (var i=0;i<ar.length;i++)
 {
    var node=document.createElement("div");
    node.setAttribute("id",id+""+i);
    node.setAttribute("class","menulist");
     (function(i) {
         node.addEventListener("click", function() {
             select(id+""+i)
         });
     })(i);
    node.style.top=((i+1)*100)+3+"%";
    node.innerHTML=ar[i];
    parent.appendChild(node);

 }
}

function select(id)
{
 var p=document.getElementById(id);
 p.style.backgroundColor="red";
 var t = p.innerHTML;
}

ccc();


text:
Q: How to test that Flask is using test_client rather than client? I'm using Pytest fixtures with Flask. My application is instantiated using an application factory.
#conftest.py

@pytest.fixture(scope='session')
def app(request):
    '''Session-wide test application'''
    app = create_app('testing')
    app.client = app.test_client()
    app_context = app.app_context()
    app_context.push()

    def teardown():
        app_context.pop()

    request.addfinalizer(teardown)
    return app

I wanted to verify that the app created by my fixture uses Flask's built-in test_client, so I wrote a test:
#test_basics.py

def test_app_client_is_testing(app):
    assert app.client() == app.test_client()

When I run this test, I get: TypeError: 'FlaskClient' object is not callable
What am I doing wrong?
Is the test incorrect, or is the fixture incorrect?

A: app.client is already an instance, you shouldn't call it again.  Ultimately, this test makes no sense.  Of course client is a test client, that's how you just created it in the fixture.  Also, the clients will never be equal, they are different instances.
from flask.testing import FlaskClient

assert app.client == app.test_client()  # different instances, never true
assert isinstance(app.client, app.test_client_class or FlaskClient)  # still pointless, but correct

What you probably want is two fixtures: app and client, rather than creating a client on the app.
@pytest.yield_fixture
def app():
    a = create_app('testing')
    a.testing = True

    with a.app_context():
        yield a

@pytest.yield_fixture
def client(app):
    with app.test_client() as c:
        yield c

from flask.testing import FlaskClient

def test_app_client_is_client(app, client):
    # why?
    assert isinstance(client, app.test_client_class or FlaskClient)


text:
Q: foreach loop not showing data I am having a strange issue with the output of data for my foreach loop.  The loop is not showing the data for the $image->thumbname,$description or $id but the print_r($get_images); works fine
Print_r Output:
Array ( [0] =>
    Array ( [id] => 1
            [description] => testing
            [imagename] => test.jpg
            [thumbname] => test_thumb.jpg
) )

View:
<?php if(is_array($get_images)): ?>
    <? print_r($get_images); ?>
        <?php foreach($get_images as $image): ?>
        <img src ="<?=base_url()?>includes/uploads/gallery/thumbs/<?=$image->thumbname?>" alt="<?= $image->description?>"> <a href="deleteimage/<?=$image->id?>">Delete
        <?php print_r($image); ?>
    <?php endforeach; ?>
<?php endif; ?>

A: youre using -> to access the array contents youre supposed to use []
<?php if(is_array($get_images)): ?>
    <? print_r($get_images); ?>
        <?php foreach($get_images as $image): ?>
        <img src ="<?=base_url()?>includes/uploads/gallery/thumbs/<?= $image['thumbname'] ?>" alt="<?= $image['description'] ?>"> <a href="deleteimage/<?= $image['id'] ?>">Delete
        <?php print_r($image); ?>
        <?php endforeach; ?>
<?php endif; ?>

A: You have an array from what I can tell:
$image['thumbname']

A: That should be $image["thumbname"] and not $image->thumbname.


text:
Q: Unique Building Identifier (UBID) ArcGIS toolbox The Department of Energy created an open-source unique building identifier (UBID) creation technique which I would like to use for my organization's management of building inventory data.

*

*https://buildingid.pnnl.gov/

*https://www.energy.gov/eere/buildings/unique-building-identifier-ubid

*https://github.com/pnnl/buildingid-py
We have a building footprint layer and would like to generate UBIDs using this file, but the process is convoluted and annoying. I believe it would be beneficial to the GIS community to create an ArcGIS toolbox, using the Python-based code, to streamline the process and make the UBID more widely used.
If I wanted to do this myself, how would I proceed?


text:
Q: Subprocess or import to invoke a script in Python I have a script task.py that I am trying to invoke. It seems there are two ways to do that. One is to use the subprocess API while the other is to use Python's import mechanism.
task.py
def call_task():
    print("task in progress...")
    return "something"

print("calling task..")
out = call_task()
print("output of the executed task::", out)

Now, we have two approaches to invoke the above task.py python script.
Approach 1
import task as task

print("invoke call-task")
out = task.call_task()
print("output::", out)

Approach 2
import subprocess, shlex, PIPE

proc = subprocess.Popen(shlex.split("python task.py"), stdout = PIPE)
out = proc.communicate()
print("output::", out)

Although both approaches work, which approach is more pythonic?

A: Running a separate Python process from Python is frequently an antipattern. There are situations where you specifically want two Python instances (for example, if the module you want to use requires its own signal handling etc) but in the absence of factors which force the other choice, import is generally vastly preferrable in terms of usability (you get to call the functions inside the package in an order different from its main flow, and have more fine-grained control over the internals) and performance (starting a separate process is almost always a bad idea if you can avoid it).

A: While "The subprocess module allows you to spawn new processes" which executes the code within your task.py,
importing will result in the original process executing your code.
Other than that, it should be identical.
You can read more about it in the Python Subprocess Docs
As i've seen, its rather unusual to execute python code using an extra subprocess.
It may benefit performance wise but the more pythonic way would be importing i guess.


text:
Q: Flash automatically names objects on stage "instance#" I have 2 TLF text boxes already placed on my main stage. In the property inspector window I give these the instance names: "txt1" and "txt2".
I am trying to have a single mouseup event, and figure out which text box it occurred on.
My document class has the following code:
package  {
import flash.display.Sprite;
import flash.events.KeyboardEvent;

public class SingleEvent extends Sprite{

    public function SingleEvent() {
        // constructor code
        root.addEventListener(KeyboardEvent.KEY_UP, textChanged,false,0,true);
    }

    private function textChanged(e:KeyboardEvent){
        trace(e.target.name);
        trace("   " + e.target);
        switch(e.target){
            case txt1:
                trace("txt1 is active");
                break;
            case txt2:
                trace("txt2 is active");
                break;
            default:
                break;
        }
    }

    }
}

Example output is:
instance15
   [object Sprite]
instance21
   [object Sprite]

Since the objects are already on the stage, I am not sure how to get flash to recognize them as "txt1" and "txt2" instead of "instance#". I tried setting the .name property, but it had no effect.
In the publish settings, I have "Automatically declare stage instances" checked.
Also, is it possible to have a single change event for multiple slider components? The following never fires:
root.addEventListener(SliderEvent.CHANGE, sliderChanged,false,0,true);

Thanks for any tips

A: It seems that the Flash Player hasn't initialized the TLFTextFields by the time the constructor is called.  Try this:
package  {

    import flash.display.MovieClip;
    import flash.utils.describeType;
    import flash.events.Event;

    public class TestTLF extends MovieClip {

        private function onEnterFrame (ev:Event) : void {
            removeEventListener (Event.ENTER_FRAME, onEnterFrame);
            for (var i:int = 0; i < numChildren; i++) {
                var obj:Object = getChildAt(i);
                trace (obj.name + ":"+describeType(obj));
            }
        }

        public function TestTLF() {
            addEventListener (Event.ENTER_FRAME, onEnterFrame);
        }
    }

}

You will find that in addition to the mysteriously created additional objects "__id#" and "instance#", both of your TFLTextFields are recognized.
Also, your Slider components obviously don't "bubble" their SliderEvents, which means they never reach the root object.  You can, however assign a handler function as many times as you want, so you could just add listeners to each of your sliders, all referring to the same sliderChanged function.


text:
Q: Showing Convergence in measure with some condition.
Let $(X,M,m)$ be a finite measurable space and $\{f_n\}$ be a sequence of real valued measurable functions on $X$ . Let $$E_n=\{x\in X : f_n(x)\ne 0\}$$ for every $n\in \mathbb{N}$ .
  Show that if $ E_n \cap E_m =\emptyset $ for every $n\ne m$ then $f_n\to f $ in measure $m$

A: Let $D_n = \cup_{k=1}^n E_k$, then $m(D_n) = \sum_{k=1}^n m(E_k)$, $m(D_n)$ is bounded by $m(X)$ and it is increasing, so it is a Cauchy sequence, which means for any $\epsilon > 0$, $\exists N$ such that for all $n > N$ we have $m(E_n) < \epsilon$.
Now remark that $\{ |f_n -0| \geq \epsilon\} \subset \{f\neq 0\} = E_n$, so $f_n$ converge to $f=0$ in measure


text:
Q: Different Box Plot Series Traces Within Plotly Subplots I am trying to create a series of sub plots each containing box plots using Plotly. At the moment I have managed to create the following plot;
.
Unfortunately, this is not exactly what I want. I would like to create a subplot for S1 and S2 rather than A1 and A2 (such that each sub plot will have a green box plot and a red box plot).
Is this possible?
This is my current code.
x = ['S1', 'S1', 'S1', 'S1', 'S1', 'S1',
     'S2', 'S2', 'S2', 'S2', 'S2', 'S2']

trace0 = go.Box(
    y=[1.935, 2.59, 2.97, 2.97, 3.28, 4.315, 1.935, 2.59, 2.97, 2.97, 3.28, 4.315],
    x=x,
    name='A1',
    marker=dict(
        color='#3D9970'
    )
)
trace1 = go.Box(
    y=[0.6, 0.7, 0.3, 0.6, 0.0, 0.5, 0.7, 0.9, 0.5, 0.8, 0.7, 0.2],
    x=x,
    name='A2',
    marker=dict(
        color='#FF4136'
    )
)
fig = tools.make_subplots(rows=1, cols=2)
fig.append_trace(trace0, 1, 1)
fig.append_trace(trace1, 1, 2)
py.iplot(fig)

A: I know it's late for the answer however for anyone out there that currently need this the issue was that if you want to compare S1 and S2 you should use a different X for each graph.
`from plotly.subplots import make_subplots
import plotly.graph_objects as go

x = ['S1', 'S1', 'S1', 'S1', 'S1', 'S1',
     'S2', 'S2', 'S2', 'S2', 'S2', 'S2']

trace0 = go.Box(
    y=[1.935, 2.59, 2.97, 2.97, 3.28, 4.315],
    x=[i+'_A1' for i in x[:6]],
    name='S1_A1'
)

trace1 = go.Box(
    y=[0.6, 0.7, 0.3, 0.6, 0.0, 0.5],
    x=[i+'_A2' for i in x[:6]],
    name='S1_A2'
)

trace2 = go.Box(
    y=[1.935, 2.59, 2.97, 2.97, 3.28, 4.315],
    x=[i+'_A1' for i in x[6:]],
    name='S2_A1'
)

trace3 = go.Box(
    y=[0.7, 0.9, 0.5, 0.8, 0.7, 0.2],
    x=[i+'_A2' for i in x[6:]],
    name='S2_A2'
)

fig = make_subplots(rows=1, cols=2)

### First subplot ###
# S1_A1
fig.append_trace(trace0, row = 1, col = 1)
# S2_A2
fig.append_trace(trace1, row = 1, col = 1)
#### Second subplot ###
# S1_A1
fig.append_trace(trace2, row = 1, col = 2)
# S2_A2
fig.append_trace(trace3, row = 1, col = 2)

fig.show()´

Removed the colours that you got for plotly to use different ones


text:
Q: Sort a list in C# I have created a list that with 3 different values I want to  order the list with one kind of the values. I have done this
      PriorityQueueList.OrderBy(x => x.pQPrioirty).ToList();

but is not odering any thins it just showing me the values according to want I have them in the list
     public class Node
    {
         public int name {get; set;}
         public int pQTime { get; set; }
         public int pQPrioirty { get; set; }

        public Node(int _Name, int _PQ, int _PQP)
       {
        this.name = _Name;
        this.pQTime = _PQ;
        this.pQPrioirty = _PQP;
    }
     }

               List<Node> PriorityQueueList = new List<Node>();

               for (int x = 0; x < nodesNumber; x++)
                {
            Label lblName = new Label();
            NumericUpDown numiNumber = new NumericUpDown();

            xCoor = coor.Next(0, 700);
            yCoor = coor.Next(0, 700);

            if (!randomListxCoor.Contains(xCoor))
            {
                randomListxCoor.Add(xCoor);

            }
            if (!randomListyCoor.Contains(xCoor))
            {
                randomListyCoor.Add(yCoor);

            }

            prioritySaver = pQueuNumbers.Next(1, nodesNumber * 3);

            numiNumber.Name = x.ToString();
            numiNumber.Location = new Point(xCoor, yCoor);
            numiNumber.Size = new Size(50, 15);
            numiNumber.Maximum = 100;
            numiNumber.Minimum = 0;

            lblName.Location = new Point(xCoor + 10, yCoor + 15);
            lblName.Text = x.ToString();
            lblName.ForeColor = System.Drawing.Color.Black;
            lblName.AutoSize = true;

            this.pnlNodes.Controls.Add(lblName);
            this.pnlNodes.Controls.Add(numiNumber);

            numberControls.Add(x, 0);
            waytosave.Add(x, 0);
            savePriority.Add(x, prioritySaver);
            Node Node = new Node(x, 0, prioritySaver);
            this.PriorityQueueList.Add(Node);
                }

      private void RunManualPriorityQueue(int nodesNumber)
    {

        PriorityQueueList.OrderBy(x => x.pQPrioirty).ToList();

            }

I am getting the values from the  numricaUpDown I have done the checking for the change in the values. Everything is just work fine just the sorting it is possible to use
              PriorityQueueList.OrderBy(x => x.pQPrioirty).ToList();
to  sort  the list but why it is not sorting according to the priority. I am building the Priority Queue

A: That method returns an ordered list, which you do not store anywhere. Try
PriorityQueueList=PriorityQueueList.OrderBy(x => x.pQPrioirty).ToList();

A: You aren't assigning the sorted results back to the list. Try this:
private void RunManualPriorityQueue(int nodesNumber)
{
    PriorityQueueList = PriorityQueueList.OrderBy(x => x.pQPrioirty).ToList();

Or you can do an in-place sort using List<T>.Sort Method (Comparison<T>) which would probably be more efficient.