text:
Q: create object in for loop I have the following for loop, in this foor loop I create an object kw.
The class keywords (string, vector<pair<int,string>>, vector<string>)

for(size_t i = 0; i < names.size();i++)
{
      Keywords kw (names[i].c_str(),vreg, stopWords);
      Document d = kw.extractKeywords();
      v_doc.push_back(d);
}

I think that there is a problem in this for loop. I thought that it might be better if i take the Keywords out of the for loop, since i just need to create that object once.
Keywords kw (vreg, stopWords);
    for(size_t i = 0; i < names.size();i++)
    {

          Document d = kw.extractKeywords(names[i].c_str());
          v_doc.push_back(d);
    }

When I do that I don't get the right output. Can you please give me a hint thank you.
Hani.
This class is being used to extract keywords out of an xml File. I provided the:

*

*Class constructor

*Copy Constructor

*Setters and getters

*Destructors

Do you think that there is a problem in the copy constructor
Keywords::Keywords(string xmlF,vector<pair<int, string>> re,vector<string> sw)
{
    // Setter for string: the path of the xml File
    setXml(xmlF);
    // Setter for the vector<pair<int, string>> re
    setRegularExpression(re);
    //setter for vector<string> sw
    setStopWords(sw);
}

//FREE MEMORY
Keywords::~Keywords()
{

    sw.clear();
    vreg.clear();
}

void Keywords::setRegularExpression(vector<pair<int, string>>   re)
{
    vreg = re;
}

vector<pair<int, string>>   Keywords::getRegularExpression()
{
    return vreg;
}

void Keywords::setStopWords(vector<string> s)
{
    sw = s;
}

vector<string> Keywords::getStopWords()
{
    return sw;
}

void Keywords::setXml(string xmlF)
{
    xmlFile = xmlF;

}

///COPY CONSTRUCTOR
Keywords::Keywords(const Keywords& other):vreg(other.vreg),sw(other.sw)
{

}

A: kw is allocated in the second code only once, but in the first code for each loop iteration
In non runtime critical code it is good practice to construct objects in a RAII fashion.


text:
Q: How to split a string by ignoring commas c#? I have made a little project that takes .cs files, reads them and returns the most frequent word in the file. However, right now it returns that the most common word is a comma.
How can i make it so splitting the string ignores commas?
For example: i have a string:

, . ? a a, b cdef cfed, abef abef abef,

right now it returns that the most common word is 'abef' and it occured 2 times (the program doesn't count the third abef, the one which is with a comma in the end.)
Another example:

, . ? a a, b cdef cfed, abef abef abef, , ,

this right now returns that the most common word is a comma ',' and it occured 3 times, but the thing is - i want my program to ignore commas and focus purely on words only.
namespace WindowsFormsApp8
{
  public partial class Form1 : Form
  {
    public Form1()
    {
        InitializeComponent();
    }

    private async void button1_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text Documents |*.cs;*.txt", ValidateNames = true, Multiselect = false }) //openfiledialog (all .cs; all.txt)
        {
            if (ofd.ShowDialog() == DialogResult.OK) //if in file dialog a file gets selected
            {
                using (StreamReader sr = new StreamReader(ofd.FileName)) //text reader
                {
                    richTextBox1.Text = await sr.ReadToEndAsync(); //reads the file and returns it into textbox
                }
            }
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string[] userText = richTextBox1.Text.ToLower().Split( ' ' );
        var frequencies = new Dictionary<string, int>(); // variable frequencies, dictionary with key string, value int.
        string highestWord = null;  //declare string highestword with starting value null.
        int highestFreq = 0; //declare integer highestfreq with starting value zero.

        foreach (string word in userText) //search words in our array userText that we declared at the beginning.
        {
            int freq; //declare integer freq.
            frequencies.TryGetValue(word, out freq); //trygetvalue from dictionary key, out value.
            freq += 1; //count it.

            if (freq > highestFreq)
            {
                highestFreq = freq;
                highestWord = word;
            }
            frequencies[word] = freq; //assign most frequent word in frequencies dictionary to freq
        }
        MessageBox.Show("the most occuring word is: " + highestWord + ", it occured " + highestFreq + " times"); //display data to messagebox.
    }
  }
}

A: Split can take an array of chars to split on. So you can split on space and comma. Then remove the empty entries with the appropriate StringSplitOption
 string[] userText = richTextBox1.Text.ToLower().Split(new char[] { ' ', ','}, StringSplitOptions.RemoveEmptyEntries );

Also you can use Linq to calculate the frequency of a word with code like this
var g = userText.GroupBy(x => x)
                .Select(z => new
                { word = z.Key, count = z.Count()})
                .ToList();
string mostUsed = g.OrderByDescending(x => x.count)
                   .Select(x => x.word)
                   .FirstOrDefault();

A: You could replace the commas with an empty string, then run the output through your algorithm.
string original = ", . ? a a, b cdef cfed, abef abef abef,";
string noCommas = original.Replace(",", string.Empty);

Reference:
https://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx

A: Another option is to make the splitting easier to extend by using regular expressions, Regex.Split more specifically:
  string input = ", . ? a a, b cdef cfed, abef abef abef, , ,";
  string[] result = Regex.Split(input, @"\w+");

Check live testing here.
If ? is a valid word, than the regex could be @"\w+|\?".
So, my recommendation is to use regex, even if the split method is enough for now, since it is more powerful and can easily accommodate for later changes.
As a bonus, it is nice to learn about regular expressions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proving a vector space has an uncountable basis I am required to prove that a vector space $V=C[0,1]$ (the space of continuous functions over complex field) has an uncountable basis. The approach I took was to show that there is a subspace $W$ of $V$ with an uncountable basis and concluded that the vector space $V$ itself must have an uncountable basis.
Is this approach correct? I'm just unsure about the last step, if you have a subspace with an uncountable basis does it imply that the space itself must have an uncountable basis?

A: The answer to your general question is yes. If $W$ is a subspace of $V$ and $W$ has an uncountable basis $B\subseteq W$ then $B$ is still linearly independent as a subset of $V$. So $B$ can be extended to a basis for $V$ which means $V$ also has an uncountable basis.

A: Let W be the set of all polynomials.  Any finite subset must have a polynomial of largest degree so cannot be a basis.


text:
Q: If i want to print any one element only from an array .. any of the array. what would be the code then? var a = {
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters":
        {
            "batter":
                [
                    { "id": "1001", "type": "Regular" },
                    { "id": "1002", "type": "Chocolate" },
                    { "id": "1003", "type": "Blueberry" },
                    { "id": "1004", "type": "Devil's Food" }
                ]
        },
    "topping":
        [
            { "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5007", "type": "Powdered Sugar" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" }
        ]
};

If i want to print any one element only from an array .. any of the array. what would be the code then ?
suppose i want to print "Type: chocolate". Then how would i write the code for it ?
Thanks in advance.

A: you can write it like :
for(var i=0;i<a.batters.batter.length;i++){
   console.log(a.batters.batter[i].type)
}

if you wan't to print chocolate only you may access the array without loop over it like
var name = a.batters.batter[1].type;


text:
Q: Retrieve data from SQL to display as XML My SQL query is this
  SELECT firstname AS 'User', count( * ) AS 'Number of photos uploaded'
    FROM members
    JOIN member_photo
   USING ( member_id )
GROUP BY firstname

Basically it is displaying data as follows:
User         Number of photos uploaded
Az                   1
Mz                   3

and so on..
What I want to do is transfer this data to a XML file in the form :
<photos>
    <user>Az</user>
    <user_photos>1</user_photos>
    <user>Mz</user>
    <user_photos>3</user_photos>
</photos>

or any other appropriate way.

A: You do the exact same way you would do it if your XML was HTML.
Suppose this is your php script:
<?php
header('Content-Type: text/xml')'
?>
<photos>
<?php
$query = "select ... form foo...";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
?>
    <user><?= $row['user'] ?></user>
    <user_photos><?= $row['photos_count'] ?></user_photos>
<?php
}
?>
</photos>

A: You did not state your DBMS, but the following will work with PostgreSQL and Oracle:
SELECT '<photos>'||xmlforest(firstname AS "user", count( * ) AS user_photos)||'</photos>'
FROM members
  JOIN member_photo USING ( member_id )
GROUP BY firstname


text:
Q: Algorithm Libraries for using OpenMP with C++ I use the C++ programming language with GCC on a GNU/Linux desktop. I am trying to implement
some PRAM parallel algorithms in C++. As I understand, with  OpenMP on a multicore CPU more or less, helps to emulate CREW PRAM algorithms.
Many sophisticated PRAM algorithms,  involve operations like parallel-prefix sum, sorting,
performing an element wise operation on a vector in global address space etc.
Somehow, after about 15 mins of Googling,  there seem to be no libraries which provide this functionality, i.e. some out of the box basic parallel algorithms or data structures like the Standard Template Library.
Can anyone list any such libraries?
EDIT: What I  need, essentially,  is an OpenMP analogue to the Thrust Library which is used in
the CUDA world. http://thrust.github.com/

A: Thrust supports parallel execution on multicores through OpenMP or TBB as well as GPUs through CUDA. From the website:

Thrust is a parallel algorithms library which resembles the C++
  Standard Template Library (STL). Thrust's high-level interface greatly
  enhances programmer productivity while enabling performance
  portability between GPUs and multicore CPUs. Interoperability with
  established technologies (such as CUDA, TBB, and OpenMP) facilitates
  integration with existing software. Develop high-performance
  applications rapidly with Thrust!

Here's some additional information on how to access Thrust's multicore functionality.


text:
Q: Literals are not objects? Help me to correctly explain why literal is not an object in C++.
My explanation is: "Strictly speaking we can't think that literals are objects. Literals are prvalues excluding string literals. Often prvalues are values that is not associated with any object!"
This explanation consistent with the C++ standart (also see here). Maybe there is another explanation?

A: A literal is a declarative object, however I think that maybe you are getting hung up on a distinction that primitives and objects. Primitives are objects and can be seen them as objects easily but due to there notation and lack of members, it can be easy to see why they could be perceived as not objects. Therefore it easy to see why it could be thought that a literal is not an object because literals usually define primitives (not many complex data structures are easy to define in literals).
However, a primitive is an object (no useful reason to not define them as objects) because it is a member of a type. Therefore since is just a static definition of an object they are also an object we just don't interact with them in the same way as other objects because they are static.
While the idea that a literal is not object probably won't cause any problems in code it can make OOP more complicated especially since the idea of OOP is that we should interact with object in programming because that is how we interact with everything outside of programming.


text:
Q: 2018 MongoDB distinct count for NodeJS Express Mongoose API I am trying to get this value (db.collecName.distinct('fieldName').length) basically a count of distinct docs, but in a ReactJS-Express-Mongoose API route.
Should be in this format of API call :
router.get('/', function(req, res, next){
    ModelName.find(function (err, CollecName){
      if(err) return next(err);
      res.json(CollecName);
    });
});

Thanks in advance !

A: Thanks to Jeremy T.,
router.get('/count', function(req, res, next){
    ModelName.find().distinct('fieldName', function(err, Response) {
        if (err) return next(err);
        // console.log(Response.length);
        res.json(Response.length);
    });
});

~ SOLUTION


text:
Q: Testing a JSON PUT request in mojolicious I am creating test cases for my app developed using Mojolicious framework. I am testing the routes for appropriate responses for the REST calls that are made. I use JSON as a means of communication between the server and client. To test GET, POST and DELETE requests I use the following functions
GET : get_ok()POST: post_json_ok() DELETE: delete_ok()
but for PUT I am not able to use put_ok(). And example of my usage of put_ok() would be  my $t = Test::Mojo->new;$t->put_ok('this/is/url/to/resource'=>{ "element" => "modified value"})->status_is(204)

I get a bad request status every time(400) and so the test fails. I use Test::Mojo for testing my application.
Additional information:
$t->put_ok('http://localhost:3000/application/instances/system/test'=>{"model" => "testing put"})->status_is(204);
  This is the exact test for PUT request that is attempted. model is a property of resource test that is being attempted to be changed to testing put and the expected status response is 204.
The mapping to the controller is done by
$r->route('/application/instances/system/:id, id  => qr/[A-Za-z0-9 ]+/ -> via('put')
    ->to(controller => 'system', action => 'update_sys');
 This route calls the update_sys method in the system controller and that is how the resource is located.

A: Actually, after discussions with SRI on IRC, he pointed me to an example almost identical you your needs in the documentation.
# Test custom transaction
my $tx = $t->ua->build_json_tx('/user/99' => {name => 'sri'});
$tx->req->method('PUT');
$t->tx($t->ua->start($tx))
  ->status_is(200)
  ->json_is('/message' => 'User has been replaced.');

So this should work for you!
Postscript:
You might be interested to know that this discussion has brought some progress: the next release of Mojolicious (version 3.66) will now have a cleaner syntax for this purpose, the new request_ok method. The above example can then be rewritten as
my $tx = $t->ua->build_json_tx('/user/99' => {name => 'sri'});
$tx->req->method('PUT');
$t->request_ok($tx)
  ->status_is(200)
  ->json_is('/message' => 'User has been replaced.');

A: Can you share the definition of your route for 'this/is/url/to/resource' ?  the server is returning 400, so it appears Mojo::Controller in your app does not understand what you are sending ...


text:
Q: Symfony serializer ignore serialization groups I have an Entity coming from a Doctrine repository, that I want to serialize and then return back. The Entity has of course several relations, those relations have also some realtions, and so on. Every relation that is needed, is already populated, BUT NOT ALL.
The properties of the Entities already have some serialization groups.
public function getListAction(SerializerInterface $serializer)
{
    // ... Getting data from database with Doctrine
    $entities = $this->someRepository->findByConditions(/* ... */);

    $serializer->serialize($entities, 'json');
}

In the profiler I see that it starts to fill up the rest of the relations. Starts to execute database queries to fill up all the missing properties. Then eventually the query times out.
Question:
Is there a way to tell the serializer, to only serialize the given object, but do not fill up the missing relations? In other words, disable lazy loading?
Adding a new serialization group would be also not good, because some Entity has a reference to itself $parent. So it'll again end up in executing queries.

A: The Serializer is not able to see whether a call will trigger the lazy loading in Doctrine. You probably could write your own Normalizer that looks for classes from Doctrine's Proxy-namespace, but I imagine that will probably just becoome a hot mess if it will solve your problem in the first place.
The best solution that I can think of is tackling the issue at the ORM-level, as that is what is causing you problems.
For example you could create a custom find-method in a repository using DQL or QueryBuilder, which will fetch all necessary data including potentially joining in related objects you want to output and excluding any fields you don't want. Then I would hydrate the result (see Doctrine Docs: Hydration) using a different Hydrator. You could try the SimpleObjectHydrator provided by Doctrine. As far as I know, this Hydrator will not use Proxies for Lazy Loading and instead will load as much as it can eagerly and it should still give you your original Entity, but the eager loading might not be what you want. In that case you can use it as a reference for your own Hydrator. Writing custom hydrators might be a huge pain and you could instead opt for array output and just forego the object hydration entirely. In that case you are sure to lose the annotations in your entity, which you would then need to address in your Serializer logic.
You could also look at Native Queries (i.e. SQL) and then custom Result Set Mapping as an alternative: see Doctrine Docs: ResultSetMappingBuilder


text:
Q: Regular Expression Tweak Needed I would appreciate some quick help on a regular expression in Perl. I'm hoping a regex expert can quickly spot what I'm doing wrong.
I'm trying to match strings of the following form and reject anything else:
1.2
1.2_EB4
1.2_FB4
1.2.3
1.2.3_EB4
1.2.3_FB4

The "1", "2", "3", and "4" can be any non-negative integers, but the "EB", "FB", underscore, and dots are fixed.
Here is what I have so far. (Don't worry about hours/minutes/seconds, and FYI yes, I am dropping the "1" and reordering the "2", "3", and "4".)
my $hours = 0;
my $minutes = 0;
my $seconds = 0;

#                          [ws]  123   .   456  [ .  789  ]  [ _xB      234 ]
#                          --- ------ -- ------  -- ------    ------- ------
my ($found) = ($input =~ /^\s*([0-9]+)\.([0-9]+)(\.([0-9]+))?(\_[EF]B([0-9]+))?/);

if ($found)
{
    $hours = $2;
    $minutes = $6;
    $seconds = $4 if ($4);

    $hours   = 0 if ($hours   eq "");
    $minutes = 0 if ($minutes eq "");
    $seconds = 0 if ($seconds eq "");
}

Here is what I'm getting for certain inputs:
+---------+--------+-------+
|  Input  |Expected| Actual|
|---------|--------|-------|
|1        |  false | false |
|1.       |  false | false |
|1.2      |  2:0:0 | 2:0:0 |
|1.2.     |  false | 2:0:0 |
|1.2.3    |  2:0:3 | 2:0:3 |
|1.2_     |  false | 2:0:0 |
|1.2_E    |  false | 2:0:0 |
|1.2_FB   |  false | 2:0:0 |
|1.2_EB4  |  2:4:0 | 2:4:0 |
|1.2_GB4  |  false | 2:0:0 |
|1.2.3_   |  false | 2:0:3 |
|1.2.3_E  |  false | 2:0:3 |
|1.2.3_FB4|  2:4:3 | 2:4:3 |
|1.2.3_GB4|  false | 2:0:3 |
+---------+--------+-------+

I appreciate any help anyone can offer.
Thanks.

A: Stick a $ on the end of the regex, and it should work:
/^\s*([0-9]+)\.([0-9]+)(\.([0-9]+))?(_[EF]B([0-9]+))?$/

You can find an online explanation and demonstration here
Without the $ anchor, the regex will match the 1.2 part of 1.2., 1.2_, 1.2_E, 1.2_FB, 1.2_GB4, 1.2.3_, 1.2.3_E, and 1.2.3_GB4 and then quit without trying to match more.
If you don't need to capture the numbers in capturing groups, you can simplify it a bit:
^\s*[0-9]+(?:\.[0-9]+){1,2}(?:_[EF]B[0-9]+)?$

https://regex101.com/r/lM3bD7/2

A: You could use anchors and simplify your regex a bit.
/^\d+(\.\d+){1,2}(_[EF]B\d+)?$/


text:
Q: Unable to PDO::bindParam() on OUT parameters in PHP on mySQL Stored Procedure (bindValue on IN param works) I am calling a mySQL Stored Procedure with OUT parameters using PDO and PHP.  I cannot get the bindParam() function to execute at all.  After much research, I have put together a remedial php script to try to figure this out.  The stored procedure works perfectly in mySQL Workbench.
Thanks in advance for your attention.
FROM phpInfo()
PHP Version 7.1.11-0ubuntu0.17.10.1
Apache/2.4.27 (Ubuntu)
  PDO support   enabled
  PDO drivers   mysql
  PDO Driver for MySQL  enabled
  Client API version    mysqlnd 5.0.12-dev - 20150407
MySQL Server 5.7
The Stored Procedure
CREATE DEFINER=`root`@`localhost` PROCEDURE `getScoreRecordsByEventId`(
    eventId int,
    OUT teamId int,
    OUT teamName varchar(30),
    OUT oppId int,
    OUT oppName varchar(30)
)
BEGIN
    set teamId = getTeamIdByEventId(eventId);
    set teamName = getTeamNameByEventId(eventId);
    set oppId = getOppIdByEventId(eventId);
    set oppName = getOppNameByEventId(eventId);

    SELECT act_time, act, `quarter`,
    team_id FROM floor_stats WHERE event_id = eventId AND act LIKE
    '%made' ORDER BY quarter, act_time;
END

This pulls from two tables:
  events:
    id        int PK
    team_id    int
    team_name    varchar(30)
    opponent_id    int
    opp_name    varchar(30)
floor_stats:
    act_time    int
    act    varchar(10)
    quarter    int
I call several functions inside the stored procedure to provide the OUT values.  Again, the SP works fine in mySQL Workbench.
The program for testing/learning:
  <?php
    echo "begin
";
    $dsn = 'mysql:dbname=stats;host=127.0.0.1';
    $user = 'root';
    $password = 'Jeuchems1';

    echo "ready to connect
";
    try {
        $dbh = new PDO($dsn, $user, $password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "  var_dump of dbh (PDO Connection)
";
        var_dump($dbh);

      } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    echo "connected  :)
";

    echo "
initialize variables to receive output from stored procedure
";
    $eventId = 5;
    echo "event_id: $event_id
";
    $team_id = 0;
    echo "team_id: $team_id
";
    $team_name = 'xxx';
    echo "team_name: $team_name
";
    $opp_id = 0;
    echo "opp_id: $opp_id
";
    $opp_name = 'xxx';
    echo "opp_name: $opp_name
";
    echo "
";

    echo "ready to prepare the statement with named parameters
";
    $sth = $dbh->prepare('CALL getScoreRecordsByEventId(:eventId, :teamId, :teamName, :oppId, :oppName)');
    echo "  var_dump of sth (PDO statement)
";
    var_dump($sth);
    echo "completed prepare statement
";

    echo "
ready to bindParam
";
    echo "  binding eventId: ".(($sth->bindValue(":eventId", $event_id, PDO::PARAM_INT)) ? "success
" : "failure
");
    echo "  binding teamId: ".(($sth->bindParam(":teamId", $team_id, PDO::PARAM_INT|PDO::PARAM_OUTPUT)) ? "success
" : "failure
");
    echo "  binding teamName: ".(($sth->bindParam(":teamName", $team_name, PDO::PARAM_STR|PDO::PARAM_OUTPUT, 30)) ? "success
" : "failure
");
    echo "  binding oppId: ".(($sth->bindParam(":oppId", $opp_id, PDO::PARAM_INT|PDO::PARAM_OUTPUT)) ? "success
" : "failure
");
    echo "  binding oppName: ".(($sth->bindParam(":oppName", $opp_name, PDO::PARAM_STR|PDO::PARAM_OUTPUT, 30)) ? "success
" : "failure
");
    echo "completed bindParam
";

    echo "
ready to execute
";
    $sth->execute();
    echo "completed execute
";

    echo "
ready to fetch
";
    $results = $sth->fetch(PDO::FETCH_ASSOC);
    echo "completed fetch.
";

    echo "
var_dump of results
";
    var_dump($results);
    echo "count(results):". count($results);
    echo $results[0];
    echo "
";

    echo "ready to echo the result keys.
";
    $keys = array_keys($results);
    foreach($keys as $key) {
      echo "key:$key
";
    }
  ?>

This is the output I get.  It should at least give me a 'failed' or something.  :(
begin
ready to connect
var_dump of dbh (PDO Connection)
object(PDO)#1 (0) { } connected :)
initialize variables to receive output from stored procedure
event_id:
team_id: 0
team_name: xxx
opp_id: 0
opp_name: xxx
ready to prepare the statement with named parameters
var_dump of sth (PDO statement)
object(PDOStatement)#2 (1) { ["queryString"]=> string(72) "getScoreRecordsByEventId(:eventId, :teamId, :teamName, :oppId, :oppName)" } completed prepare statement
ready to bindParam
binding eventId: success
After all this work, I will be both exhilarated and frustrated if it is a simple fix.
Thanks for your help.


text:
Q: Running Class based methods as Celery Tasks Am having problems running tasks when setup as class methods. I've read about celery.contrib.methods from the answer here on SO but am not able to apply it to my case.
celery_conf.celeryapp.py
from __future__ import absolute_import
from celery import Celery
app = Celery()
app.config_from_object('celery_conf.celeryconfig')
if __name__ == '__main__':
    app.start()

celery_conf.celeryconfig.py
BROKER_URL = 'amqp://'
CELERY_RESULT_BACKEND = 'amqp://'
CELERY_TASK_RESULT_EXPIRES = 3600
CELERY_AMQP_TASK_RESULT_EXPIRES = 60
CELERYD_PREFETCH_MULTIPLIER = 0
CELERY_IMPORTS=("student.process_records")

student.process_records.py
from celery_conf.celeryapp import app
from celery.contrib.methods import task_method

class Student():
    '''student class'''
    @app.task(filter=task_method, name='student.process_records.get_student_id')
    def get_student_id(self, **kwargs):
        '''process some student ids'''

def main():
    student = Student()
    student.get_student_id.delay(**task_to_do)

if __name__ == '__main__':
    main()

With the above configuration, I keep getting the errors
[2014-10-29 20:38:02,073: CRITICAL/MainProcess] Can't decode message body: DecodeError(AttributeError("Can't get attribute 'Student' on <module 'celery.bin.celery' from '/home/lukik/venv/python_3_4/lib/python3.4/site-packages/celery/bin/celery.py'>",),) [type:'application/x-python-serialize' encoding:'binary' headers:{}]
kombu.exceptions.DecodeError: Can't get attribute 'Student' on <module 'celery.bin.celery' from '/home/lukik/venv/python3_4/lib/python3.4/site-packages/celery/bin/celery.py'>
How should I configure or import items in order for it to work?
celery_version = 3.1.16
python_version = python3.4


text:
Q: Cant convert .png to .tiff in intellij IDE using jmagick So I'm trying to write a simple program that will change the type of an image from a .png to a .tiff using jmagick in java. I followed a tutorial that i found online for different image formats located Here. The program compiles successfully but when I run it I get this message:
Process finished with exit code -1073740940 (0xC0000374)

This is my code:
System.out.println("I'm at 0");
String inputfileName = "C:\\Users\\MySelf\\IdeaProjects\\tess4jTest\\p1.png"; //Input PNG file
ImageInfo info = new ImageInfo(inputfileName); //Get PNG file into ImageInfo object
MagickImage magick_converter = new MagickImage(info); //Create MagickImage object
System.out.println("I'm at 1")
    String outputfile = "C:\\Users\\emctiern\\IdeaProjects\\tess4jTest\\p01.tiff"; //Output File name
    magick_converter.setFileName(outputfile); //set output file format
    magick_converter.writeImage(info); //do the conversion
    System.out.println("I'm at 2");

My code never actually reaches the print 1 and 2, I think it might be that its not sure where to get the file from, That's why I entered the the full file path. In the tutorial I followed they just had the image name and nothing else.
Thanks in advance


text:
Q: Javascript Incrementing Numbers What I'm after:
There are 5 counters on my page, they should all start from 0 and count upwards (increment) at the same time to different values that are set at different speeds. So for example I set 10, 25, 1500, 400, 500 in my variables I would like them all to reach these values.
• start at the same time
• all increment at different speeds
• stop at value set for each
My Problem
I can't figure out a good way to write some simple very efficient javascript to do this (going to be used on a mobile), currently I'm using setinterval which seems to start all the counters at different times and jerks/not smooth..
how far I've got so far
http://jsfiddle.net/95smH/
setInterval(f1,500);
setInterval(f2,1500);
setInterval(f3,500);
setInterval(f4,50);

var v1      = 0
,   v2 = 0
,   v3  = 0
,   v4  = 0;

function f1() {
    $('.count.v1').text(v1);
    if ( v1 < 450 )
    {
        v1 ++;
    }
}
function f2() {
    $('.count.v2').text(v2);
    if ( v2 < 50 )
    {
        v2 ++;
    }
}
function f3() {
    $('.count.v3').text(v3);
    if ( v3 < 23 )
    {
        v3 ++;
    }
 }
function f4() {
    $('.count.v4').text(v4);
    if ( v4 < 4 )
   {
        v4 ++;
    }
}

A: This is based on your own code style:
setInterval(tick,50);

var cusers      = 0
,   cawardshows = 0
,   ccountries  = 0
,   cregions    = 0;

var susers = 500
,   sawardshows = 1500
,   scountries = 500
,   sregions = 50;

var i = 0;

function tick() {
    $('.count.users').text(cusers);
    if ( cusers < 450 && i % susers == 0)
    {
        cusers ++;
    }

    $('.count.awardshows').text(cawardshows);
    if ( cawardshows < 50 && i % sawardshows == 0 )
    {
        cawardshows ++;
    }
    $('.count.countries').text(ccountries);
    if ( ccountries < 23  && i % scountries == 0 )
    {
        ccountries ++;
    }
    $('.count.regions').text(cregions);
    if ( cregions < 4 && i % sregions == 0)
    {
        cregions ++;
    }
    i += 50;
}

The idea is to have only one timer, so all updates will be synchronized to the same clock. Since values have different "speeds", you update some of them only every nth step.

A: This would be my shot at a slightly more general way. It will also kill the setInterval once every counter has finished. Of course this will still have the typical inaccuracy of Javascript intervals.
var counter = new (function () {
    'use strict';

    var counters = [],
        handler = null,
        precision = 50;

    this.addCounter = function (maxValue, interval, selector) {
        counters.push({
            maxValue: maxValue,
            currentValue: 0,
            interval: interval / precision,
            intervalCounter: 0,
            $output: $(selector)
        });

        return this;
    };

    this.start = function () {
        handler = setInterval(function () {
            var stillRunning = false;
            for (var i = 0; i < counters.length; i++) {
                var counter = counters[i];

                counter.intervalCounter++;
                if (counter.intervalCounter === counter.interval) {
                    counter.intervalCounter = 0;
                    counter.currentValue++;

                    if (counter.currentValue <= counter.maxValue) {
                        stillRunning = true;
                        counter.$output.val(counter.currentValue);
                    }
                } else {
                    stillRunning = true;
                }
            }

            if (!stillRunning) {
                clearInterval(handler);
            }
        }, precision);
    };

    return this;
})();

counter
    .addCounter(50, 250, '.v1')
    .addCounter(25, 500, '.v2')
    .start();

Demo fiddle: http://jsfiddle.net/s9AYz/1/
Note that precision must be set such that the interval of each counter is a multiple of it (Boris solution has the same requirement).

A: Here is a solution quite cpu-friendly :
 - you only have one setInterval using a base period that you decide.
 - On each interval you iterate through your all counters doing very little work each time.
(i even avoided to use % ).
 - The elements are cached.
jsbin is here :
http://jsbin.com/urUxojo/2/edit?html,js,console,output
window.onload=function() {

// this is the period of the base Interval in ms.
// The counters will be aligned on this base period
Counter.basePeriod = 50 ;

// constructor of a Counter
// ! initializes the counter display.
function Counter(id, period_ms, max, initialValue) {
         this.element  = document.getElementById(id);
         this.period   = Math.ceil(period_ms / Counter.basePeriod) || 1;
         this.max      = max ;
         this.value    = initialValue || 0 ;
         this.last     = 0;
         this.element.value = (this.value);
         return this;
};

// called on each basePeriod tick
// updates the element every period until it reaches its max value.
Counter.prototype.tick = function() {
        this.last++;
        if (this.last == this.period  &&
                           this.value != this.max ) {
             this.value++;
             this.element.value = (this.value);
             this.last=0;
        }
};

Counter.counters = [];

Counter.start= function () {
       function handleCounters() {
         for (var i=0; i< Counter.counters.length; i++) {  Counter.counters[i].tick();  }
       }
       Counter._interval = setInterval(handleCounters, Counter.basePeriod);
};

Counter.add = function() {
    var newCounter = Object.create(Counter.prototype);
    Counter.counters.push( Counter.apply(newCounter, arguments) );
}

// -------------------------------

Counter.add('cnt1'      , 500  , 450 );
Counter.add('cnt2'      , 400  , 40 );
Counter.add('topCounter', 1000 , 5  );

Counter.start();

}

A: Well, you always want to get rid of duplicity, so you can do:
function IntervalClass(selector, sleepTime, maxValue, startValue) {
    var curValue = startValue;

    this.tick = function () {
        if (curValue < maxValue) {
            curValue++;
        }
        $(selector).html(curValue);
    };

    this.start = function () {
        setInterval(this.tick, sleepTime);
    };
}

new IntervalClass(".count.users", 1000, 35, 0).start();
new IntervalClass(".count.awardshows", 500, 20, 0).start();
new IntervalClass(".count.countries", 1500, 15, 0).start();
new IntervalClass(".count.regions", 200, 100, 0).start();

JSFIDDLE


text:
Q: Formula causing .xlsx to need repair on open I'm generating an .xlsx file using the EPPlus library.
I create several worksheets, each with multiple rows. Some rows have a cell reference in column J which I am inserting using the following:
for (int i = 2; i < rowCount; i++)    // start on row 2 (header)
{
    var formula = GetCellRefFormula(i);
    worksheet.Cells[$"J{i}"].Formula = formula;
}

// save worksheet/workbook

private string GetCellRefFormula(int i)
{
    return $"\"Row \"&ROW(D{i})"
}

When I open the workbook I get the following errors:
Removed Records: Formula from /xl/worksheets/sheet1.xml part
Removed Records: Formula from /xl/worksheets/sheet7.xml part

The errors are certainly caused by the string returned from GetCellRefFormula(), if I don't set these formulas or GetCellRefFormula simply returns an empty string, I get no errors.
I have also tried setting the formula to have an equals sign in front, with the same result.
private string GetCellRefFormula(int i)
{
    return $"=\"Row \"&ROW(D{i})"
}

Should I be setting the formula field like this?
Is there a way to see specifically which formulas are incorrect in the Excel repair log?
As far as I can see it only gives the errors I've copied above.


text:
Q: Tried to decompress a zip file into memory with boost,but it doesn't work I tried to unzip a zip file with boost zlib, but it doesn't work ,my boost version is 1.75  which is binary which is have been built,I tried the code below with VS 2013 CE
 #include<iostream>
 #include<fstream>
 #include<algorithm>
 #include<iterator>
 #include<sstream>
 #include <boost/iostreams/filtering_streambuf.hpp>
 #include <boost/iostreams/copy.hpp>
 #include <boost/iostreams/filter/zlib.hpp>

 using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    ifstream src;
    ofstream dst;
    stringstream  ss;

 try
 {
      src.open("d:\\202012303333629003180526491.txt.zip", ios::in | ios::binary);
      dst.open("to.zip", ios::out | ios::binary);

      copy(istreambuf_iterator<char>(src),
        istreambuf_iterator<char>(),
        ostreambuf_iterator<char>(ss));

      cout << ss.str() << endl;

      std::stringstream decompressed;

      boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
      in.push(boost::iostreams::zlib_decompressor());
      in.push(ss);
      boost::iostreams::copy(in, decompressed);
      string decompressestr = decompressed.str();

      src.close();
      dst.close();
      return 0;
  }
  catch (const std::exception& error)
  {
      std::cerr << error.what() << std::endl;
      return (EXIT_FAILURE);
   }
}

the exception was zlib error: iostream stream error,any idea what wrong I have done? thank you so much

A: zlib does not process zip files. zlib can process zlib, gzip, and raw deflate streams.


text:
Q: PDE: $ (\partial_{tt}-\partial_{xx})u(x,t)=0, u(x,0)=x(1-x)$ Hello I am trying to solve the partial differential equation with initial and boundary conditions given by
\begin{eqnarray}
 (\partial_{tt}-\partial_{xx})u(x,t)=0\\
u(x,0)=f(x)\\
\partial_t u(x,0)=0\\
u(0,t)=u(1,t)=0\\
f(x)=x(1-x)
\end{eqnarray}
where $x\in [0,1]$ and $t\geq 0$.
Usually we can seek solutions to this problem by writing it of the form
$$
u(x,t)=\frac{1}{2} (f(x+t)+f(x-t))
$$
but this assumes that $f(-x)=-f(x)$ and also $f(x+2)=f(x)$. Note, this is required for these boundary and initial conditions, the function $f$ most have two derivatives and be extended to the whole real line by defining it to be odd and satisfying $f(x+2)=f(x)$.
However, in this example, $f(x)$ is not odd (or even), so I am stuck as to how to find this analytic solution.
I thought about Fourier transforming in space, using $u(x,t)=\int_{-\infty}^\infty u(k,t)e^{ikx}dk$, to obtain
$$
(\partial_{tt}+k^2 )u(k,t)=0\implies u(k,t)=A\cos(kt)+B\sin(kt)
$$
however then had problems computing the inverse Fourier transform.
Thanks for your help.

A: I would suggest the ol' fashioned way of separating by variables.
$\underline{\textbf{Separation}}$
We begin by considering the equivalent PDE:
$$\frac{\partial^2u}{\partial t^2}=\frac{\partial^2u}{\partial x^2}$$
And consider solutions of the form $u(x,t)=X(x)T(t)$. From this we obtain:
$$X\frac{d^2T}{dt^2}=T\frac{d^2X}{dx^2}$$
Which can be rearranged to reveal:
$$\frac{1}{T}\frac{d^2T}{dt^2}=\frac{1}{X}\frac{d^2X}{dx^2}=-k^2$$
Choosing $-k^2$ as the eigenvalue. This results in two separate PDEs:
$$\frac{d^2T}{dt^2}+k^2T=0\phantom{..}\&\phantom{..}\frac{d^2X}{dx^2}+k^2X=0$$
We recognize that these both have the solution:
$$T(t)=A\cos(kt)+B\sin(kt)\phantom{..}\&\phantom{..}X(x)=C\cos(kt)+D\sin(kx)$$
$\underline{\textbf{Endpoint Conditions}}$
We now turn to the boundary conditions. The first of which deals with the fact that:
$$u(0,t)=0\phantom{..}\&\phantom{..}u(1,t)=0$$
Since $u(x,t)=X(x)T(t)$, we can reformulate these in terms of the component functions. Of course assuming that $T(t)\neq0$, then this implies the initial value conditions:
$$X(0)=0\phantom{..}\&\phantom{..}X(1)=0$$
The first implies a form of $X(x)=D\sin(kx)$, the second implies that k can be of the form $n\pi$ where $n$ is an integer. This means effectively that $X(x)$ can in fact be a sum of functions in the following form:
$$X(x)=\sum_{n=0}^\infty D_n\sin(n\pi x)$$
$\underline{\textbf{Initial Speed Condition}}$
The following condition:
$$\frac{\partial}{\partial t}u(x,0)=0$$
speaks about the time variable. This means after differentiating that
$$\frac{d}{dt}T(0)=0$$
This implies that the time function is of the following form:
$$T(t)=A_n\cos(n\pi t)$$
Therefore our function is:
$$u(x,t)=\sum_{n=0}^\infty A_nD_n\cos(n\pi t)\sin(n\pi x)$$
We allow $\Gamma_n=A_nD_n$ to produce the final function:
$$u(x,t)=\sum_{n=0}^\infty \Gamma_n\cos(n\pi t)\sin(n\pi x)$$
$\underline{\textbf{Initial Function Condition}}$
By this point in time, you may see that the solution is headed towards a Fourier Series. This is because the final condition states that:
$$u(x,0)=x(1-x)$$
Expanding using the product form, we find the following condition:
$$\sum_{n=0}^\infty\Gamma_n\sin(n\pi x)=x(1-x)$$
Normally, a function $f(x)$ which can be represented by a sum of sines is represented under the Fourier Series as
$$f(x)=\sum_{n=0}^\infty b_n\sin\left(\frac{\pi n x}{P}\right),\text{ where },b_n=\frac{2}{P}\int^{x_0+P}_{x_0}f(x)\sin\left(\frac{\pi n x}{P}\right)dx$$
Therefore, we need to alter the form to:
$$f(x)=\sum_{n=0}^\infty \Gamma_n\sin\left(\pi n x)\right),\text{ where },\Gamma_n=2\int_0^1x(1-x)\sin(\pi n x)dx$$
Obtaining the coefficients for the integral and using them for $\Gamma_n$, we finally get our function. This is the final product:

A: HIT :
The general solution of the PDE is on the form :
$$u(x,t)=g(x+t)+h(x-t)$$
any two times differentiable functions $g$ and $h$.
With condition $u(x,0)=f(x)$
$$u(x,0)=g(x)+h(x)=f(x)\quad\implies\quad h(x)=f(x)-g(x)$$
$$u(x,t)=g(x+t)+h(x-t)=g(x+t)+f(x+t)-g(x+t)$$
With $f(x)=x(1-x)\quad\to\quad f(x+t)=(x+t)\left(1-(x+t)\right)$
$$u(x,t)=(x+t)\left(1-(x+t)\right)+g(x+t)-g(x+t)$$
The function $g$ is to be determined according to the other conditions.


text:
Q: Understanding a topological proof involoving set theory Here is the proof of the following statement: "Let $f: X \rightarrow Y$ be a function with $X$ and $Y$ topological spaces. If f is continuous, then for all $F \subset Y$ closed, $f^{-1}(F) \subset X$ is closed.
I will write the whole proof but only the last line is troubling me:
Let $F = Y \setminus U , U \subset Y$ open
$U = Y \setminus F$
$f^{-1}(Y\setminus F) \subset X$ is open
$= f^{-1}(Y)\setminus f^{-1}(F)$ is open
$\implies X\setminus (f^{-1}(Y) \setminus f^{-1}(F)) $ is closed in $X$
$\implies f^{-1}(F)$ is closed   $(*)$
The I don't understand the last line $(*)$


text:
Q: WCF Service throwing a timeout error when using WcfTestClient If I send parameters which will cause a lot of data to be pulled I get the following error:
The request channel timed out while waiting for a reply after 00:01:00. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.
I have increased all of my timeouts. Is there something I have to do on the client side? I am wondering if this is because I am using wcftestclient? Do I need to adjust the operationTimeout?
My webconfig has the following:
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="Basic" sendTimeout="12:00:00" receiveTimeout="12:00:00" openTimeout="00:10:00" closeTimeout="00:10:00"
                 maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
          <readerQuotas maxDepth="128" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="8192"/>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="CaseStudyBehavior" name="EDTFS.ADMS.CaseStudyService">
        <endpoint address=""
                  binding="basicHttpBinding"
                  bindingConfiguration="Basic"
                  name="Basic"
                  contract="EDTFS.ADMS.ICaseStudyService" />
        <endpoint address="mex"
                  binding="mexHttpBinding"
                  name="Metadata"
                  contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="CaseStudyBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceTimeouts transactionTimeout="24:00:00"/>
          <serviceThrottling maxConcurrentCalls="100" maxConcurrentInstances="100" maxConcurrentSessions="100"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

A: In the WCF Test Client you will find a node called Config File beneath your service. Right-click this and select Edit with SvcConfigEditor to increase timeout on the client.


text:
Q: Cannot convert implicitly Linked List to Queue When I am trying to convert Linked List to Queue I am getting following error
Queue<String> oldList = new LinkedList<>();

A: Well, a LinkedList<T> is not a Queue<T>.
You could create a Queue via constructor:
LinkedList<string> linkedList = ....

Queue<String> oldList = new Queue<string>(linkedList);


text:
Q: How can I create a stream in RxJava2 (Android) that has no input value, but produces a String? In Android, I want to use the call AdvertisingIdClient.getAdvertisingIdInfo(getContext()).getId() on a separate thread (IO-thread) and handle the string on the main thread.
I wan't to do this with RxJava2.
This is what I have now: (which works)
SingleOnSubscribe<String> source = new SingleOnSubscribe<String>() {
        @Override
        public void subscribe(SingleEmitter<String> e) throws Exception {
            e.onSuccess(AdvertisingIdClient.getAdvertisingIdInfo(getContext()).getId());
        }
    };

    Single.create(source)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError(new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Timber.e(throwable.getMessage());
                }
            })
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(String s) throws Exception {
                    advertisingId = s;
                }
            });

What I would prefer, which is purely taste, is if I could "just" create the stream and handle it all in the flow of methods. Such as: (warning, super pseudo code)
Completable
    .empty()
    .produce(() -> String {
        return makeString();
    })
    .sub/obs-On()...
    .subscribe(coolString -> {mVariable = coolString})

So, Make an Observable and turn it into an Observable by executing some function.

A: Just use defer or fromCallable like in this example:
Observable<String> stringObservable = Observable.fromCallable(() -> {
        return getStuff();
    });

Test
@Test
public void fromCallable() throws Exception {
    Observable<String> stringObservable = Observable.fromCallable(() -> {
        return getStuff();
    });

    ExecutorService executorService = Executors.newSingleThreadExecutor(runnable -> {
        return new Thread(runnable, "myFancyThread");
    });
    Scheduler scheduler = Schedulers.from(executorService);

    TestObserver<String> test = stringObservable.subscribeOn(scheduler)
                .test();

    test.await()
            .assertResult("wurst");

    assertThat(test.lastThread().getName()).contains("myFancyThread");
}

private String getStuff() {
    return "wurst";
}


text:
Q: How to test Rspec For controller, How to Rectify this error in RSpec for Controller,
1) SellersController GET index find the Activity
     Failure/Error: assigns(:activity).should eq([activity])
   expected: [#<Activity id: 65, transactable_type: "admin", transactable_id: 1, action_type: "seller", user_id: 1, is_approved: false, approved_by: nil, created_at: "2012-04-09 11:02:17", updated_at: "2012-04-09 11:02:17", associatable_type: nil, associatable_id: nil>]
        got: nil

   (compared using ==)

Seller_rspec.rb
describe "GET index" do
    it "find the Activity" do
 activity = Activity.create!(:transactable_type=>"admin",:transactable_id=>1,:action_type=>"seller",:user_id =>1,:is_approved=>0)
     get :index,{:is_approved => activity.to_param,:user_id=>1,:approved_by=>"admin"}
     assigns(:activity).should eq([activity])
    end

In controller
 def index
        @activities=Activity.find(:all,:select => 'DISTINCT transactable_type,transactable_id,action_type,is_approved,approved_by',:conditions=>["is_approved= ?  and user_id=? and approved_by IS NULL",false,current_user.id])
  end

A: You are putting a code into controller which should go to the model. Create a method or scope in Activity model like:
def self.find_not_approved(current_user_id)
      find(:all,
           :select => 'DISTINCT transactable_type,transactable_id,action_type,is_approved,approved_by',
           :conditions= ["is_approved= ?  and user_id=? and approved_by IS NULL",
           false,
           current_user_id])
end

So you can just have in controller (I've made up the method name):
  def index
    @activities = Activity.find_not_appoved(current_user.id)
  end

And just to anser your question, it should be assigns(:activities).should eq([activity]) not assigns(:activity).should eq([activity]) - as your are checking @activities variable in controller not, @activity.


text:
Q: Browser Extension Background Module I am working on a browser extension that runs a background script. So far I have all of that working. My issue is I need to use a module in my background script. When I write the import statement I get the follwing exception:
Uncaught SyntaxError: import declarations may only appear at top level of a module

How does one turn a background script into a module?
Manifest.json
{
  "name": "Extension Demo",
  "version": "1.0",
  "description": "Build an Basic Extension!",
  "permissions": [
    "activeTab",
    "webRequest",
    "webRequestBlocking",
    "<all_urls>"
  ],
  "browser_action": {
    "default_popup": "index.html",
    "default_icon": {
      "16": "img/icon16.png",
      "32": "img/icon32.png",
      "48": "img/icon48.png"
    }
  },
  "manifest_version": 2,
  "background": {
    "scripts": [ "background.js" ]
  }
}

bakground.js
import * as myMod from './myMod.js'

function redirect(requestDetails) {
    //do some awesome stuff
}

browser.webRequest.onBeforeRequest.addListener(
    redirect,
    { urls: ["<all_urls>"], types: ["page"] },
    ["blocking"]
);

A: You are using manifest V2, and I highly recommend updating to Manifest v3 to latest features and your error fix.
In your manifest.json file, pass "type": "module" inside the object to allow ESM imports.
"background": {
    "service_worker": "background.js",
    "type": "module"
}

Alternatively, in case you still want to use V2, use a dynamic import instead. Keep in mind that those returns promises and you will have to await it or use a .then() statement.
(async () => {

  const myMod = await import("./myMod.js");
  // if myMod.js uses an `export default` statement, use `(await import("./myMod.js")).default` instead.

  function redirect(requestDetails) {
    //do some awesome stuff
  }

  browser.webRequest.onBeforeRequest.addListener(
    redirect,
    { urls: ["<all_urls>"], types: ["page"] },
    ["blocking"]
  );
})();


text:
Q: How to make a docker container that is identical to my server I have a amazon web server that runs on ubuntu 16.04. This server is dedicated to running a simulation that consists of multiple processes. I have been given the task to create docker containers so that multiple instances of the simulation can be run on the server simultaneously. I understand that running multiple containers will require changing some port id's for each container so my first task it to just run one instance of the simulation in a container.  It seems that I could pull in all of the necessary software images in the dockerFile to create my image file. But I was wondering if there is an easier way to create an image file that is basically a clone of all the software currently on my server?
Thank you

A: first get a list of installed packages from your server (source)
dpkg --get-selections > list.txt

then use that list in your dockerfile:
from ubuntu:16.04
add list.txt

RUN dpkg --clear-selections &&\
  dpkg --set-selections < list &&\
  apt-get autoremove &&\
  apt-get dselect-upgrade

You might also want to copy some folders from your server (etc, var, log, etc). (source)
scp -r user@your.server.example.com:/var /home/user/Desktop/var

and add it to your dockerfile:
ADD /home/user/Desktop/var /var

(repeat for other folders you might need)
and then just build and troubleshoot:
docker build -t my_tag . && docker run -it --rm my_tag bash

Note: This process will get you started, but it will be very very error-prone. Also it will be far from perfect. I recommend, after doing this, to improve your images iteratively by removing unneeded packages and folders. And for a production-docker image, you want to rewrite it to use alpine
Note 2: you can not end up with a docker image, that is identical to your server. Your server has different hardware, a different kernel, a different network, different storage, etc.

A: Note: This will probably not work, but if you want an exact copy, this is something you could try
you could just take the entire filesystem and turn it into a docker container (this is how base-images are build, example)
first download entire file-system (source)
ssh user@server "tar czpf - /" > file.gz

and then create a docker-image from it:
FROM scratch
ADD file.gz /

Note: for this to work, you probably have to exclude some directories, like /dev or /tmp


text:
Q: dealing with NA in seasonal cycle analysis R I have a timeseries of monthly data with lots of missing datapoints, set to NA.  I want to simply subtract the annual cycle from the data, ignoring the missing entries.  It seems that the decompose function can't handle missing data points, but I have seen elsewhere that the seasonal package is suggested instead.  However I am also running into problems there too with the NA.
Here is a minimum reproducible example of the problem using a built in dataset...
library(seasonal)

# set range to missing NA in Co2 dataset
c2<-co2
c2[c2>330 & c2<350]=NA
seas(c2,na.action=na.omit)

Error in na.omit.ts(x) : time series contains internal NAs

Yes, I know! that's why I asked you to omit them! Let's try this:
seas(c2,na.action=na.x13)

Error: X-13 run failed

Errors:
- Adding MV1981.Apr exceeds the number of regression effects
  allowed in the model (80).

Hmmm, interesting, no idea what that means, okay, please just exclude the NA:
seas(c2,na.action=na.exclude)

Error in na.omit.ts(x) : time series contains internal NAs

that didn't help much! and for good measure
decompose(c2)

Error in na.omit.ts(x) : time series contains internal NAs

I'm on the following:
R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

Why is leaving out NA such a problem? I'm obviously being completely stupid, but I can't see what I'm doing wrong with the seas function.  Happy to consider an alternative solution using xts.

A: My first solution, simply manually calculating the seasonal cycle, converting to a dataframe to subtract the vector and then transforming back.
# seasonal cycle
scycle=tapply(c2,cycle(c2),mean,na.rm=T)
# converting to df
df=tapply(c2, list(year=floor(time(c2)), month = cycle(c2)), c)
# subtract seasonal cycle
for (i in 1:nrow(df)){df[i,]=df[i,]-scycle}
# convert back to timeseries
anomco2=ts(c(t(df)),start=start(c2),freq=12)

Not very pretty, and not very efficient either.
The comment of missuse lead me to another Seasonal decompose of monthly data including NA in r I missed with a near duplicate question and this suggested the package zoo, which seems to work really well for additive series
library(zoo)
c2=co2
c2[c2>330&c2<350]=NA
d=decompose(na.StructTS(c2))
plot(co2)
lines(d$x,col="red")

shows that the series is very well reconstructed through the missing period.

The output of deconstruct has the trend and seasonal cycle available.  I wish I could transfer my bounty to user https://stackoverflow.com/users/516548/g-grothendieck for this helpful response. Thanks to user missuse too.
However, if the missing portion is at the end of the series, the software has to extrapolate the trend and has more difficulties.  The original series (in black) maintains the trend, while the trend is smaller in the reconstructed series (red):
c2=co2
c2[c2>350]=NA
d=decompose(na.StructTS(c2))
plot(co2)
lines(d$x,col="red")

Lastly, if instead the missing portion is at the start of the series, the software is unable to extrapolate backwards in time and throws an error... I feel another SO question coming on...
c2=co2
c2[c2<330]=NA
d=decompose(na.StructTS(c2))

Error in StructTS(y) :
the first value of the time series must not be missing

A: You could just use some algorithm that fills the missing data before.
(e.g. from package imputeTS or zoo)
imputeTS for example has extra imputation algorithms for seasonal time series e.g.:
x <- na_seadec(co2)

Another good option for seasonal data:
x <- na_kalman(co2)

And now just go on without the missing data.
An important hint from Adrian Tompkins (see also comment below):
This will work best, when the missing data is somewhere in the middle. For a lot of leading NAs the method is no good choice. In this case it fills the NAs, but it is not able to extrapolate the trend backwards:
c2<-co2
c2[c2<330]<-NA
c3<-na_kalman(c2)
c4<-na_seadec(c2)
plot(co2)
lines(c3,col="blue")
lines(c4,col="red")


text:
Q: Android - Google Maps with Photos I'm currently working on a Camera app. The app lets you, obviously, take a picture however, we have a feature that the photos you taken using the app can be shown on a map where it was taken. Like in this picture

A: You can achieve using custom marker, See this


text:
Q: Java Polymorphic Generic Calls I just recently started messing around with Generics in Java, and am running in to some odd behavior. This is the simplified version, but I have a base class that is extended by multiple classes that gets passed into a generic function. Inside this function, I call a method that has several versions that take different base or derived classes as parameters.
If I have the following:
public class A{};
public class B extends A{};
public class C extends A{};
public class Runner
{
    public static void Run( ClassA a ){Do Something};
    public static void Run( ClassB b ){Do Something};
    public static void Run( ClassC c ){Do Something};
}
void SomeRandomCall<B extends ClassA>( B b )
{
     Runner.Run( b );
}
SomeRandomCall<ClassB>( new ClassB() );

I am finding in debug that Runner.Run is calling the Run( ClassA a ) instead of the Run( ClassB b ) function. Given the two functions, shouldn't Run( ClassB b ) be called since the type specific function is provided?
If this isn't the case how would I be able to have a Generic function that would call be able to call functions that have signatures that take base and derived classes?

A: Since your abbreviations were a bit confusing to me, I made a small, runnable example. I assume that your B in SomeRandomCall is a Generic type, not the class B.
Here it is:
public class Main {

    public static class A{};
    public static class B extends A{};
    public static class C extends A{};
    public static class Runner{
        public static void Run( A a ){System.out.println("A");};
        public static void Run( B b ){System.out.println("B");};
        public static void Run( C c ){System.out.println("C");};
    }

    static <T extends A> void SomeRandomCall( T x ){
         Runner.Run( x );
    }

    public static void main(String[] args) {
        B b = new B();
        new Runner().Run( b );
    }
}

The output is: B.
That's what you expected, and this is good. At compile time, the Java compiler chooses candidates for methods, which are Run( A a ) and Run( B b ). At run time, the type of the parameter is B, so B is printed.
However, note the following example:
    public static void main(String[] args) {
        A ab = new B();
        new Runner().Run( ab );
    }

What happens now? Now the output is A. The reason is, at compile time, ab is of the type A, so we have only one candidate method to execute: Run( A a ). The actual type of ab during runtime is not important anymore, since we have only one candidate that can be executed. The output, independent whether ab is A, B or C, is A.

A: Well, since A extends B, then an object of type B may be passed as a parameter in a method that accepts parameters as type A. The same happens here. Since run(A a) is present before run(B b), the former is executed. Hence, your error (if you're considering it).
For further elaboration consider this following example:
A Programmer is a superclass (like A).
A Java Programmer is a subclass of Programmer, and so is a C++ programmer (like B and C).
Now, there are three doors, in the order of increasing distance:

*

*For Programmers.

*For Java Programmers.

*For C++ Programmers.

Since the 1st door is closest to you and the conditions are met, you enter it right away. You don't wanna spend more energy to go to the 2nd door. The same happens here.

A: void SomeRandomCall<T extends SomeClass>( T t )

is compiled as if it was
void SomeRandomCall( Someclass t )

And that's why
EnclosingClass.<ClassB>SomeRandomCall( new ClassB() );

will result in A because ClassB as compile time type is no longer visible inside the method.
This is also visible if you look at the class (Main in below example) via javap -c -s (i.e. decompiled)
  static <T extends Main$A> void SomeRandomCall(T);
    Signature: (LMain$A;)V
    Code:
       0: aload_0
       1: invokestatic  #18                 // Method Main$Runner.Run:(LMain$A;)V
       4: return

It's signature is void SomeRandomCall( A ) and it will always call Run( A ).
See also Overloading in Java and multiple dispatch why the compile time type matters with overloaded methods.

public static class Runner{
    public static void Run( A a ){System.out.println("A");};
    public static void Run( B b ){System.out.println("B");};
    public static void Run( C c ){System.out.println("C");};
}

public static void main(String[] args) {
    B b = new B();
    Runner.Run(b);
    A a = b;
    Runner.Run(a);
}

The compiler will only choose the correct overloaded method if it can. E.g. above will decompile to
  public static void main(java.lang.String[]);
    Signature: ([Ljava/lang/String;)V
    Code:
       0: new           #29                 // class Main$B
       3: dup
       4: invokespecial #31                 // Method Main$B."<init>":()V
       7: astore_1
       8: aload_1
       9: invokestatic  #32                 // Method Main$Runner.Run:(LMain$B;)V
      12: aload_1
      13: astore_2
      14: aload_2
      15: invokestatic  #18                 // Method Main$Runner.Run:(LMain$A;)V
      18: return

Every call to Run will use a different overloaded version (identified by the number after invokestatic)


text:
Q: Issue when compiling `log` version "0.4.14" In my "Cargo.lock" file I see that log{ version="0.4.14"} is defined.
When trying to run some tests and compile my project I get the following:

error[E0277]: the trait bound `ValueBag<'_>: From<u128>` is not satisfied
   --> /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/log-0.4.14/src/kv/value.rs:364:21
    |
364 |                       Value::from_value_bag(value)
    |                       ^^^^^^^^^^^^^^^^^^^^^ the trait `From<u128>` is not implemented for `ValueBag<'_>`
...
384 | / impl_to_value_primitive![
385 | |     usize, u8, u16, u32, u64, u128, isize, i8, i16, i32, i64, i128, f32, f64, char, bool,
386 | | ];
    | |_- in this macro invocation
    |
    = help: the following other types implement trait `From<T>`:
              <ValueBag<'v> as From<&'a ()>>
              <ValueBag<'v> as From<&'a bool>>
              <ValueBag<'v> as From<&'a char>>
              <ValueBag<'v> as From<&'a f32>>
              <ValueBag<'v> as From<&'a f64>>
              <ValueBag<'v> as From<&'a i16>>
              <ValueBag<'v> as From<&'a i32>>
              <ValueBag<'v> as From<&'a i64>>
            and 25 others
    = note: required because of the requirements on the impl of `Into<ValueBag<'_>>` for `u128`
note: required by a bound in `value::Value::<'v>::from_value_bag`
   --> /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/log-0.4.14/src/kv/value.rs:250:12
    |
248 |     fn from_value_bag<T>(value: T) -> Self
    |        -------------- required by a bound in this
249 |     where
250 |         T: Into<ValueBag<'v>>,
    |            ^^^^^^^^^^^^^^^^^^ required by this bound in `value::Value::<'v>::from_value_bag`
    = note: this error originates in the macro `impl_to_value_primitive` (in Nightly builds, run with -Z macro-backtrace for more info)

I haven't defined log as a dependency for my project and thus I'm not sure what this error is, or how to possibly change the version of this dependency to a newer one that might resolve the issue.

A: Unless you have a dependency which is restricting the version of log it uses, you should be able to solve this problem by running cargo update, which will edit the Cargo.lock file to update the log version in use to one without this bug (as well as any other minor/patch updates in dependencies).
If that doesn't work, you can use cargo tree --invert log to see a listing of which crates depend on log, all the way back to your own crates in your project. Then you can decide what to do about them.


text:
Q: jquery event could not be bound show('

Where will the document go?
<select id="dest"><option value="">-- select destination --</option><option>'+this.DESTINATIONS.join('</option><option>')+'</option></select>
Notes
<input type="text" id="notes" size="70" />
<button id="regbtn">Register</button>

','append',function(){
            $('#regbtn').click(function(){
                alert('ok');
            });
            alert($('#regbtn').click);
        });

The above is the code. show() is just a function that adds animation but executes third parameter after animation. It works with other functions. However, the problem is in $('#regbtn').click() -> I cannot seem to bind it. What could be the problem here?
I'm hoping that even if I don't upload the whole code you can help me figure it out. When i alert the .click, this is the output:
function (a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)}

A: Since you seem to be appending the element dynamically, so please try .on even to ping click event:
http://api.jquery.com/on/
Please lemme know if I missed anything!
script

code
$('#regbtn').on('click',function(){
                alert('ok');
            });

or
   $(document).on('click','#regbtn',function(){
                    alert('ok');
                });


text:
Q: Ignored file still showing changes my .gitignore is as follows:
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# Project files
*.sln
*.vcxproj
*.vcxproj.filters
UpgradeLog.htm

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates

# ....

Now all of these files are ignored properly, with the exception of my solution file, main.sln. Why is this not ignored when I specifically put it in the gitignore?
Is it due to the main.sln existing before I added it to the ignore? I thought it would just stop tracking it if I placed it within the ignore but I guess that's not the case. Here's a screenshot:

How can I simply stop tracking changes for main.sln?

A: .gitignore only works for untracked files. if files already tracked then it can not be ignored, If you added files to repository then two ways to solve it:
1).First way is to do:
git update-index --assume-unchanged <file>

From the doc:

*

*git-update-index - Register file contents in the working tree to the index,

*--assume-unchanged - When the "assume unchanged" bit is on, the user promises not to change the file and allows Git to assume that the working tree file matches what is recorded in the index

2).Second way is to remove the file(s) from repository as below:
git rm --cached <file>

Explanation of command from git-scm-doc:

*

*git-rm -
  Remove files from the working tree and from the index

*--cached -
  Use this option to unstage and remove paths only from the index. Working tree files, whether modified or not, will be left alone. (this means that file will be deleted from tree index not from real directory.)

*<file> -
  Files to remove. Fileglobs (e.g. *.c) can be given to remove all matching files. If you want Git to expand file glob characters, you may need to shell-escape them. A leading directory name (e.g. dir to remove dir/file1 and dir/file2) can be given to remove all files in the directory, and recursively all sub-directories, but this requires the -r option to be explicitly given.

A: Lines in .gitignore will only ignore files that are not part of the repository. Once they are added to the repository, they are tracked, and cannot be ignored.
If you want truly to stop traking this file you have to remove it from the git tree. Just do, from the command line:
$ git rm --cached main.sln

And then commit that change. From then on, your file will be gitignored.
NOTE: the --cached option is to keep the real file in the working directory. Without it the file would also be deleted.

A: Yes, your supposition is correct, you must remove the file from the repository for git to begin ignoring it:
git rm main.sln
git commit -m"Removing file which should be ignored"


text:
Q: Missing the end of the XML when serializing with DataContractSerializer I have the following method that I use to serialize various objects to XML. I then write the XML to a file. All the objects have the proper [DataContract] and [DataMember] attributes.
    public static string Serialize<T>(T item)
    {
        var builder = new StringBuilder();
        var serializer = new DataContractSerializer(typeof(T));

        using (var xmlWriter = XmlWriter.Create(builder))
        {
            serializer.WriteObject(xmlWriter, item);
            return builder.ToString();
        }
    }

The serialization works fine, however, I am missing the end of the content. I.e., the string does not contain the full XML document: the end gets truncated. Sometimes the string ends right in the middle of a tag.
There does not seem to be a miximum length that would cause an issue: I have strings of 18k that are incomplete and I have strings of 80k that are incomplete as well.
The XML structure is fairly simple and only about 6-8 nodes deep.
Am I missing something?

A: xmlWriter isn't flushed at the point you call ToString(); try:
    using (var xmlWriter = XmlWriter.Create(builder))
    {
        serializer.WriteObject(xmlWriter, item);
    }
    return builder.ToString();

This does the ToString() after the Dispose() on xmlWriter, meaning it will flush any buffered data to the output (builder in this case).


text:
Q: Java multiple regex on string I'm trying to apply multiple regex on a string. I'm not able to get a good understanding on something of this matter.
I have multiple strings which would under go this replacement:
String csvFile = "/Users/john/Documents/chartFolder/chart_test_1.csv"
String chartTitle = csvFile.replaceAll("_", " ");
chartTitle = chartTitle.replaceAll(".*/", "");
chartTitle = chartTitle.replaceAll("\\..*", "");

I'd like the output to be -
chart test 1

which I achieve, but I feel is not good coding due to the multiple lines of coding.
If someone could please explain if it can be done in 1 line and how they come up with the solution, without just posting the solution that would be great.

A: You can concatinate all the replace Statements:
String chartTitle = csvFile.replaceAll("_", " ").replaceAll(".*/", "").replaceAll("\\..*", "");

A: You can do it with one replace, like this:
String chartTitle = csvFile.replaceAll(".*/|_|\\..*", " ").trim();

This uses an *alternation" to match all three targets, then replace them all with a space, which leaves a space at either end, which are then removed using trim().
The main problem with your idea, for which there is no work around, is that replaceAll()'s replacement term can't vary depending on the match.
You may also be interested to know that replace() still replaces all occurrences, it just uses a plain text pattern (not a regex), so you could code
str.replace("_",  " ")

with equal effect

A: You can save yourself some .replaceAll by building a better regular expression (which targets several substrings to replace), but only if the replacement String remains the same.
In your example:
chartTitle = chartTitle.replaceAll(".*/", "");
chartTitle = chartTitle.replaceAll("\\..*", "");

Can be grouped as you replace  matches with the same substring (here : ""). You can use the "or" operator to build a "grouped" regular expression.
Otherwise, you have to call this function several times.


text:
Q: how to properly create my own custom items and triggers for zabbix 4 :)
I have Zabbix 4.4.1 installed on Ubuntu 19.10.
I have a postgresql plugin configured and working properly so it checks my database metrics.
I have a a table that I want to check a timestamp column for the last inserted row. column name is insert_time.
if the last inserted row have a insert time of more then 5 minutes to product warning and 10 minutes to product error.
I'm new to zabbix.. all I did so far is for googling, not sure if that's the way to go.. it's probably not cause it's not working :)
ok so first thing I did is created a bash files at /etc/zabbix/mytools, get-last-insert-time.sh.
I perform the query and send the output to zabbix_sender with the following template:
#!/bin/bash
PGPASSWORD=<PASSWORD> -U <USER> <DB> -t -c "<RELEVANT QUERY>" | awk '{$1=$1};1' | tr -d "\n" | xargs -I {} /usr/bin/zabbix_sender -z $ZABBIXSERVER -p $ZABBIXPORT  -s $ZABBIXAGENT -k "my.pgsql.cdr.last_insert_time" -o {}

is there a way to test this step? how can I make sure that zabbix_sender receives that information? is there some kind of.. zabbix_sender_sniffer of some sort ? :)
next.. I created a configuration files at /etc/zabbix/zabbix_agentd.d called get-last-insert-time.conf with the following template:
UserParameter=my_pgsql_cdr_last_insert_time,/etc/zabbix/mytools/get-last-insert-time.sh;echo $?

here the key is my_pgsql_cdr_last_insert_time while the key in zabbix_sender is my.pgsql.cdr.last_insert_time. as far as I understand these should be two different keys.
why?!
then I created a template and attached it to the relevant host and I created 2 items for it:

*

*item for insert time with the key my.pgsql.cdr.last_insert_time and of type Zabbix Trapper

*a Zabbix Agent item with the key my_pgsql_cdr_last_insert_time Type of information: text.

is that the type of information for timestamp ?
now on Overview -> latest data I see:
CDR last insert time with no data
and  Run my database trappers insert time that is... the text is disabled? it's in gray.. and there is also no data.
so before I begin to create an alert. what did I do wrong ?
any information regarding this issue would be greatly appreciated.
update
thanks Jan Garaj for this valuable information.
I was expecting that creating such a trigger should be easier then what I found on google, glad to see I was correct.
I edited my bash scripts to return seconds since epoch, since it's from postgresql it returns float, so I configured the items as float. I do see in latest data that the items receive the proper values.
I created triggers, I made sure that the warning trigger depends on the critical trigger so they won't both appear on the same time.
for example I created this trigger {cdrs:pgsql.cdr.last_insert_time.fuzzytime(300)}=0 so if the last insert time is greater then 5 minutes to return a critical error. the problem is that it returns a critical error.. always! even when it shouldn't. I couldn't find a way to debug this. so besides actually getting the triggers to work properly everything else is well configured.
any ideas ?
update 2
when I configured the script to return a timestamp, I changed it to a different timezone instead of living it as it is, which actually compared the data with current time + 2 hours in the future :)
I found that out while going to latest data, checking the timestamp and converting it to actual time. so everything works now thanks a lot!

A: It looks over complicated, because you are mixing sender with agent approach. Simpler approach - agent only:
UserParameter=pgsql.cdr.last_insert_time,/etc/zabbix/mytools/get-last-insert-time.sh

Script /etc/zabbix/mytools/get-last-insert-time.sh returns last insert Unix timestamp only, e.g.1574111464 (no new line and don't use zabbix_sender in the script). Keep in mind, that zabbix agent uses zabbix user usually, so you need to configure proper script (exec) permissions, eventually env variables.
Test it with zabbix-get from the Zabbix server, e.g.:
zabbix_get -s <HOST IP> -p 10050 -k "pgsql.cdr.last_insert_time"

For any issue on the agent side: increase log agent level and watch agent logs
When you sort agent part, then create template with item key pgsql.cdr.last_insert_time and Numeric (unsigned) type. Trigger can use fuzzytime(60) function.


text:
Q: Loading Static Content pdf2Html Itext 7 Good afternoon.
I am trying to load static content for my Html to PDF converstion using Itext 7's PdfHTML add-on.
At this point I am just doing a hello world example following the boilerplate example on their Website:
My code doesn't deveate from that in significant anyway.  The only difference is that i am setting up a ConverterProperties object and adding that to the call.
ConverterProperties converterProperties = new ConverterProperties()
                .setBaseUri("https://randomURIforReelzBro.com/");
        HtmlConverter.convertToPdf(new FileInputStream("src/htmldocs/randomHTMLforReelzBro.html"), new FileOutputStream(dest), converterProperties);

The content exists on my vpn and I can access it from the runtime of my IDE.
So if I put the full path of that URI in my browser I can clearly see the content (in this instance a JPEG).  The converted PDF is not seeing it however.  Am I missing something simple?  It is supposed to be a relative path according to the documentation on Itext's Website.  Should I only include the part of the path's that are common to all the Content Resources that my html page is using?  If you have any ideas let me know.  If I figure something out I will write up my answer for any one else struggling with this issue.
After doing a little bit of experimentation, it would appear as though the Jar has a very random response to locally hosted content.  I thought it might be a difference in https versus http but, I found examples of each that loaded and examples of others that didn't load.  All the content loads in a browser (obviously).  Also, setting the Base URI seems to have no effect whatsoever on the outcome?  I would say that is strange.  Any ideas anyone?  Particularly someone from the IText team?

A: After looking into this issue it turns out that because the images were in a background tag of a Table Data element, The htmlToPDF wasn't even finding the images.
Background images in  elements are deprecated so I think Itext 7 Doesn't do anything with them.
After migrating the Images to a Style tag in the header:
<style>
    .blueimage1 {background-image: url("https://randomstaticcontent.screwy/random.gif"); }
    .blueimage2 {background-image: url("https://randomstaticcontent.screwy/randomA1.gif"); }
</style>

iText 7 was able to find the Static content and create the PDF.
Moral of the story, Search your HTML for deprecated tags before running through IText.


text:
Q: Appending lists using multiprocessing pool I am new to python, and the multiprocessing module. I created a far simplified version of what I am trying to accomplish to distill my problem. The issue is that the variables don't seem to update when called outside of the function where they are appended/the worker processes .
After researching I thought it might have something to do with queues? However, I believe queues to be more about sharing memory between the processes which I don't believe is required in my situation, since each list could be appended independently.
from multiprocessing import Pool

def build(array):
    array.append("hello")
    return array

if __name__== '__main__':
    x=["yo","sup"]
    y=["blah", "blah"]
    z=["apple","banana"]
    w=["cats", "dogs"]

    p=Pool(4)
    p.map(build,[x,y,z,w])
    p.close()
    p.join()

    print x, y, z, w

When I run the code above, it simply returns x,y,z,w as imputed without appending "hello" to each list and I cannot figure out why. I know that if I put the print statement at the end of the function build that it will output the appended lists. I also realize that I could do the following:
results = p.map(build,[x,y,z,w])

print results

However, in my actual project I need to utilize x, y, z, w later and would prefer not to index results to get the list I am looking for. Is there anyway to have the changes made to the lists stick, so to speak, outside of the worker processes?

A: Each process has its own memory heap so your lists are copied to the Process Pool workers memory and are changed only there


text:
Q: Invalid hook call on save, not edit when using swiper slider I have installed swiper slider (react version) and created a custom block. When I add the block in the backend it works swimmingly and I can swipe just fine. But when I save and view in the frontend nothing appears. When I check the error messages after refreshing in the backend I see this message:

Uncaught Error: Invalid hook call. Hooks can only be called inside of
the body of a function component. This could happen for one of the
following reasons:

*

*You might have mismatching versions of React and the renderer (such as React DOM)

*You might be breaking the Rules of Hooks

*You might have more than one copy of React in the same app

import { registerBlockType } from "@wordpress/blocks";
import { useBlockProps } from "@wordpress/block-editor";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";

import "./editor.scss";
import "./style.scss";

import json from "./block.json";
import { __ } from "@wordpress/i18n";
const { name, ...settings } = json;

registerBlockType(name, {
    ...settings,
    edit: (props) => {
        return (

                <Swiper
                    spaceBetween={50}
                    slidesPerView={3}
                    onSlideChange={() => console.log("slide change")}
                    onSwiper={(swiper) => console.log(swiper)}
                >
                    <SwiperSlide>Slide 1</SwiperSlide>
                    <SwiperSlide>Slide 2</SwiperSlide>
                    <SwiperSlide>Slide 3</SwiperSlide>
                    <SwiperSlide>Slide 4</SwiperSlide>
                </Swiper>

        );
    },
    save: () => {
        return (

                <Swiper spaceBetween={50} slidesPerView={3}>
                    <SwiperSlide>Slide 1</SwiperSlide>
                    <SwiperSlide>Slide 2</SwiperSlide>
                    <SwiperSlide>Slide 3</SwiperSlide>
                    <SwiperSlide>Slide 4</SwiperSlide>
                </Swiper>

        );
    },
});

A: You've misunderstood the purpose of the save component. The goal of the save component is not to return an interactive React component, it's to return something that can be converted into static HTML and saved in the database as a string in the post content.
Since only the HTML gets saved, it's your responsibility to load javascript on the frontend that finds this HTML and converts it into a Swiper slider.
So you should not attempt to do any of the following in the save component, directly or indirectly via a library:

*

*event listeners

*react state

*callbacks/effects/HTTP requests/etc

A save component can even be ran when no saving is occurring, for example when validating a block by comparing the saved block to the save component.
So with this in mind, it makes no sense to use <Swiper> or <SwiperSlide> components here.
Instead, follow the Swiper documentation and generate actual HTML instead:

Slide 1

Slide 2

Slide 3

    ...

https://swiperjs.com/get-started#add-swiper-html-layout
Adjust it for JSX and save it that way.

As an aside, the way the Swiper library detects the slides in the <Swiper> component is by inspecting the virtual dom and looking for direct descendants of type <SwiperSlide>. This means it cannot find the slides if you use Slide blocks. This means having user configurable slides is not possible in Gutenberg because of the higher order components used to provide block information. It's not possible to have nested blocks this way. Swiper will interpret child blocks as additional HTML to append after the slider, even if they're slides or <SwiperSlide> components.


text:
Q: Scala overloading Methods I have a little question about this piece of code (which does not compile) :
       def avg(seq: Seq[Int]): Double = seq.sum.toDouble/seq.length
       def avg(seq: Seq[Double]): Double = seq.sum/seq.length

the idea is simple as shown above, the first method calculates the average to a sequence of integers, and the second does the same to a seq of Doubles
but it gives me a compilation error around repetition, I want to know why...and if you have a much Scala approach than this code to perform the same idea please, share it in your answer
Thank you

A: The problem is due to type erasure, which can be overcome by using the Numeric type class.
def avg[N:Numeric](ns :Seq[N]) :Double =
  implicitly[Numeric[N]].toDouble(ns.sum) / ns.length

avg(List(3, 5, 7, 11))           //res0: Double = 6.5
avg(Vector(9.2, 3.3, 1.7, 21.1)) //res1: Double = 8.825

You can also place it in an implicit class for a more concise expression.
implicit class GetAvg[N:Numeric](ns :Seq[N]) {
  def avg :Double = implicitly[Numeric[N]].toDouble(ns.sum) / ns.length
}

Stream(3, 5, 7, 11).avg      //res2: Double = 6.5
Seq(9.2, 3.3, 1.7, 21.1).avg //res3: Double = 8.825


text:
Q: Why are decisions "made" instead of "done"? Typically when we've decided something, we say we've "made a decision". But why is a decision associated with the verb "to make"? Nothing is being made. If anything, it seems a decision should be "done", and associated with the verb "to do".
Why do we make them instead of doing them? Or deciding them?

A: For me it has more to do with intent vs action. A decision is made but that does not mean that the deed will be done. A decision is a thought process, not a physical action, and it comes before the action is completed. The verb "to do," implies an action with a result or, conjugated, describes an attribute.


text:
Q: Are jQuery Selector Rules Changing for Newer Browsers? I just ran this jsPerf test in Chrome 18 and found that .class performs significantly better than tag.class despite the myriad of resources that say otherwise. I know this questions was recently asked on SO but without a definitive / satisfactory answer other than "don't use jQuery". Can someone shed some light on the latest best practices?
NOTE: Assume clarity and semantics are taken care of (e.g. I have a class on an anchor tag called item-link it's going to come off just as clear with a.item-link as it will .item-link).

A: You're asking about best practices, so I would lean more toward the way that is more readable vs. one that can possibly shave a microsecond off your script runtime.

A: The latest browsers have a better implementation of getElementsByClassName and hence when you use jquerys class selector only it immediately fallsback to this method and hence the performance difference and gain.
When you precede it with a tag selector firstly jquery needs to process your selector and then break it down to the different tokens and then it goes about searching for the control, not sure what order is followed here, whether all elements with the className is retrieved first and then the additional selector is applied or vice versa but I am sure you can research it by looking at the jquery source code..
And regarding the debate readable or not, I am not sure what you stand to gain by knowing that  the selector is on an what control, if that is what you need then well name your classes better for gods sake..What next precede ids with tagname?? :/


text:
Q: Update Vector3 array from C++ native plugin Marshal.Copy() Method only supports a few array types. Now I only know how to copy from IntPtr(pointing to a float array from C++ code) to float[].
IntPtr pvertices = GetVerticesFromCPP();
float[] vertices = new float[nVertices * 3];
Marshal.Copy(pvertices, vertices, 0, nVertices * 3);

But what I really want is a UnityEngine.Vector3[].
Do I need to manually convert float[] to UnityEngine.Vector3[]? Or is there a simpler and faster way that directly do this?

A:
Do I need to manually convert float[] to UnityEngine.Vector3[]? Or is
  there a simpler and faster way that directly do this?

Yes, you have to do that manually but there is a better way to do this.
I will assume that you need to modify a Vector3 on the native side then return the result. There is no need to use float array for this. Just create a Vector3 struct on the C++ side then use pointer to pass it between C++ and C#. Do not return the Vector3 array from C++, create it on the C# side, then pass it to the C++ function to modify and apply the changes to the argument.
C++:
This requires that you enable the unsafe keyword in Unity.
struct Vector3
{
     float x;
     float y;
     float z;
};

then your function:
extern "C" void UpdateVectorArray(Vector3* vecArray, int vecSize)
{
    for(int i = 0; i < vecSize; ++i)
    {
        //Simply modify each Vector reference
        Vector3 &vec = vecArray[i];
        vec.x = 11;
        vec.y = 20;
        vec.z = 55;
    }
}

C#:
[DllImport("Plugin Name")]
static unsafe extern void UpdateVectorArray(Vector3* vecArray, int vecSize);

void UpdateVectorArray(Vector3[] vecArray)
{
    unsafe
    {
        //Pin array then send to C++
        fixed (Vector3* vecPtr = vecArray)
        {
            UpdateVectorArray(vecPtr, vecArray.Length);
        }
    }
}

Usage:
Get vertices from model, send to C++ and modify it the re-assign the modified mesh:
void Start()
{
    Mesh mesh = GetComponent<MeshFilter>().mesh;

    Vector3[] vertices = mesh.vertices;
    UpdateVectorArray(vertices);

    //Re-assign the modified mesh
    mesh.vertices = vertices;
    mesh.RecalculateBounds();
}

To avoid using the unsafe keyword in Unity use the [In, Out]  attribute.
[DllImport("Plugin Name")]
static extern void UpdateVectorArray([In, Out] Vector3[] vecArray, int vecSize);

void Start()
{
    Mesh mesh = GetComponent<MeshFilter>().mesh;

    Vector3[] vertices = mesh.vertices;
    UpdateVectorArray(vertices, vertices.Length);

    mesh.vertices = vertices;
    mesh.RecalculateBounds();
}

The C++ side remains the-same. You can also use the GCHandle to pin the array and avoid using the  unsafe keyword  but the unsafe keyword solution is better and faster.


text:
Q: Spinning element for form submit button I am trying to include a spinning element for Bootstrap input loading text, as described in this example, but I am getting row string instead of actual html element. Can anyone give a hint why this could happen ?
JSFIddle provided
<input type = 'submit'
       class="btn btn-primary btm-sm pull-right" value="Оформить договор"
       data-loading-text=" @Localization.Uploading">

A: It's because it is calling the button instead of the input
CodePen
HTML
<button type='submit' class="btn btn-primary btm-sm pull-right" value="Оформить договор" data-loading-text=" @Localization.Uploading">Оформить договор</button>

JS
$('.btn').on('click', function() {
    var $this = $(this);
  $this.button('loading');
    setTimeout(function() {
       $this.button('reset');
   }, 8000);
});


text:
Q: Javascript Promises, Returned Promise of then and catch method Was fooling around a bit with Promises, here is the code:

let prom1 = new Promise((res, rej) => {
  res('res');
});

const resolvedProm1 = prom1.then((val) => {
  return val
});
console.log(resolvedProm1);

let prom2 = new Promise((res, rej) => {
  rej('rej');
});

const resolvedProm2 = prom2.catch((err) => {
  return err
});
console.log(resolvedProm2);

The chrome devtools shows the following information about the promises:

However, I didn't expect this particular output. What I expected was the following:

*

*Both resolvedProm1 and resolvedProm2 would be <fullfilled> Promises instead of <pending>. Why are they pending and not fullfilled?

*The resolvedProm2 was rejected, why does the promiseStatus shows that it is resolved?

A: In both cases promises printed before they are resolved. What you send into promise context will always execute after your current callstack unwinds, so consoles till the end of a function run first.

A:
Both resolvedProm1 and resolvedProm2 would be  Promises instead of . Why are they pending and not fullfilled?

Because they are resolved asynchronously. You were logging them while they still were pending. You'll notice if you put some console.log statements in your then and catch callbacks that the callbacks weren't executed yet as well.
You only get the [[PromiseStatus]] as "resolved"  (which really should be "fulfilled") when you inspect the promise value in the devtools, which you do after they were resolved.

The resolvedProm2 was rejected, why does the promiseStatus shows that it is resolved?

No, you were rejecting the prom2. The resolvedProm2 is the result of the .catch() invocation, whose callback did handle the rejection and returned a non-error result.


text:
Q: Azure github deployment with private submodule I am trying to deploy private repository with github onto Azure and it used to work perfectly until I made a piece of repository into separate private submodule that is also hosted on github.
Now, every time I try to deploy to Azure it breaks during submodule deployment with following message:
fatal: could not read Username for 'https://github.com'
What can I do to fix it?

A: As in this issue (or this question), check the remote url of your main repo, and of your submodule
cd /path/to/repo
git remote -v
cd path/to/submodule
git remote -v

You could switch the url of the submodule to an ssh one instead of an https, add, commit and push the parent repo (to record the change), and then deploy again.


text:
Q: How to determine Tikhonov regularization parameter using standard deviation? I have a linear ill posed problem with the form:
$$Ax=b.$$
One approach to this problem is Tikhonov regularization, replacing it with
$$\min_x( \|Ax-b\|^2+\alpha\|x\|^2 ).$$
In https://en.wikipedia.org/wiki/Tikhonov_regularization said that you can use covariance matrix of dataset to find optimal regularisation parameter for Tikhonov regularization. I also heard in a conference that a resolution matrix can be very useful in this task.
What is the resolution matrix of a linear problem, what does it mean?
and more important: How can I use standard deviation of my data to determine Tikhonov regularization parameter?

A: It seems to be measurement concatenated with inversion.
$$R^M = (\hat S ^\dagger \hat S)$$
where I presume $^\dagger$ is some pseudo-inverse.
according to this source http://www.resistivity.net/dc2dinvres/invres.pdf
In other words what something looks like according to the model.
The error would be $I-R^M$ real data minus what the model can catpure.


text:
Q: Adding a class to a tag I want to add a class to my

some content is here...

Here is how I tried to do that but it's not working:
$('#equipmentTypeContent').addClass("singleEquipmentText");

I don't know if in this case jQuery needs to know what type of element it is (in this case a  tag) in addition to the type of tag?  I doubt it, I think it only needs the id of the element you're manipulating right?

A: Your code seems fine but you need to wrap your code in ready handler:
$(function(){
  $('#equipmentTypeContent').addClass("singleEquipmentText");
});

Also make sure that you have loaded jQuery on your page.

A: There's nothing wrong with your code. See the working copy on jsFiddle

A: Here is a fiddle showing how to do it (and proving it by returning the updated class of the p element) after a selection is changed in a dropdown.
I'm using the jQuery .change() function to execute certain code after the value of the select element is changed. In this case, I take the value of the select element, strip the spaces, and add the resulting, space-free string as a class to the p element.

A: Nothing wrong with your code try with with jquery ready function if the script is above your HTML
$(document).ready(function(){
  $('#equipmentTypeContent').addClass("singleEquipmentText");
});

YOu can access using the class too if you want to add to all of them with that class
$(document).ready(function(){
  $('.formField').addClass("singleEquipmentText");
});


text:
Q: about c++ conversion : no known conversion for argument 1 from '[some_class]' to '[some_class]&' I'm working on C++, and had an error that I didn't know the exact reason. I've found the solution, but still want to know why.
    class Base
    {
        public:
               void something(Base& b){}
    };

    int main()
    {
        Base b;
        b.something(Base());
        return 0;
    }

when I compile the code, I got this following error :
abc.cpp:12:20: error: no matching function for call to 'Base::something(Base)'
abc.cpp:12:20: note: candidate is:
abc.cpp:6:7: note: void Base::something(Base&)
abc.cpp:6:7: note:   no known conversion for argument 1 from 'Base' to 'Base&'

but when I replaced b.something(Base()) into
Base c;
b.something(c);

the error is gone, I'm wondering why??? aren't they have the same type? It only matters how I write it, but the meaning should be the same???
Thanks Guys!

A: You are passing a temporary Base object here:
b.something(Base());

but you try to bind that to a non-const lvalue reference here:
void something(Base& b){}

This is not allowed in standard C++. You need a const reference.
void something(const Base& b){}

When you do this:
Base c;
b.something(c);

you are not passing a temporary. The non-const reference binds to c.

A: In the first case you attempt to pass a (non-const)reference to a temporary as argument to a function which is not possible. In the second case you pass a reference to an existing object which is perfectly valid.


text:
Q: LinkedList in Delphi or Alternative I need to linkedlist. I googled but couldn' t find any example about this.
Is there a linkedlist in Delphi or any alternative suggest?
Here is Java e.g:
private LinkedList<JPIPDataSegment> jpipDataList;