text:
Q: Natural Language Processing - Converting Text Features Into Feature Vectors So I've been working on a natural language processing project in which I need to classify different styles of writing. Assuming that semantic features from texts have already been extracted for me, I plan to use Weka in Java to train SVM classifiers using these features that can be used to classify other different texts.
The part I'm having trouble on is that to train an SVM, the features must be converted into a feature vector. I'm not sure how you would be able to represent features such as vocabulary richness, n-grams, punctuation, number of paragraphs, and paragraph length as numbers in a vector. If somebody could point in the right direction, that would be greatly appreciated.

A: I'm not sure what values your attributes can take on, but perhaps this example will help you:
Suppose we are conducting a supervised learning experiment to try to determine if a period marks the end of a sentence or not, EOS and NEOS respectively.  The training data came from normal sentences in a paragraph style format, but were transformed to the following vector model:

*

*Column 1: Class: End-of-Sentence or Not-End-of-Sentence

*Columns 2-8: The +/- 3 words surrounding the period in question

*Columns 9,10: The number of words to the left/right, respectively, of the period before the next reliable sentence delimiter (e.g. ?, ! or a paragraph marker).

*Column 11: The number of spaces following the period.

Of course, this is not a very complicated problem to solve, but it's a nice little introduction to Weka.  We can't just use the words as features (really high dimensional space), but we can take their POS (part of speech) tags.  We can also extract the length of words, whether or not the word was capitalized, etc.
So, you could feed anything as testing data, so long as you're able to transform it into the vector model above and extract the features used in the .arff.
The following (very small portion of) .arff file was used for determining whether a period in a sentence marked the end of or not:
@relation period

@attribute minus_three {'CC', 'CD', 'DT', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNPS', 'NNS', 'NP', 'PDT', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP','WRB', 'NUM', 'PUNC', 'NEND', 'RAND'}
@attribute minus_three_length real
@attribute minus_three_case {'UC','LC','NA'}
@attribute minus_two {'CC', 'CD', 'DT', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNPS', 'NNS', 'NP', 'PDT', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP','WRB', 'NUM', 'PUNC', 'NEND', 'RAND'}
@attribute minus_two_length real
@attribute minus_two_case {'UC','LC','NA'}
@attribute minus_one {'CC', 'CD', 'DT', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNPS', 'NNS', 'NP', 'PDT', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP','WRB', 'NUM', 'PUNC', 'NEND', 'RAND'}
@attribute minus_one_length real
@attribute minus_one_case {'UC','LC','NA'}
@attribute plus_one {'CC', 'CD', 'DT', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNPS', 'NNS', 'NP', 'PDT', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP','WRB', 'NUM', 'PUNC', 'NEND', 'RAND'}
@attribute plus_one_length real
@attribute plus_one_case {'UC','LC','NA'}
@attribute plus_two {'CC', 'CD', 'DT', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNPS', 'NNS', 'NP', 'PDT', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP','WRB', 'NUM', 'PUNC', 'NEND', 'RAND'}
@attribute plus_two_length real
@attribute plus_two_case {'UC','LC','NA'}
@attribute plus_three {'CC', 'CD', 'DT', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNPS', 'NNS', 'NP', 'PDT', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP','WRB', 'NUM', 'PUNC', 'NEND', 'RAND'}
@attribute plus_three_length real
@attribute plus_three_case {'UC','LC','NA'}
@attribute left_before_reliable real
@attribute right_before_reliable real
@attribute spaces_follow_period real
@attribute class  {'EOS','NEOS'}

@data

VBP, 2, LC,NP, 4, UC,NN, 1, UC,NP, 6, UC,NEND, 1, NA,NN, 7, LC,31,47,1,NEOS
NNS, 10, LC,RBR, 4, LC,VBN, 5, LC,?, 3, NA,NP, 6, UC,NP, 6, UC,93,0,0,EOS
VBD, 4, LC,RB, 2, LC,RP, 4, LC,CC, 3, UC,UH, 5, LC,VBP, 2, LC,19,17,2,EOS

As you can see, each attribute can take on whatever you want it to:

*

*real denotes a real number

*I made up LC and UC to denote upper case and lower case,  respectively

*Most of the other values are POS tags

You need to figure out exactly what your features are, and what values you'll use to represent/classify them. Then, you need to transform your data into the format defined by your .arff.
To touch on your punctuation question, let's suppose that we have sentences that all end in . or ?. You can have an attribute called punc, which takes two values:
@attribute punc {'p','q'}

I didn't use ? because that is what is (conventionally) assigned when a data point is missing. Our you could have boolean attributes that indicates whether a character or what have you was present (with 0, 1 or false, true).  Another example,  but for quality:
@attribute quality {'great','good', 'poor'}

How you determine said classification is up to you,  but the above should get you started.  Good luck.


text:
Q: load json files in google cloud storage into big query table I am trying to do it with client lib using python.
the problem I am facing is that the TIMESTAMP on the JSON files are on Unix epoch TIMESTAMP format and big query can't detect that:
according to documentation:

so I wonder what to do?
I thought about changing the JSON format manually before I load it into BigQuery table?
Or maybe looking for an auto conversion from the BigQuery side?
I wondered across the internet and could not find anything useful yet.
Thanks in advance for any support.

A: You have 2 solutions

*

*Either you update the format before the BigQuery integration

*Or you update the format after the BigQuery integration

Before
Before means updating your JSON (manually or by script) or to update it by the process that load the JSON into BigQuery (like Dataflow).
I personally don't like this, file handling are never funny and efficient.
After
In this case, you let BigQuery loading your JSON file into a temporary table and convert your UNIX timestamp into a Number or a String. Then, perform a request into this temporary table, convert the field in the correct timestamp format, and insert the data in the final table.
This way is smoother and easier (a simple SQL query to write). However, it implies cost to read all the loaded data (to write them then)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there different environment (Dev, Stage, Production) mode in Cloudfoundry? Is there different environment (Dev, Stage, Production) mode in Cloudfoundry?
Recently I move my Spring MVC application from local setup to CloudFoundry setup thr STS CloudFoundry plugin(just one click to public, awesome feature).
Is there any environment mode i.e. Dev, Stage mode so that I will deploy my application in Dev and Stage env? So tester will do there job and developer will develop new functionality.

A: There is no strong concept of an "environment" in Cloud Foundry, but there will be a notion of space in the upcoming version that may be used for that very purpose (and other things). You can read more about it here : http://blog.cloudfoundry.org/2012/06/20/heads-up-on-some-new-cloud-controller-features/
For the time being, you can deploy your app multiple times giving it different names (and hence URLs) in the scope of your Cloud Foundry account, OR you can use different accounts if you want to restrict who can do what


text:
Q: HDMI output missing from JACK I'm trying to take advantage of the HDMI audio output on my video card within JACK, but the HDMI output device doesn't appear within JACK. I've created a zip file full of documentation, which you can retrieve from my GDrive here: https://drive.google.com/file/d/1g0LhZo3A3bEE8_Ef2M9lzV-pJkGkU60-/view?usp=sharing

*

*Output from dmesg

*Output from aplay -l

*Output from aplay -L

*Output from inxi -Fxxxrz

*Screenshot of PulseAudio Volume Control, showing that the HDMI output device exists and works

*Screenshot of Cadence before JACK is started

*Screenshot of JACK configuration

*Screenshot of Catia after starting JACK, showing that the HDMI output device is missing

*Screenshot of several windows illustrating that the PulseAudio to JACK bridge works

I hope it's something simple that I just haven't learned yet. Any help is greatly appreciated.


text:
Q: Use of "mass" in Bullet I am sorry to ask such a basic question about bullet. However, I am having an issue. Here is the setup:
I have a world with no gravity. When I press a key, a 1x1x1 box is created in the center of the world. When I right click, a box of size 0.05*0.05*0.05 is create at the camera position, and is 'shot' in the direction you are looking. Here is where the trouble begins.
When a small cube hits a large cube, the interaction seems wrong. You would expcet a box 1/8000th the size of another to have very little effect. Yet the large cube goes flying, as if  it been with a cube of its same size. I assumed it is because I created both objects with the same mass.
To confirm this, I apply an upward force of 1 newton (or whatever unit bullet uses). Both objects accelerate at the same rate.
My code for creating objects is as follows:
btMotionState *state = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)));
btConvexHullShape* shape = new btConvexHullShape();
for(unsigned int i = 0; i < vertices.size(); ++i) {
    shape->addPoint(toBt(vertices[i]));
}
shape->setMargin(0.01f);

btScalar mass = 1.f;
btVector3 inertia;
shape->calculateLocalInertia(mass, inertia);
shape->setMargin(0.01f);
btRigidBody::btRigidBodyConstructionInfo ci(mass, state, shape, inertia);
body = new btRigidBody(ci);

I expect that the btScalar mass = 1.f; line is the culprit.
Am I expected to calculate the mass of my objects? This is simple enough for a cube, but what about some weird convex shape? Is there any way I can get bullet to do this for me?

A: Yes, mass is the culprit. Think about your big box being an empty wooden crate and your small box being a solid cube of iron. Huge difference in size but equal mass. Now your physics seem correct, right?
Yes, you are expected to provide the mass. Whether you calculate it or just state "this box weighs 20kg" is up to you. Actually expecting someone else to calculate the mass for you just makes your problem worse, because you'd have to specify materials, material density, and material distribution of your objects besides its geometry. If you want to go that way there are plenty of other tools available to aid you with such calculations. But I'm sure you agree that just stating some mass through trial and error is easier by far.


text:
Q: How to add a health check in .NET 5 for MassTransit Amazon SQS? I have a working and running .NET 5 application. There is a REST API to POST data. When data is posted, a MassTransit message is published. Using the AWS Explorer, I can clearly see that if the topic named customerinfo.fifo does not exist, it is created in Amazon by my application. Apparently, my application does something useful with Amazon SQS/SNS. I like that.
What I do not like, is that when adding a health check, an error appears causing my health check to be "Unhealthy" (after calling http://localhost:5000/health/ready ). This should not happen as my application is working fine and being able to publish messages. Logically, an "Unhealthy" status should only occur when there is something wrong. Here is my code responsible for the health check. This is part of the ConfigureServices method.
        services.AddHealthChecks();
        services.Configure<HealthCheckPublisherOptions>(options =>
        {
            options.Delay = TimeSpan.FromSeconds(2);
            options.Predicate = (check) => check.Tags.Contains("ready");
        });

To use the added health check, the following code is added to the Configure method.
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHealthChecks("/health/ready", new HealthCheckOptions()
            {
                Predicate = (check) => check.Tags.Contains("ready"),
            });

            endpoints.MapHealthChecks("/health/live", new HealthCheckOptions());
        });

This code shown above is basically how it is documented in the MassTransit documentation. Moreover, I also have code to add MassTransit SQS itself.  I have specific extension method for this:
    public static void UseMassTransit(this IServiceCollection services, MassTransitConfiguration massTransitConfiguration)
    {
        services.AddMassTransit(x =>
        {
            x.AddConsumer<CustomerChangeConsumer>();
            x.UsingAmazonSqs((context, cfg) =>
            {
                cfg.Host(massTransitConfiguration.Host, h =>
                {
                    h.AccessKey(massTransitConfiguration.AccessKey);
                    h.SecretKey(massTransitConfiguration.SecretKey);
                    h.EnableScopedTopics();
                });

                cfg.ReceiveEndpoint("CustomerChangeConsumer",
                    configurator =>
                    {
                        configurator.ConfigureConsumer<CustomerChangeConsumer>(context);
                    });

                cfg.Message<CustomerUpdate>(x =>
                {
                    x.SetEntityName("customerupdate.fifo");
                });

                cfg.Publish<CustomerUpdate>(x =>
                {
                    x.TopicAttributes["FifoTopic"] = "true";
                });
            });
        });
        services.AddMassTransitHostedService();
    }

To solve this problem, two solution types are possible:

*

*Just remove the MassTransit health check. It cannot fail it is not there any more.I need to find a way to implement a SQS/SNS health check myself when choosing such a solution.

*Fix (my?) code in order to make the health check work properly.

Obviously, the last one is preferred but for both solution types, I have no idea how to implement them.
To further clarify my problem, the logged error message when doing a health check is shown here.

fail:
Microsoft.Extensions.Diagnostics.HealthChecks.DefaultHealthCheckService[103]
Health check masstransit-bus completed after 13.2985ms with status Unhealthy and description 'Not ready: not started'
MassTransit.AmazonSqsTransport.Exceptions.AmazonSqsConnectionException:
ReceiveTransport faulted: https://eu-west-2/
---> Amazon.SQS.AmazonSQSException: Access to the resource https://sqs.eu-west-2.amazonaws.com/ is denied.
---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException'
was thrown.
at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken
cancellationToken)
at Amazon.Runtime.Internal.HttpHandler1.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext) at Amazon.SQS.Internal.ValidationResponseHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext) --- End of inner exception stack trace --- at GreenPipes.Caching.Internals.NodeValueFactory1.CreateValue()
at GreenPipes.Caching.Internals.NodeTracker1.AddNode(INodeValueFactory1
nodeValueFactory)
--- End of inner exception stack trace ---
at MassTransit.Transports.ReceiveTransport1.ReceiveTransportAgent.RunTransport() at MassTransit.Transports.ReceiveTransport1.ReceiveTransportAgent.Run()

I really hope there someone can help me with this. It is so strange. MassTransit and SQS/SNS are working fine together. The only problem is that the health check denies that, which is really frustrating.

A: I found some link where they say you need to define the custom health check like below
https://github.com/MassTransit/MassTransit/issues/1513#issuecomment-554943164

A: Have you tried to set Autostart = true? It helped me with RabbitMq so possibly it will help you as well.
mt.UsingAmazonSqs((context, cfg) =>
            {
                cfg.Host(massTransitConfiguration.Host, h =>
                {
                    h.AccessKey(massTransitConfiguration.AccessKey);
                    h.SecretKey(massTransitConfiguration.SecretKey);
                    h.EnableScopedTopics();
                });

                cfg.AutoStart = true;

                cfg.ReceiveEndpoint("CustomerChangeConsumer",
                    configurator =>
                    {
                        configurator.ConfigureConsumer<CustomerChangeConsumer>(context);
                    });

                cfg.Message<CustomerUpdate>(x =>
                {
                    x.SetEntityName("customerupdate.fifo");
                });

                cfg.Publish<CustomerUpdate>(x =>
                {
                    x.TopicAttributes["FifoTopic"] = "true";
                });
            });


text:
Q: Why is my neg_mean_squared_error a positive number for AdaBoostRegressor? When tuning AdaBoostRegressor using sklearn's cross_val_score with scoring='neg_mean_squared_error', it returns a positive number. All of my other algorithms (linear regression, svr, randomforestregressor, etc) return negative numbers. Then I compute the mean of the RMSE scores using np.mean(np.sqrt(-cross_val_score)).
Here's the code:
# AdaBoost Reg CV
start_time = time.time() # Timing

# Metrics
ada_reg_cv = AdaBoostRegressor(DecisionTreeRegressor(random_state=42),
                            n_estimators=200,
                            loss='linear', random_state=42)
ada_reg_cv_scores = cross_val_score(ada_reg_cv, X_train_trees, y_train,
                                    scoring='neg_mean_squared_error',
                                    cv=5)
ada_reg_cv_scores = np.sqrt(-ada_reg_cv_scores)

print('CV RMSE:', ada_reg_cv_scores.mean())
print('CV Std:', ada_reg_cv_scores.std())

# Timing
ada_reg_cv_time = (time.time() - start_time)
print('\nRunning Time: {}'.format(datetime.timedelta(seconds=ada_reg_cv_time)))

The output is actually an extremely high RMSE (way too high to be an accurate measure). I ran these lines separately and found that line 11 ada_reg_cv_scores = np.sqrt(-ada_reg_cv_scores) returns nan because it's taking the root of a negative number.
Then when I run it without the (-) sign inside the sqrt, I get the correct RMSE. So why are the 'neg_mean_squared_error' values positive?

A: Once I tuned the DecisionTreeRegressor within the AdaBoostRegressor (max_depth=5), the neg_mean_squared_error returned negative, as it should. So I'm guessing the error has something to do with how unregularized the decision tree was, as the error of the tree model was likely 0.

A: I had that error once when I had untreated categorical features in my dataset for an XGBoost model (aka the categorical features were strings still).
I had that while using cross_validate() function, such as:
evaluations = cross_validate(xgb_regressor, X_train, y_train,
                             scoring=("neg_mean_squared_error"),
                             cv=5, return_estimator=False)

Once I transformed the categorical data to numerical the problem was gone!


text:
Q: Checking if 2 of 3 string is null to do something in razor/c# i have a tabbed image and tittle i want to show and hide based on if images exist or not. There are 3 images and 3 title, i am already hiding titles if images for each of those are empty (see code). Now i have a new requirement , Hide all titles if only 1 of 3 image exist. BTW i am checking if image exist via checking "src" exist ( which is a string).
So I know i can check if all of the strings are empty like this
bool allNull = strings.All(s => s == null);

But how do i check if 2 of 3 images/string is empty?
My current solution is a simple counter then using jquery to remove titles, which works great but i want to know if there is a c#/razor answer (in cshtml file)

    @{
        int counter = 0;

        if (!string.IsNullOrEmpty(Model.BasicLevelImage.Src))
        {
            counter = counter + 1;

@Sitecore.Globalization.Translate.Text("PackageFeatureLevelBasic")

        }

        if (!string.IsNullOrEmpty(Model.ProfessionalLevelImage.Src))
        {
            counter = counter + 1;

@Sitecore.Globalization.Translate.Text("PackageFeatureLevelProfessional")

        }
        if (!string.IsNullOrEmpty(Model.PremiumLevelImage.Src))
        {
            counter = counter + 1;

@Sitecore.Globalization.Translate.Text("PackageFeatureLevelPremium")

        }

        if (counter < 2)
        {

        }
    }

    @Html.Glass().Editable(x => x.BasicLevelImage, new { @class = "resp-img active" })
    @Html.Glass().Editable(x => x.ProfessionalLevelImage, new { @class = "resp-img" })
    @Html.Glass().Editable(x => x.PremiumLevelImage, new { @class = "resp-img" })

A: Try this:
bool allNull = strings.Count(s => s == null) == 2;


text:
Q: Uncompressed file size using zlib's gzip file access function Using linux command line tool gzip I can tell the uncompressed size of a compress file using gzip -l.
I couldn't find any function like that on zlib manual section "gzip File Access Functions".
At this link, I found a solution http://www.abeel.be/content/determine-uncompressed-size-gzip-file that involves reading the last 4 bytes of the file, but I am avoiding it right now because I prefer to use lib's functions.

A: There is no reliable way to get the uncompressed size of a gzip file without decompressing, or at least decoding the whole thing.  There are three reasons.
First, the only information about the uncompressed length is four bytes at the end of the gzip file (stored in little-endian order).  By necessity, that is the length modulo 232.  So if the uncompressed length is 4 GB or more, you won't know what the length is.  You can only be certain that the uncompressed length is less than 4 GB if the compressed length is less than something like 232 / 1032 + 18, or around 4 MB.  (1032 is the maximum compression factor of deflate.)
Second, and this is worse, a gzip file may actually be a concatenation of multiple gzip streams.  Other than decoding, there is no way to find where each gzip stream ends in order to look at the four-byte uncompressed length of that piece.  (Which may be wrong anyway due to the first reason.)
Third, gzip files will sometimes have junk after the end of the gzip stream (usually zeros).  Then the last four bytes are not the length.
So gzip -l doesn't really work anyway.  As a result, there is no point in providing that function in zlib.
pigz has an option to in fact decode the entire input in order to get the actual uncompressed length: pigz -lt, which guarantees the right answer.  pigz -l does what gzip -l does, which may be wrong.


text:
Q: SSRS Remote Errors Enabled but NOT Working SSRS Remote Errors Enabled but NOT Working,
I have enabled report errors on a report server in sp integrated mode and still get the following error:
"For more information about this error navigate to the report server on the local server machine, or enable remote errors"
I have checked the report server which is reporting "remote errors = true" and the server has been restarted
Other information: I am using Report Builder 3 to develop my reports then I am publishing to SharePoint but the only appears when rendering in SP (2010 & SQL Server R2 upgrade)

A: I bet your SSRS is running on a server that is not your web front end, right?  SSRS will not pass most errors forward for the WFE to display.  Best way to debug report errors is to setup a host entry on your SSRS server and hit the reports directly from your SSRS server.  The other option if you don't have local access to the server is to set the host entry to the SSRS server on your local machine and hit it directly that way.
Hope this can help anyone who comes across this as this is an older question.

A: I had the same problem, even after I enabled remote errors in Central Admin.  Check the SharePoint site setting for the area where you store your reports.
Site Settings > Report Services > Reporting Services Site Settings and make sure "Enable remote errors in local mode" is ticked.
After ticking this, I saw the detailed error messages when I tried to open the reports.
Hope it helps!


text:
Q: filter out e-mail addresses in boolean searches I'm constructing a database with photo's.
By using a boolean search I get the right images for the used search(phrase).
Now I have this problem:
In many of the descriptions the email address of the person or subject is marked. Like my.name@telenet.be
Now, when I want to find an image of the company Telenet, I get all the records that contain a email address of the provider. Who are of no imporatance of my search.
Here is a example of my search:
SELECT ID,auteur, title, datetaken, description,
keywords,thumbnail,URL,rel_date,showa,initialen,type
FROM archief
WHERE MATCH(description, keywords) AGAINST(' +telenet ' IN BOOLEAN
MODE) AND rechten <> '0' AND showa = '1' AND type >= '2' AND rel_date
<= '20120921' ORDER BY datetaken desc LIMIT 60'
in 'where clause'

What can I do to filter out the searchphrase containing an @ symbol?

A: I think you can try REGEXP operator, in your cause it will look something like:
SELECT *
FROM archief
WHERE
    description REGEXP '[^@]telenet' OR
    keywords REGEXP '[^@]telenet'

This query should select all records which contain telenet string without preceding @ in description or keywords fields.


text:
Q: Computing the union and intersection of two unsorted arrays in O(mlogn) time Okay, so I need to devise the following algorithm (NO CODE NEEDED, just steps):
Given two sets A and B with length m and n respectively where the numbers in each set are distinct, unsorted, and m<n. Compute the intersection and union of the two sets without any duplicate values in either result. The algorithm should work in O(mlog(n)) time.
I'm having a really hard time figuring out an algorithm with such a time complexity. Initially, I wanted to concat the two unsorted arrays and then perform a merge sort on it and remove duplicates but that goes way over the alotted complexity.

A: I missread the performance requirement. The solution is in O(n log(m)) and not as required in O(m log(n) ).
The required runtime is imho not possible. The proof was sketched already in the comments. The basic idea is to go to the extrem case where A is the singleton set. Then the performance requirements boils down to check whether a given element is contained in a set B in runtime O(log(|B|)). This is to the best of my knowledge, however, only possible if B is sorted or there is some kind of indexing structure over B.

The O(blog(m)) solution
As m<n you can sort A the result is As. Sorting A is O(m log(m)) < O(m log(n) ).
Finding an element in the sorted As  is in O(log(m)). So you just need to check each instance of B and figure whether it is contained in As.
resulting runtime (abusing notation) is
O(n log(n))+ m* O(log(n)) = O(n log(n))+ O(n* log(m))=O(n log(m))


text:
Q: Difficulty using malloc and scanf I have difficulty using malloc and fscanf.
I just want to read a file and print out the result using
I got a segmentation fault error when I executed this code.
I am not sure what I have done wrong. I would be very grateful if someone points out a fix.
Here is my code:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]){
    char* buffer = (char*)malloc(*argv[1]); // Allocate memory
    if(buffer=NULL) // if *argv[1] is not existed, exit the program
        exit(1);

    int n = 0;
    FILE* fp=fopen("file.txt","r"); // Open the file
    do {
        buffer[n] =fscanf(fp,"%c",buffer); // read from file until it gets EOF
    } while(buffer[n] != EOF);
    fclose(fp); // Close the file

    printf("%s",buffer); // Print the stored string

    free(buffer); // Return the memory
    return 0;
}

A: Got it. This:
if(buffer=NULL)

should be this:
if(buffer==NULL)

You're setting buffer to NULL. I'm sure you can see what happens next.
More generally, this code is trying to do several things, and it's full of bugs. You should have tested the different functions separately and worked out those bugs along the way.

A: This here seems wrong:
   char* buffer = (char*)malloc(*argv[1]);

The command line argument is a string, but you want a number. You have to convert the string to a number first.
Another problem: In your loop n is never increased, which is why only the first byte of the buffer is written.

A: Please find the fixed code and the comments inline:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
  // Add the check if *argv[1] does not exist, exit the program
  long mem_sz=strtol(argv[1],NULL,10);//Safer to atoi
  char* buffer = (char*)malloc(mem_sz); // properly allocate memory

  //You missed the == in the NULL check.
  if(buffer==NULL)
   exit(1);

  int n = 0;
  FILE* fp=fopen("file.txt","r"); // Open the file
  if (fp == NULL)//Check fp too
   exit(1);

  do
  {
    buffer[n++]=fscanf(fp,"%c",buffer);
  } // read from file until it gets EOF and n++
  while(buffer[n-1] != EOF);//Check the last read character

  buffer[n]=0;//Put an end of string, so that printf later will work correct

  fclose(fp); // Close the file
  printf("%s\n",buffer); // Print the stored string
  free(buffer); // Return the memory
  return 0;
}


text:
Q: How is scroll height larger than window height? I am trying to make a function stop running before the user scrolls the entire window height, but what I am seeing in the console isn't adding up. Somehow, the scrollHeight (which is the scrollTop value) ends up being more than the window heigh itself. How is this possible?
$(document).ready(function() {

    var windowHeight = $(window).height();

    if( $(window).width() > 720  && $(window).scrollTop() < (windowHeight-400) ) {

                $(window).bind('scroll', function(){

                var scrollHeight = $(window).scrollTop();
                console.log('scroll height', scrollHeight)
                console.log('window height', windowHeight)

                function parallaxScroll(){
                   $('#main').css('top',(500-(scrollHeight*2))+'px');
                };

                    parallaxScroll();
                });
    }
});

A: Looking at the documentation from jQuery, you are getting the height of the viewport, meaning that you are only getting what's in view. You need to set the height to the document height like so:
$(document).ready(function() {

    var windowHeight = $(document).height();

    if( $(window).width() > 720  && $(window).scrollTop() < (windowHeight-400) ) {

                $(window).bind('scroll', function(){

                var scrollHeight = $(window).scrollTop();
                console.log('scroll height', scrollHeight)
                console.log('window height', windowHeight)

                function parallaxScroll(){
                   $('#main').css('top',(500-(scrollHeight*2))+'px');
                };

                    parallaxScroll();
                });
    }
});


text:
Q: Count Number of Times 100 Feature Classes Overlap This must have been asked before, but I can't find the exact answer and my attempts so far have not worked. Most of the overlap questions I see are for calculating the area of overlap for portions of polygons or points in polygons. I want to do something that should be simpler: count overlapping polygons from separate feature classes.
I have 100 separate feature classes, each representing the occurrence of a single species. They all use the same polygon template (based on sub-watershed boundaries), meaning that when more than one species is found in an area the polygon (sub-watershed) for those species' feature classes are perfectly aligned (overlap by 100%, exactly). Note: although not as efficient for disk storage, this is how the data was provided, rather than relating tables of species data.

Example of overlaps: Each color (blue, red dots, orange lines) each represent one species. When they overlap, e.g. red and orange, there is a perfect overlap of polygon boundaries.
What I want to do is count the number of species recorded for any given location, i.e. count the number of times a polygon overlaps and associated this with a specific polygon location. The area of overlap is not relevant in this case, just the count. With a raster, this would be equivalent to setting each layer's cells to have a value of 1, then summing. Is there a simple way to efficiently batch/automate this with 100+ vector features, without converting to raster?
So far I have tried using this count overlaps model.
However, this resulted in an m-aware error, which seems unrelated. I am now running union, which has been progressing for a few hours without completing. Since I may try and run this with 1,000+ feature classes in the future, I was trying to find a more efficient way to complete the analysis. There must be a very simple way to do this, something that I am overlooking.

A: Have you looked at Spatial Join?
http://resources.arcgis.com/en/help/main/10.2/index.html#//00080000000q000000
Make the sub-basins the 'target features', the species polygons the 'join features' and then Spatial Join should generate a field Join_Count that simply gives the number of joins that matched each target feature.
You can join one-to-one and get the Join_Count directly. If you wanted to retain information about which species were matched to which sub-basin, you can do a one-to-many join (you end up with a record for each species) and then calculate the frequency of each sub-basin in the final table.


text:
Q: Why are brackets required for try-catch? In various languages (Java at least, think also C#?) you can do things like
if( condition )
    singleStatement;

while( condition )
    singleStatement;

for( var; condition; increment )
    singleStatement;

So when I have just one statement, I don't need to add a new scope with { }. Why can't I do this with try-catch?
try
    singleStatement;
catch(Exception e)
    singleStatement;

Is there something special about try-catch which requires always having a new scope or something? And if so, couldn't the compiler fix that?

A: IMO, they're included in Java and C# primarily because they already existed in C++. The real question, then, is why is C++ that way. According to The Design and Evolution of C++ (§16.3):

The try keyword is completely redundant and so are the { } brackets except where multiple statements are actually used in a try-block or a handler. For example, it would have been trivial to allow:
int f()
{
    return g() catch(xxii) { // not C++
        error("G() goofed: xxii");
        return 22;
    };
}

However, I found this so difficult to explain that the redundancy was introduced to save support personnel from confused users.

Edit: As to why this would be confusing, I think one has only to look at the incorrect assertions in @Tom Jeffery's answer (and, especially, the number of up-votes it has received) to realize that there would be a problem. To the parser, this is really no different from matching elses with ifs -- lacking braces to force other grouping, all catch clauses would match up with the most recent throw. For those misbegotten languags that include it, finally clauses would do the same. From the viewpoint of the parser, this is hardly enough different from the current situation to notice -- in particular, as the grammars stand now, there's really nothing to group the catch clauses together -- the brackets group the statements controlled by the catch clauses, not the catch clauses themselves.
From the viewpoint of writing a parser, the difference is almost too tiny to notice. If we start with something like this:
simple_statement: /* won't try to cover all of this */
                ;

statement: compound_statement
         | simple_statement
         ;

statements:
          | statements statement
          ;

compound_statement: '{' statements '}'

catch_arg: '(' argument ')'

Then the difference would be between:
try_clause: 'try' statement

and:
try_clause: 'try' compound_statement

Likewise, for catch clauses:
catch_clause: 'catch' catch_arg statement

vs.
catch_clause: 'catch' catch_arg compound_statement

The definition of a complete try/catch block would not need to change at all though. Either way it would be something like:
catch_clauses:
             | catch_clauses catch_clause
             ;

try_block: try_clause catch_clauses [finally_clause]
         ;

[Here I'm using [whatever] to indicate something optional, and I'm leaving out the syntax for a finally_clause since I don't think it has any bearing on the question.]
Even if you don't try to follow all the Yacc-like grammar definition there, the point can be summarized fairly easily: that last statement (starting with try_block) is the one where catch clauses get matched up with try clauses -- and it remains exactly the same whether the braces are required or not.
To reiterate/summarize: the braces group together the statements controlled by the catchs, but do not group the catchs themselves. As such, those braces have absolutely no effect upon deciding which catch goes with which try. For the parser/compiler the task is equally easy (or difficult) either way. Despite this, @Tom's answer (and the number of up-votes it's received) provides ample demonstration of the fact that such a change would almost certainly confuse users.

A: In an answer about why brackets are required for some single-statement constructs but not others, Eric Lippert wrote:

There are a number of places where C# requires a braced block of
  statements rather than allowing a "naked" statement. They are:

*

*the body of a method, constructor, destructor, property accessor, event accessor or indexer accessor.

*the block of a try, catch, finally, checked, unchecked or unsafe region.

*the block of a statement lambda or anonymous method

*the block of an if or loop statement if the block directly contains a local variable declaration. (That is, "while (x != 10) int y = 123;"
  is illegal; you've got to brace the declaration.)

  In each of these cases it would be possible to come up with an
  unambiguous grammar (or heuristics to disambiguate an ambiguous
  grammar) for the feature where a single unbraced statement is legal.
  But what would the point be? In each of those situations you are
  expecting to see multiple statements; single statements are the rare,
  unlikely case. It seems like it is not realy worth it to make the
  grammar unambiguous for these very unlikely cases.

In other words, it was more expensive for the compiler team to implement it than was justified, for the marginal benefit it would provide.

A: I think it's to avoid dangling else style issues.  The following would be ambiguous...
try
    // Do stuff
try
    // Do  more stuff
catch(MyException1 e1)
    // Handle fist exception
catch(MyException2 e2)
    // So which try does this catch belong to?
finally
    // and who does this finally block belong to?

It could mean this:
try {
   try {

   } catch(Exception e1) {

   } catch(Exception e2) {

   }
} finally {

}

Or...
try {
   try {

   } catch(Exception e1) {

   }
} catch(Exception e2) {

} finally {

}

A: I think the main reason is that there is very little you can do in C# that would need a try/catch block that is only one line. (I can't think of any right now of the top of my head).  You may have a valid point in terms of the catch block, e.g a one line statement to log something but in terms of readability it makes more sense (at least to me) to require {}.


text:
Q: How to take a screenshot of a reddit post using playwright? I am trying to use the python PlayWright module to take screenshots of reddit posts and comments.
I've looked at a couple obvious solutions, such as the function that screenshots the whole page, combined with some other image processing module to crop the image to just the post, but that's very out of my wheelhouse, and probably an overcomplicated solution. Ideally, I would be able to use a function where the parameters would be the web page, and element I would like to screenshot. (eg: take_screenshot('header', 'askreddit link') So far im unable to find any magic function like this. Please tell me if I have been unclear in my explanation so I may provide needed information.
I would like something like the following images as the result: https://imgur.com/a/1VqDHTf

Blockquote

A: This should get you started, because you don't really need to do fancy image trickery.
All reddit posts have data-testid=post-container selectors which let you get the top level post. All comments have a .Comment class you can use, so you can enumerate all the comments on any given reddit post and capture them separately if that's what you want.
Some major caveats of this code:

*

*It does not respect comment nesting - I only took a brief glance at Reddit's page source but they don't seem to have easy ways of getting comment chains.

*Reddit could change their selector names/CSS classes any time, and they do have some inconsistencies in how they seem to name things anyway.

*You specify you want to capture AskReddit threads, which can be quite large, so you could easily end up with, say, 1000+ comment screenshots on popular threads, or even 10K+ screenshots if you just let it run with abandon. I set a limit of 10, modify code as needed.

*I wrote this as a demonstration, I have no idea how it will perform on giant posts or such, but hopefully it shows you how to actually pull the information you want. If you need to do more work, you will likely have to inspect Reddit page layouts with your browser's developer tools.
#!/usr/bin/env python3

import asyncio
from playwright.async_api import async_playwright, Browser

MAX_COMMENT_LIMIT = 10

async def capture(browser: Browser,  url: str) -> None:
    page = await browser.new_page()

    await page.goto(url)
    posts = page.locator("data-testid=post-container")

    # reddit loads differently sometimes, so you need to
    # find the first post on the page
    await posts.first.screenshot(path="post.png")

    # this does not respect comment-nesting
    comments = page.locator(".Comment")
    count = await comments.count()
    print(f"Found {count} comments")

    for i in range(count):
        await comments.nth(i).screenshot(path=f"comment-{i}.png")

        if i+1 == MAX_COMMENT_LIMIT:
            print(f"Screened {MAX_COMMENT_LIMIT} images, stopping.")
            break

async def main() -> None:
    reddit_url = "https://www.reddit.com/r/cpp/comments/w9xkmf/c_for_scientific_programming/"
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        await capture(browser, reddit_url)
        await browser.close()

asyncio.run(main())

The thread I picked generated some images like this...
Top-level post text

A comment


text:
Q: xCode - Google Cardboard build failure I can build and run my Cardboard app with Unity 5 and xCode 6 and it works great on my iPhone 5.  However, when I hand the project off to another developer he gets the below error when trying to build.  He's using xCode 7 beta and an iPhone 6.  I assume the issue is because he's using xCode 7 beta.  He's added comments within the below log.
- Completed reload, in  0.055 seconds
Built-in distortion correction disabled. Causes: [Requires OpenGL]

(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebug.gen.cpp Line: 56)

Built-in UI layer disabled. Causes: [Requires OpenGL]

(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebug.gen.cpp Line: 56)

2015-06-12 15:26:59.290 cardboardTest[12562:2094875] Unbalanced calls to begin/end appearance transitions for <UnityLandscapeRightOnlyViewController: 0x16e0a090>.
2015-06-12 15:27:07.805 cardboardTest[12562:2094875] Rotation check?! 3
2015-06-12 15:27:10.807 cardboardTest[12562:2094875] popping automatically
2015-06-12 15:27:10.817 cardboardTest[12562:2094875] rotation station

>>>> The below is logged just before the crash, after the stardust finishes circling, after which Aulani video is supposed to start. <<<

Unloading 3 Unused Serialized files (Serialized files now loaded: 0)
UnloadTime: 10.548125 ms
Built-in distortion correction disabled. Causes: [Requires OpenGL] <<<< OpenGLES.framework is included in the project.

(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebug.gen.cpp Line: 56)

Built-in UI layer disabled. Causes: [Requires OpenGL]

(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebug.gen.cpp Line: 56)

Unloading 25 unused Assets to reduce memory usage. Loaded Objects now: 621. <<<< Closed any application running in the background on my iPhone, just to free up available memory. No difference.
Total: 3.234458 ms (FindLiveObjects: 0.401500 ms CreateObjectMapping: 0.034583 ms MarkObjects: 0.550083 ms  DeleteObjects: 2.247291 ms)

#

#

In Unity I have the Graphics API set to Automatic.

A: The only way I managed to get this to work was to un-tick Automatic graphics API, and to put Metal below OpenGLES2. It seems there's something with the Cardboard SDK that doesn't work with the Metal rendering pipeline.
It's not ideal but it should hopefully get the VR mode working!


text:
Q: How often does a browser poll for mouse location? var mouseTrack = (function() {
        document.onmousemove = handleMouseMove;
        function handleMouseMove(event) {
            var dot, eventDoc, doc, body, pageX, pageY;

            event = event || window.event; // IE-ism

            // If pageX/Y aren't available and clientX/Y are,
            // calculate pageX/Y - logic taken from jQuery.
            // (This is to support old IE)
            if (event.pageX == null && event.clientX != null) {
                eventDoc = (event.target && event.target.ownerDocument) || document;
                doc = eventDoc.documentElement;
                body = eventDoc.body;

                event.pageX = event.clientX +
                  (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
                  (doc && doc.clientLeft || body && body.clientLeft || 0);
                event.pageY = event.clientY +
                  (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
                  (doc && doc.clientTop  || body && body.clientTop  || 0 );
            }

            console.log(event.pageX + ', ' + event.pageY);
            // document.body.innerHTML += '

'
        }
    });
    mouseTrack();

(try this in your browser :) )
If you race the mouse on high sensitivity across the page, you'll only get a coordinate set of like 10-20. If you do it slowly, you'll accumulate hundreds or thousands of points.
How often does a browser (let's say, Chrome) poll for mouse location to fire the mousemove event and even better, where is the source I can look at for this?

A: It is not the browser that is causing this effect. The browser does not poll the mouse position at all, actually.
It is the scripting engines implementation that takes a certain execution time for each command, thus is only able to compare positions every so many microseconds. If a change is detected an event is raised.
It is impossible to name a specific time here in my eyes, since obviously the execution time of single commands depends on the specific hardware and load of the system you test on.


text:
Q: unable to find $wpdb variable with AJAX call I'm creating an application in PHP for Wordpress and at this point, I'm trying to fetch a value from a database through AJAX every 2 seconds, and I've created a new file with the function that should be fired.
<?php
global $wpdb;
function conta(){
    global $wpdb, $table_name;
    $count = $wpdb->get_var("SELECT contatore FROM $table_name WHERE email = '$mail'");
    echo "$count";
}
conta()
?>

An this function is called here with an XMLHttpRequest Object every 2 seconds
    setInterval(function () {
    var url = <?php echo json_encode($con); ?>;
    var valuereq = new XMLHttpRequest();
    valuereq.open("GET", url, true);
    valuereq.send();
    valuereq.status;
    valuereq.onreadystatechange = function () {
        if (valuereq.readyState == 4 && valuereq.status == 200) {
            var return_data = valuereq.responseText;
            document.getElementById("conta").innerHTML = "Executed: " + return_data;
        }
        else document.getElementById("conta").innerHTML = "Error";
    }

}, 2000);

The Http request is executed correctly, but I receive this error:
Fatal error: Uncaught Error: Call to a member function get_var() on null in
C:\xampp\apps\wordpress\htdocs\wp-content\plugins\bittrex-
trader\admin\partials\conta.php:7 Stack trace: #0
C:\xampp\apps\wordpress\htdocs\wp-content\plugins\bittrex-
trader\admin\partials\conta.php(11): conta() #1 {main} thrown in
C:\xampp\apps\wordpress\htdocs\wp-content\plugins\bittrex-
trader\admin\partials\conta.php on line 7

The program is not able to find the global variable $wpdb, even though is declared. This happens only with the AJAX request because if i include directly the file $wpdb is found and working.
Is there a reason?
Thank you in advance.

A: Your $mail variable is not set inside the conta() function, yet you perform a query with it.
Use this to load basic wordpress (only loads wordpress core) so you can use $wpbd:
<?php

    // use this flag to load only wordpress core
    define( 'SHORTINIT', true );
    // find the wp-load.php file and require it
    require( '/path/to/wp-load.php' );

    // now you can use $wpdb

    function conta($wpdb, $table_name, $mail)
    {
       $count = $wpdb->get_var("SELECT `contatore` FROM `".$table_name."` WHERE `email` = '".$mail."'");
       echo "$count";
    }

    // call the function and pass the parameters
    conta($wpdb, $table_name, $mail);

    // close connection
    $wpdb->close();
?>

More on the flag for worpdress core here.


text:
Q: Refreshing only specified div after X seconds? Is there a way how can I refresh only a specified div every X seconds?
Code is here just for nice formatting, I dont think its useful for you guys.

LATEST UPGRADES

"; echo "$nick"; $nick = $nicknames_array[array_rand($nicknames_array)]; echo "

A:      //This Is Main File (index.php or any name)

LATEST UPGRADES

//Make Another Page And Call That Page By AJAX Call With URL mentioned in AJAX Script

//query.php //which will show refeshed data here i'm showing for a random number

                    Hello I Am Your Random Number <?php echo rand();?>


text:
Q: how to group rows in jquery uisng w2grid? I'm trying to achieve this format using w2ui grid. I don't know how to group the cells (rows) or split the cells. I tried to split while rendering but couldn't achieve.

A: In 1.5 records can have a w2ui.colspan property (of type object).
Rowspan is not supported.
I have not seen this feature in action yet, but let me quote mrg2001, who is a Collaborator of the w2ui project on github:

Combining with colspan should allow you to achieve this. Colspan example is
records: [
{ recid: 1, title: "some", w2ui: { colspan: { field: 2 } }
...
]

Source: https://github.com/vitmalina/w2ui/issues/280


text:
Q: Failed to load PDF document (ASP.NET MVC ajax) I need display dynamically pdf. But I get error : Failed to load PDF document.(I use Chrome)
Index.cshtml:

 AJAX: (data='@@Url.Action("GetPDF")')

    <object data='@Url.Action("GetPDF")' type="application/pdf" width="300" height="200"></object>

 PATH: (data="/Pdf/32_1.pdf")

    <object data="/Pdf/32_1.pdf" type="application/pdf" width="300" height="200"></object>

HomeController.cs:
public FileStreamResult GetPDF()
{
    string fileName = "32_1.pdf";
    FileStream fs = new FileStream(@"C:\Documents\MUH0000020\" + fileName, FileMode.Open, FileAccess.Read);
    return File(fs, "application/pdf", fileName);
}

result :

please help.

A: When you use FileStreamResult() or File() to return a file, and you specify a filename, MVC renders a Content-Disposition header that looks like this:
attachment; filename=someFile.pdf
The 'attachment' part is specifically telling the browser not display this document in-browser, but rather to send it as a file. And it appears that Chrome's PDF viewer chokes in that situation, probably by design!
This seems to be a better way to specify filename, when trying to get a PDF to display in-browser, in Chrome:
Response.AddHeader("Content-Disposition", "inline; filename=someFile.pdf");

return new FileStreamResult(stream, "application/pdf");

As a side note, your solution above actually works because you aren't specifying the file name at all, which gets around the header problem! It works, but not because of the StreamReader, which is actually for working with text files. You could have passed in a MemoryStream or FileStream directly and been fine.
More: Content-Disposition:What are the differences between "inline" and "attachment"?

A: I changed my method :
public FileStreamResult GetPDF()
        {
            string fileName = "32_1.pdf";
            StreamReader reader = new StreamReader(@"C:\Documents\MUH0000020\" + fileName);

            return new FileStreamResult(reader.BaseStream, "application/pdf");
        }


text:
Q: font size discrepancy between tumblr and hard coded I have an odd issue... When im comparing two elements on a website I have coded on my server compared to a tumblr site I created on their server, there is a 2px font size discrepancy.
both sites have this code:

Text

I have no font sizes set anywhere but both body css codes are:
body {
    font-family: Arial;
    font-size: 100%;
    color: #000;
    background: #FFF;
    width: 4100px;
    padding: 0;
    margin: 0;
}

and both h1 codes are:
h1 {
    font-size: 100%;
    font-weight: normal;
    margin: 0.67em 0 0.67em 0;
}

for whatever reason, the tumblr site has a 2px font size difference (smaller). is there any known reason why?
EDIT
I've added a base font size of 16px to both html attributes, however there still seems to be about a 2px difference. Some links to the sources:
Server:
http://goo.gl/PfyQ6r
Tumblr:
http://goo.gl/5gDfp4

A: Tumblr's global.css file as AR7 noted is set to 14px, the default html font size in most browsers is 16px but is also user definable.
html, body {
    font-family: "Helvetica Neue","HelveticaNeue",Helvetica,Arial,sans-serif;
    font-weight: 400;
    line-height: 1.4;
    font-size: 14px;
    font-style: normal;
    color: #444;
}

Your question code example sets the body font-size as inherited from its parent (html) at 100%. If you did not specify the html font-size it would inherit the browser's defined default font-size to 100%.

A: Font size by default is 16px I believe and is usually defined in the body.
Popular frameworks like bootstrap have the font size set as 14px in the body.
That's probably why there's a difference because the default font size is what is used when you specify 100%. Tumblr's own css files, which are completely unrelated to yours, specify it as 14px by default.


text:
Q: mvc partial view onsubmit form send data from parent view I am developing MVC 5 App. I have a Parent View that call a Partial View, where user can Load a Image.
On Submit a call a .Ajax defined in Parent view that call Method/Controller.
What I need is to send to the controller data I have in Parent View. Is that Posible?
Here is my code.
Parent View

Partial View

.Ajax Method

          $('#formPhoto').submit(function (event) {
                event.preventDefault();
                if ($(this).valid()) {
                    var id="aaa";
                    var formdata = new FormData($(this).get(0));
                    $.ajax({
                        url: this.action,
                        type: this.method,
                        data:formdata,
                        processData: false,
                        contentType: false,
                        beforeSend: function () {
                            return true;
                        },
                        success: function (result) {
                            successPhoto();
                        },
                        complete: function () {
                            // alert(3);
                            // And so on.
                        }
                    });
                }
                return false;
            });

I need to send var aa='aaa' in data:

A: Yes it's possible. So basically I can suggest for you two ways to do what you need:
1st: You could consider putting the form element in the ParentView and change your code a little bit...
2nd: You could recover the data from the parent view and serialize it together to send to your action.
So, from the second option it would be something like:
var parentInformation = 'aaa';
var formdata = new FormData($(this).get(0));
formdata.ExpectedParentOnPropertySide = parentInformation;

Please, I hope this solve your problem


text:
Q: storing and retrieving images in dictionary - python Can anyone tell me how to store images in python dictionary (dict), and how to retrieve images from the dictionary based on the key value ?

A: Personally, if I had to go down that road, I would load the image into a variable and then add it to dictionary as a value {key:value} as you would with any other variable. If you are using Pygame you don't need to load it as a file and can already load the image using pygame.image.load(file) .
Just a note : Loading image files, especially JPEGs in binary as suggested is tricky. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it'll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.
As with images in dictionaries, you could even nest a list of images in the dictionary (along with a key), Having a list is one way to easily animate by looping the list within each key. {'key1' : ['value1', 'value2','value2']}
Remember however that once you pack a variable inside a dictionary, the value of the variable would not change and remain constant inside the dictionary, unless you specifically update the dictionary. Just updating the value outside of the dictionary, would not affect it's original value that it was given when it was placed inside the dictionary.
Example: (using pygame, load images into a list, and nest it into a dictionary for recall)
def load_image(file):
    """loads and prepares image from data directory"""
    file = os.path.join(main_dir, 'data', file)
    try:
        surface = pygame.image.load(file)
    except pygame.error:
        raise SystemExit('Could not load image "%s" %s'%(file, pygame.get_error()))
    return surface.convert()

def load_images(*files):
    """ function to load a list of images through an *arg and return a list
    of images"""
    images = []
    for file in files:
        images.append(load_image(file))
    return images

bomb_images = load_images('bomb.gif', 'bomb2.gif','bomb3.gif')
explosion_images = load_images('ex1.gif', 'ex2.gif', 'ex3.gif')
# now all the images are inside a list and you can pack them in a dictionary

image_dict = {'bomb' : bomb_images, 'explode' :explosion_images}
# to call the image would be the same as you call any value from the dict
bombs = image_dict['bomb']

image_ready_for_blit = bombs[0]
# changing the slice position allows animation loops [0]

A: It is better to store images in files and then reference them with a filename:
pictures = {'mary': '001.jpg', 'bob', '002.jpg'}
filename = pictures['mary']
with open(filename. 'rb') as f:
    image = f.read()

That said, if you want to store images directly in a dictionary, just add them:
pictures = {}

with open('001.jpg', 'rb') as f:
     image = f.read()
pictures['mary'] = image

Images aren't special, they are just data.


text:
Q: How to have options on a dropdown menu sorted aplpabetically I have a dropdown menu that displays information in the order it was entered into the array however I would like it sorted alphabetically so that in the case that someone should search all objects in the array that start with the same letters will be grouped near each other there by giving the user an easier time finding the one that they are looking for with out having to look through the entire list. This is my code
import axios from 'axios';
import CallForm from './CallForm';
import { produce } from 'immer';

export default class EditPage extends React.Component {

    state = {
        call: {
            name: '',
            address: '',
            zip: '',
            neighborhood: '',
            landlord: '',
            appliance: '',
            brand: '',
            applianceLocation: '',
            type: '',
            workPreformed: '',
            additionalWorkAndNotes: '',
            calls: '',
            reasonForReturn: '',
            ammout: '',
            methodOfPayment: '',
            date: ''
        },
        calls: []
    }

    componentDidMount = () => {
        if (this.props.match.params.callId) {
            axios.get(`/api/calls/getbyid/${this.props.match.params.callId}`)
                .then(({ data }) => {
                    this.setState({ call: data });
                });
        } else {
            axios.get('/api/calls/get').then(({ data }) => {
                this.setState({ calls: data });
            });
        }
    }

    onInputChange = e => {
        const nextState = produce(this.state, draft => {
            draft.call[e.target.name] = e.target.value;
        });
        this.setState(nextState);
    }

    onSubmit = () => {
        axios.post('/api/calls/update', this.state.call).then(() => {
            this.props.history.push('/');
        });
    }

    onSelectChange = e => {
        const id = e.target.value;
        axios.get(`/api/calls/getbyid/${id}`)
            .then(({ data }) => {
                this.setState({ call: data });
            });
    }

    render() {
        const  { name, address, zip, neighborhood, landlord, appliance, brand, applianceLocation, type, workPreformed, additionalWorkAndNotes, calls, reasonForReturn, ammout, methodOfPayment, date } = this.state.call;
        let content;
        if (name) {
            content = <CallForm
                name={name}
                address={address}
                zip={zip}
                neighborhood={neighborhood}
                landlord={landlord}
                appliance={appliance}
                brand={brand}
                applianceLocation={applianceLocation}
                type={type}
                workPreformed={workPreformed}
                additionalWorkAndNotes={additionalWorkAndNotes}
                calls={calls}
                reasonForReturn={reasonForReturn}
                ammout={ammout}
                methodOfPayment={methodOfPayment}
                date={date}

                onInputChange={this.onInputChange}
                onSubmit={this.onSubmit}
            />
        }
        else {
            content = (

Start typing to search by Name

                        <select className="form-control" onChange={this.onSelectChange}>

                            <option value="0" ><input type="text" />-- Search By Name--</option>

                            {this.state.calls.map(p => <option key={p.id}
                                value={p.id}>{p.name + ' ' + p.appliance}</option>)}
                        </select>

Start typing to search by Address

                            <select className="form-control" onChange={this.onSelectChange}>
                                <  option value="0" ><input type="text"/>-- Search By Address--</option>

                                {this.state.calls.map(p => <option key={p.id}
                                    value={p.id}>{p.address + ' ' + p.name}</option>)}
                            </select>

)

)

        }
        return (

Edit call

               {content}

        )
    }
}

A: You can achieve that with this:
{
  this.state.calls
    .sort((a, b) => (a.name > b.name ? 1 : -1))
    .map((p) => (
      <option key={p.id} value={p.id}>
        {p.name + ' ' + p.appliance}
      </option>
    ));
}


text:
Q: Tramsformar divs com tamanhos e posiçoes fixos em conteudo responsiva Amigos, estou no meio de um trabalho de viés acadêmico, e tenho como missão transformar esse mapa em conteúdo virtual e responsivo.

Para isso já tenho uma estrutura de divs gerada pelo próprio Photoshop. A minha duvida é como transformar isso em conteúdo responsivo? Desde já agradeço a compreensão.

    <link rel="stylesheet" href="css/materialize.min.css">


text: Q: How to make SearchKit trigger API call I have a client requirement wherein a Remove Button has to be implemented. The Ideal way would be to pick up the ID of the Item to be removed and pass the data to the backend for updating, but how do i trigger searchkit to fetch the api and populate data according to the remove status? I am using the SearchKit library along with React and I just can't find a way around it.


text:
Q: Using Javascript is it possible to hook a custom function to the browser back button while preventing the default event? Using Javascript is it possible to hook a custom function to the browser back button while preventing the default event?
So simply put, the user clicks the browser back button,  and instead of being taken back to the previous page on my site, my function fires. My aim is not to to prevent the user leaving my site.
Something like the below pseudo code:
window.backbutton.click(function(e){ preventDefault(e); myFunc(); })

FYI What I actually have is an internal back/forward system controlled by buttons within the view and I'd like to trigger my buttons when user clicks browser back.

A: You should look into Browser History https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history . It is a new standard for emulating pages (back and forward) on a single-page site.

A:
you can do this
$(window).bind("beforeunload", function() {
    return "Are you Sure you want to do this even though there are internal navigation buttons? if you do whatever you have done so far

will be gone unless it has been completed and/or submitted "; //
  Return whatever message you want
      });
Edit: this method displays a confirmation with the message and
  automatically places buttons in the confirmation window
the author also clearly stated he does not want to prevent users from
  leaving his site
see js fiddle  http://jsfiddle.net/JW9fX/
Aaron - "updated question, I do not want to prevent them leaving my
  site –  Aaron 27 mins ago"
Edit: there is no definitive way to display a message only on the back
  button in my knowledge i have also looked and have seen the only
  methods that pick up on the back button  are
  $(window).bind("beforeunload",function(){return;}) and
  $(window).onbeforeunload = function(){return;} and they both pick up
  on when the page is refreshed or any other navigation away from the
  current page. This is currently the best answer that can be provided
  in the year 2014

Edit:
above is for all unload events
http://jsfiddle.net/Lhw2x/85/
been messing with that through all its lower objects it cant be done through javascript till someone decides to make all major browsers use a specific name for each unload event instead of it just being an unload event
so the answer is no you cannot hook a custom function to the browser back button while preventing the default event using javascript


text:
Q: Graph:: Deletion Contraction Complexity? I am applying the classic deletion contraction algorithm to a Graph G of "n" vertices and "m" edges.
Z(G) = Z(G-e) + Z(G/e)
In Wikipedia,
http://en.wikipedia.org/wiki/Chromatic_polynomial#Deletion.E2.80.93contraction
They say that complexity is: O(1.6180^(n+m)).
Mi main question is why they included the number of vertices in the complexity ?? when is clear that the recursion only depends on the number of edges.
The closest reference to deletion-contraction is fibonacci sequence, which its computing complexity is demonstrated in Herbert S. Wilf's Algorithms and Complexity book
http://www.math.upenn.edu/~wilf/AlgComp3.html
pages 18-19.
All help is welcome.

A: Look at page 46 of the pdf version. Deletion and contraction each reduce the number of edges by 1, so a recurrence in edges only shows that Z(G) is O(2m), which is worse than O(Fib(n + m)) for all but the sparsest graphs. The improvement in considering vertices as well as edges is that, when a self-loop is formed, we know immediately that the chromatic polynomial is zero.


text:
Q: How to reduce called paramets in methods? I have a class and in that class I have a method that calls multiple methods in it.
But the problem I am facing now is that when the method with the multiple methods in it duplicate parameter has.
And so when I am calling the method with the multiple methods in it, it returns a empty list:[].
So this is the method with the multiple methods in it:
 def show_extracted_data_from_file(self,  file_name):
        self.extractingText.extract_text_from_image(file_name)
        total_fruit = self.filter_verdi_total_number_fruit()
        fruit_name = self.filter_verdi_fruit_name()
        fruit_total_cost = self.filter_verdi_total_fruit_cost(file_name)

        return "\n".join("{} \t {} \t {}".format(a, b, c) for a, b, c in zip(total_fruit, fruit_name, fruit_total_cost))

and this is the method: filter_verdi_total_fruit_cost:
   def filter_verdi_total_fruit_cost(self, file_name):
        locale.setlocale(locale.LC_ALL, locale='Dutch')
        self.extractingText.extract_text_from_image(file_name)
        return [
            locale.atof(items[-1]) for items in (
                token.split() for token in file_name.split('\n')
            ) if len(items) > 2 and items[1] in self.extractingText.list_fruit
        ]

this method returns the following data:
[123.2, 2772.0, 46.2, 577.5, 69.3, 3488.16, 137.5, 500.0, 1000.0, 2000.0, 1000.0, 381.25]

You see that I am calling two times file_name.
and so when I calling the method show_extracted_data_from_file in the views.py:
if uploadfile.image.path.endswith('.pdf'):
                    content = filter_text.show_extracted_data_from_file(uploadfile.image.path)
                    print(content)

it produces a empty list: []
Question: how can I reduce the parameter file_name so that it will return the correct results?
this are my two other methods that I am calling in the combined method:
  def filter_verdi_total_number_fruit(self):
        regex = r"(\d*(?:\.\d+)*)\s*\W+(?:" + '|'.join(re.escape(word)
                                                       for word in self.extractingText.list_fruit) + ')'
        return re.findall(regex, self.extractingText.text_factuur_verdi[0])

    def filter_verdi_fruit_name(self):
        regex = r"(?:\d*(?:\.\d+)*)\s*\W+(" + '|'.join(re.escape(word)
                                                       for word in self.extractingText.list_fruit) + ')'
        return re.findall(regex, self.extractingText.text_factuur_verdi[0])

So this is the other class:
class ExtractingTextFromFile:

    def extract_text_from_image(self, filename):

        self.text_factuur_verdi = []
        pdf_file = wi(filename=filename, resolution=300)
        all_images = pdf_file.convert('jpeg')

        for image in all_images.sequence:
            image = wi(image=image)
            image = image.make_blob('jpeg')
            image = Image.open(io.BytesIO(image))

            text = pytesseract.image_to_string(image, lang='eng')
            self.text_factuur_verdi.append(text)

        return self.text_factuur_verdi

    def __init__(self):
        # class variables:

        self.tex_factuur_verdi = []
        self.list_fruit = ['Appels', 'Ananas', 'Peen Waspeen',
                           'Tomaten Cherry', 'Sinaasappels',
                           'Watermeloenen', 'Rettich', 'Peren', 'Peen',
                           'Mandarijnen', 'Meloenen', 'Grapefruit', 'Rettich']

A: @AndrewRyan has the right idea.
I presume calling  extract_text_from_image just adds the attribute list_fruit
Two routes you can go, from what you are commenting you'll probably just go with #1.. but I gave #2 as another option in case you'd ever want to call filter_verdi_total_fruit_cost by itself.
Path 1, Just remove it.

Note: filter_verdi_total_fruit_cost is only called from show_extracted_data_from_file.

def show_extracted_data_from_file(self,  file_name):

    # extract text
    #  Note: stores data in `self.extractingText.list_fruit`
    self.extractingText.extract_text_from_image(file_name)

    total_fruit = self.filter_verdi_total_number_fruit()
    fruit_name = self.filter_verdi_fruit_name()
    fruit_total_cost = self.filter_verdi_total_fruit_cost()

    return "\n".join("{} \t {} \t {}".format(a, b, c) for a, b, c in zip(total_fruit, fruit_name, fruit_total_cost))

def filter_verdi_total_fruit_cost(self):
    # Note: `self.extractingText.list_fruit` should be already defined

    locale.setlocale(locale.LC_ALL, locale='Dutch')
    return [
        locale.atof(items[-1]) for items in (
            token.split() for token in file_name.split('\n')
        ) if len(items) > 2 and items[1] in self.extractingText.list_fruit
    ]

Path 2, Check if it's already extracted- if not, extract; if so, continue

Note: if you wanted to just call filter_verdi_total_fruit_cost

def show_extracted_data_from_file(self,  file_name):

    # extract text
    #  Note: stores data in `self.extractingText.list_fruit`
    self.extractingText.extract_text_from_image(file_name)

    total_fruit = self.filter_verdi_total_number_fruit()
    fruit_name = self.filter_verdi_fruit_name()
    fruit_total_cost = self.filter_verdi_total_fruit_cost(file_name)

    return "\n".join("{} \t {} \t {}".format(a, b, c) for a, b, c in zip(total_fruit, fruit_name, fruit_total_cost))

def filter_verdi_total_fruit_cost(self, file_name):
    locale.setlocale(locale.LC_ALL, locale='Dutch')

    if not hasattr(self, 'list_fruit'):
        # file hasn't been extracted yet.. extract it
        #  Note: stores data in `self.extractingText.list_fruit`
        self.extractingText.extract_text_from_image(file_name)

    return [
        locale.atof(items[-1]) for items in (
            token.split() for token in file_name.split('\n')
        ) if len(items) > 2 and items[1] in self.extractingText.list_fruit
    ]


text:
Q: add an XPath statement to a FLOWR to select "id" nodes from Twitter database Looking at the "id" field for a twitter database:
thufir@dur:~/flwor$
thufir@dur:~/flwor$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
>
> open twitter
Database 'twitter' was opened in 218.67 ms.
>
> xquery //id
<id type="number">1224165280068382720</id>
<id type="number">60919433</id>
<id type="number">1224160851797643264</id>
<id type="number">60919433</id>
..
<id type="number">14248074</id>
Query executed in 268.13 ms.
>

how would I get the same result from a FLWOR statement?
thufir@dur:~/flwor$
thufir@dur:~/flwor$ cat id.xq

for $tweets in db:open("twitter")
let $tweet := $tweets
return <results>{$tweet}</results>

thufir@dur:~/flwor$

which wraps everything in <result> tags, but still gives every node.  How is just the "id" node selected?  Trying variations on:
  let $tweet := $tweets/id

without positive results.  Perhaps because there's JSON in the mix?

A: snowflake id's:
thufir@dur:~/flwor/twitter$
thufir@dur:~/flwor/twitter$ basex tweetID.xq
<tweet>
  <id__str>1224165280068382720</id__str>
</tweet>
<tweet>
  <id__str>1224160851797643264</id__str>
</tweet>
<tweet>
  <id__str>1224134565280862208</id__str>
</tweet>
<tweet>
  <id__str>1224133755562086406</id__str>
</tweet>
<tweet>
  <id__str>1224117426364846081</id__str>
</tweet>
<tweet>
  <id__str>1224113562777419777</id__str>
</tweet>
<tweet>
  <id__str>1224083010015956992</id__str>
</tweet>
<tweet>
  <id__str>1224080221663645697</id__str>
</tweet>
<tweet>
  <id__str>1224042214541496320</id__str>
</tweet>
<tweet>
  <id__str>1224041056024645632</id__str>
</tweet>
<tweet>
  <id__str>1224036122344534017</id__str>
</tweet>
<tweet>
  <id__str>1224017759132143616</id__str>
</tweet>
<tweet>
  <id__str>1224016596634603520</id__str>
</tweet>
<tweet>
  <id__str>1224001430417297410</id__str>
</tweet>
<tweet>
  <id__str>1223987662094249991</id__str>
</tweet>
<tweet>
  <id__str>1224165280068382720</id__str>
</tweet>
<tweet>
  <id__str>1224160851797643264</id__str>
</tweet>
<tweet>
  <id__str>1224134565280862208</id__str>
</tweet>
<tweet>
  <id__str>1224133755562086406</id__str>
</tweet>
<tweet>
  <id__str>1224117426364846081</id__str>
</tweet>
<tweet>
  <id__str>1224113562777419777</id__str>
</tweet>
<tweet>
  <id__str>1224083010015956992</id__str>
</tweet>
<tweet>
  <id__str>1224080221663645697</id__str>
</tweet>
<tweet>
  <id__str>1224042214541496320</id__str>
</tweet>
<tweet>
  <id__str>1224041056024645632</id__str>
</tweet>
<tweet>
  <id__str>1224036122344534017</id__str>
</tweet>
<tweet>
  <id__str>1224017759132143616</id__str>
</tweet>
<tweet>
  <id__str>1224016596634603520</id__str>
</tweet>
<tweet>
  <id__str>1224001430417297410</id__str>
</tweet>
<tweet>
  <id__str>1223987662094249991</id__str>
</tweet>
<tweet>
  <id__str>1224165280068382720</id__str>
</tweet>
<tweet>
  <id__str>1224160851797643264</id__str>
</tweet>
<tweet>
  <id__str>1224134565280862208</id__str>
</tweet>
<tweet>
  <id__str>1224133755562086406</id__str>
</tweet>
<tweet>
  <id__str>1224117426364846081</id__str>
</tweet>
<tweet>
  <id__str>1224113562777419777</id__str>
</tweet>
<tweet>
  <id__str>1224083010015956992</id__str>
</tweet>
<tweet>
  <id__str>1224080221663645697</id__str>
</tweet>
<tweet>
  <id__str>1224042214541496320</id__str>
</tweet>
<tweet>
  <id__str>1224041056024645632</id__str>
</tweet>
<tweet>
  <id__str>1224036122344534017</id__str>
</tweet>
<tweet>
  <id__str>1224017759132143616</id__str>
</tweet>
<tweet>
  <id__str>1224016596634603520</id__str>
</tweet>
<tweet>
  <id__str>1224001430417297410</id__str>
</tweet>
<tweet>
  <id__str>1223987662094249991</id__str>
</tweet>
<tweet>
  <id__str>1224165280068382720</id__str>
</tweet>
<tweet>
  <id__str>1224160851797643264</id__str>
</tweet>
<tweet>
  <id__str>1224134565280862208</id__str>
</tweet>
<tweet>
  <id__str>1224133755562086406</id__str>
</tweet>
<tweet>
  <id__str>1224117426364846081</id__str>
</tweet>
<tweet>
  <id__str>1224113562777419777</id__str>
</tweet>
<tweet>
  <id__str>1224083010015956992</id__str>
</tweet>
<tweet>
  <id__str>1224080221663645697</id__str>
</tweet>
<tweet>
  <id__str>1224042214541496320</id__str>
</tweet>
<tweet>
  <id__str>1224041056024645632</id__str>
</tweet>
<tweet>
  <id__str>1224036122344534017</id__str>
</tweet>
<tweet>
  <id__str>1224017759132143616</id__str>
</tweet>
<tweet>
  <id__str>1224016596634603520</id__str>
</tweet>
<tweet>
  <id__str>1224001430417297410</id__str>
</tweet>
<tweet>
  <id__str>1223987662094249991</id__str>
</tweet>
<tweet>
  <id__str>1224165280068382720</id__str>
</tweet>
<tweet>
  <id__str>1224160851797643264</id__str>
</tweet>
<tweet>
  <id__str>1224134565280862208</id__str>
</tweet>
<tweet>
  <id__str>1224133755562086406</id__str>
</tweet>
<tweet>
  <id__str>1224117426364846081</id__str>
</tweet>
<tweet>
  <id__str>1224113562777419777</id__str>
</tweet>
<tweet>
  <id__str>1224083010015956992</id__str>
</tweet>
<tweet>
  <id__str>1224080221663645697</id__str>
</tweet>
<tweet>
  <id__str>1224042214541496320</id__str>
</tweet>
<tweet>
  <id__str>1224041056024645632</id__str>
</tweet>
<tweet>
  <id__str>1224036122344534017</id__str>
</tweet>
<tweet>
  <id__str>1224017759132143616</id__str>
</tweet>
<tweet>
  <id__str>1224016596634603520</id__str>
</tweet>
<tweet>
  <id__str>1224001430417297410</id__str>
</tweet>
<tweet>
  <id__str>1223987662094249991</id__str>
</tweet>thufir@dur:~/flwor/twitter$
thufir@dur:~/flwor/twitter$
thufir@dur:~/flwor/twitter$ cat tweetID.xq
for $tweets  in db:open("twitter")
return <tweet>{$tweets/json/id__str}</tweet>
thufir@dur:~/flwor/twitter$
thufir@dur:~/flwor/twitter$

The FLWOR:
for $tweets  in db:open("twitter")
return <tweet>{$tweets/json/id__str}</tweet>


text:
Q: java.io.IOException: Wrong index checksum, store was not closed properly and could be corrupted I encountered the exception after restarting Jetty, which contains producer-consumer implementation via MapDB's Queue. I haven't call "DBMaker.transactionDisable()", but why did I still get the above exceptions?
Before I restarted Jetty, I found the consumer seems blocked. By jstack command, I got lots of following logs:

"qtp1730704097-270" #270 prio=5 os_prio=0 tid=0x00007f7b60006800
  nid=0xb44f waiting on condition [0x00007f7986ae9000]
  java.lang.Thread.State: TIMED_WAITING (parking)   at
  sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000054047c420> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at
  java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at
  java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
    at
  org.eclipse.jetty.util.BlockingArrayQueue.poll(BlockingArrayQueue.java:342)
    at
  org.eclipse.jetty.util.thread.QueuedThreadPool.idleJobPoll(QueuedThreadPool.java:526)
    at
  org.eclipse.jetty.util.thread.QueuedThreadPool.access$600(QueuedThreadPool.java:44)
    at
  org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
    at java.lang.Thread.run(Thread.java:745)
Locked ownable synchronizers:
    - None

Here are some code fragment:
// Consumer code:

public void run() {
    try {
        while (!stopped) {
            if (System.currentTimeMillis() - lastCheckTime > 60000) {
                localDb.commit();
                localDb.compact();
                lastCheckTime = System.currentTimeMillis();
            }
            ...
            for (...) {
                queue.poll();
            }
            ...
            localDb.commit();
        }
        localDb.commit();
        localDb.compact();
    } catch (InterruptedException ie) {
        LOG.error("", ie);
    }
}

// Others code:

...
DB localDb = DBMaker.newFileDB(new File(path)).closeOnJvmShutdown().make();
localDb.catPut(QUEUE_NAME + ".useLocks", false);
queue = localDb.getQueue(QUEUE_NAME);
...

public void interrupt() {
    stopped = true;
    localDb.close();
}

java -version: java version "1.8.0_11"
Thanks!


text:
Q: Run application in background Cordova I'm developing a Cordova application that sends data (registration and image) for external server, it is already working but would like to make it if the user has no internet at registration, the application is running in background waiting for internet connection to send data, how to do this?

A: Use this plugin
   cordova plugin add cordova-plugin-network-information

and cal your code in this callback function
document.addEventListener("online", onOnline, false);

function onOnline() {
// Handle the online event
 }

It will automatically run your code when internet will available
other way is to implement background service but this is simple and nice way
https://github.com/apache/cordova-plugin-network-information


text:
Q: How to calculate the probability of a data point belonging to a multivariate normal distribution? Okay, so I have a $n$-dimensional normal distribution with the means and co-variance matrix defined (for now we can assume that these are the true distribution parameters, not estimates). For a given data point I want to calculate the probability that this point belongs to this distribution.
I believe I would be interested in the probability of generating a point "at least as unlikely" as the given data point. In a $1D$ normal distribution case this would be the area under the "two tails" of the PDF. E.g. $1-(CDF(x)-CDF(\mu-x))$. Now I want to calculate this probability for a general $n$-dimensional normal distribution. I believe maybe this should be $1$ - "volume inside the hyper-sphere in Mahalanobis distance space defined by the radius given by the Mahalanobis distance of the data point from the mean".
Question 1: Is this interpretation correct?
Question 2: How do I calculate this?
Question 3: Does the analysis change if the mean and covariance matrix are only estimates of the true parameters?
Question 4: Is there an easy way to do this is python?
My best attempt at solving this question myself (but my statistics knowledge isn't very good, so I am asking for correctness confirmation, it is very important I get this correct)
According to wikipedia:
$$(x-\mu)^T\Sigma^{-1}(x-\mu) \le \chi_k^2(p)$$
So I can first calculate the Mahalanobis distance as above (MD), and then maybe I just have to calculate the CDF of the chi-squared distribution at MD, and take $1$ minus this.
I have no idea if this is correct, but currently my best guess.
Thanks in advance.

A: Yeah, that sounds right. If you have parameters $\mu$ and $\Sigma$ and data point $x$, then the set of all data points that are less likely than $x$ are the ones that have less density, or in other words higher Mahalanobis distance:
\begin{align*}
(2\pi)^{-k/2}|\Sigma|^{-1/2}e^{\left[-\frac{1}{2}(y-\mu)^T\Sigma^{-1}(y-\mu) \right]} &\le (2\pi)^{-k/2}|\Sigma|^{-1/2}e^{\left[-\frac{1}{2}(x-\mu)^T\Sigma^{-1}(x-\mu) \right]} \iff\\
e^{\left[-\frac{1}{2}(y-\mu)^T\Sigma^{-1}(y-\mu) \right]} &\le e^{\left[-\frac{1}{2}(x-\mu)^T\Sigma^{-1}(x-\mu) \right]} \iff \\
(y-\mu)^T\Sigma^{-1}(y-\mu) &\ge (x-\mu)^T\Sigma^{-1}(x-\mu).
\end{align*}
So you want the probability of some unseen $Y$ being "better" than your observed $x$, which is the same as $Q = (Y-\mu)^T\Sigma^{-1}(Y-\mu)$ being bigger than $(x-\mu)^T\Sigma^{-1}(x-\mu)$. And you are correct in pointing out that $Q \sim \chi^2(k)$. So
$$
\mathbb{P}\left[(y-\mu)^T\Sigma^{-1}(y-\mu) \ge (x-\mu)^T\Sigma^{-1}(x-\mu)\right] = 1- \mathbb{P}\left[Q \le (x-\mu)^T\Sigma^{-1}(x-\mu)\right].
$$
In python you can calculate that wth something like this:
from scipy import stats
import numpy as np
x = np.array([1,1,1])
mu = np.array([0,0,0])
sigma = np.array([[1,0,0],[0,1,0],[0,0,1]])
m_dist_x = np.dot((x-mu).transpose(),np.linalg.inv(sigma))
m_dist_x = np.dot(m_dist_x, (x-mu))
1-stats.chi2.cdf(m_dist_x, 3)


text:
Q: MySQL Server Has Gone Away (MariaDB - MEMORY Engine) I have an OpenCart website with a bunch of plugins with encrypted files. As I added more and more products (150k currently) it became slower & slower. Since I cannot change the queries (files are encrypted) I had to change some of my tables' storage engine to MEMORY. My query times went from 50 seconds to 2 seconds.
But there is a new problem. If I try to open 4 or 5 pages at the same time DB server crashes. This is a managed VPS so I don't have access to everything. Hosting's support isn't helping at all and telling me not to use MEMORY as it is uncompatible!
I have the exact same setup on my localhost (only difference is that webhost is MariaDB but I use MySQL on my localhost) and I cannot reproduce the error on it how hard I try.
Here is the error log from within OpenCart:
2018-04-26 22:32:42 - PHP Warning:  mysqli::query(): MySQL server has gone away in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  mysqli::query(): Error reading result set's header in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  Error while sending QUERY packet. PID=26733 in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  mysqli::query(): (00000/0):  in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  mysqli::query(): MySQL server has gone away in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  mysqli::query(): Error reading result set's header in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  mysqli::query(): MySQL server has gone away in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  mysqli::query(): Error reading result set's header in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Notice:  Trying to get property of non-object in /home/grdrop/public_html/catalog/model/extension/module/yumenu.php on line 163
2018-04-26 22:32:42 - PHP Warning:  Error while sending QUERY packet. PID=26732 in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  Error while sending QUERY packet. PID=26718 in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  Error while sending QUERY packet. PID=26722 in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  Error while sending QUERY packet. PID=26730 in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  Error while sending QUERY packet. PID=26725 in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:42 - PHP Warning:  Error while sending QUERY packet. PID=26726 in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:43 - PHP Warning:  Error while sending QUERY packet. PID=26734 in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:43 - PHP Warning:  Error while sending QUERY packet. PID=26724 in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:43 - PHP Warning:  Error while sending QUERY packet. PID=26727 in /home/grdrop/public_html/system/library/db/mysqli.php on line 18
2018-04-26 22:32:44 - PHP Warning:  mysqli::__construct(): (HY000/2002): Connection refused in /home/grdrop/public_html/system/library/db/mysqli.php on line 7
2018-04-26 22:32:44 - PHP Warning:  DB\MySQLi::__construct(): Couldn't fetch mysqli in /home/grdrop/public_html/system/library/db/mysqli.php on line 10
2018-04-26 22:32:44 - PHP Warning:  DB\MySQLi::__construct(): Couldn't fetch mysqli in /home/grdrop/public_html/system/library/db/mysqli.php on line 10
2018-04-26 22:32:44 - PHP Warning:  mysqli::__construct(): (HY000/2002): Connection refused in /home/grdrop/public_html/system/library/db/mysqli.php on line 7
2018-04-26 22:32:44 - PHP Warning:  DB\MySQLi::__construct(): Couldn't fetch mysqli in /home/grdrop/public_html/system/library/db/mysqli.php on line 10
2018-04-26 22:32:44 - PHP Warning:  DB\MySQLi::__construct(): Couldn't fetch mysqli in /home/grdrop/public_html/system/library/db/mysqli.php on line 10
2018-04-26 22:32:45 - PHP Warning:  mysqli::__construct(): (HY000/2002): Connection refused in /home/grdrop/public_html/system/library/db/mysqli.php on line 7
2018-04-26 22:32:45 - PHP Warning:  DB\MySQLi::__construct(): Couldn't fetch mysqli in /home/grdrop/public_html/system/library/db/mysqli.php on line 10
2018-04-26 22:32:45 - PHP Warning:  DB\MySQLi::__construct(): Couldn't fetch mysqli in /home/grdrop/public_html/system/library/db/mysqli.php on line 10
2018-04-26 22:32:45 - PHP Warning:  mysqli::__construct(): (HY000/2002): Connection refused in /home/grdrop/public_html/system/library/db/mysqli.php on line 7
2018-04-26 22:32:45 - PHP Warning:  DB\MySQLi::__construct(): Couldn't fetch mysqli in /home/grdrop/public_html/system/library/db/mysqli.php on line 10
2018-04-26 22:32:45 - PHP Warning:  DB\MySQLi::__construct(): Couldn't fetch mysqli in /home/grdrop/public_html/system/library/db/mysqli.php on line 10
2018-04-26 22:32:45 - PHP Warning:  mysqli::__construct(): (HY000/2002): Connection refused in /home/grdrop/public_html/system/library/db/mysqli.php on line 7

I don't know much about DBs & I am completely lost here. If this is memory related issue isn't there a variable or setting that I can change so that DB waits until the first queries to finish & continue when there is enough RAM ?


text:
Q: Exporting timestamps from Data Extensions When I export my data from my Data Extensions the Date/Time fields print in the following format 11/16/2010 12:00:00 AM, how can I export them in this format YYYY-MM-DD HH:MM:ss?
(This is how they were originally inserted into the data extension)

A: I was able to achieve this by creating a new Data Extension that copies the fields from the source Data Extension. The fields which need to be in a certain date format I had used the Text field type instead of Date and casted it using SQL.

A: Write a query activity to move the data from your Data Extension to another DE. In your query, use Date format conversion functions to get the date into desired format. In your target DE, get this value in text format

A: When you view the data in the data extension, does it show as : 11/16/2010 12:00:00 AM or YYYY-MM-DD HH:MM:ss ?
Perhaps check the Date Format of your Business unit and try changing that and seeing if it changes the export format.


text:
Q: Async call (fire and forgot call) in try and finally block in Python I have a try and finally block like below:
def get_data():
    try:
        resp = {'id':101,'val':500}
        return resp
    except:
        print('Error!!!')
    finally:
        log = {'start_time':111111,'file':test}
        DB[log_coln].update_one({"_id": 101}, {"$set": log}, upsert=True)

Here resp is returned to client and in finally block log data is loaded into database. The log data loading taking time which is impacting the SLA. I want to implement Async call / fire and forgot call for the functionalities in finally block.
I have tried asyncio and threading, but I am unable to get return value from function. I want to implement fire and forgot call with minimal code change.


text:
Q: The kitchen sink of HTML pages I'm designing web themes and I'd like to put together a "kitchen sink" HTML page which contains the most common design elements of a web page. It's great to show theme features but also helps me develop CSS for everything on the page without missing anything.
There's the obvious list of HTML tags which is a great starting point:

*

*Headings
 through

*Paragraphs

* and  in paragraphs, headings, etc

*Floated images with optional caption

*Lists
 and
, short (one-liner) and long (multi-line) list items

*Definition lists
,
,

*Horizontal rules
 with optional Back To Top link

*Tables with
 and ,
 with alternate row highlighting,
 with pagination and/or notes

*Feature comparison tables (tick/cross or dash)

*
 for long/referenced quotes

*<q> for short quotes

*Forms with text, radio, checkbox, textarea, select and buttons, and support for left/right labels, default values, hint text and validation error highlighting

*Code samples with syntax highlighting and raw output/clipboard

Then additional styling of stuff:

*

*Breadcrumbs

*Dropcap on paragraphs

*Floated extract of text, pullquotes

*Columns

*Block inset - background colour, border, etc

*Background highlighting of text

*Hover-activated links (dotted underline)

*Tooltips

And then specific applications of a block of HTML:

*

*Table of Contents for document/wiki

*Homepage feature slider/box

*File download

*Contact information, styled
 for address, phone, email, etc

*Gallery of images

*Calendar (year, month, week, day views)

*Embedded video

*Pricing table

*Maps

*WYSIYG editor

*Blog post summary, blog post

*Forum list of posts, form post

*"Add to cart" style block

*Customer review with star rating

*Out-of-page user alerts (SO style)

*In-page feedback - error, success, etc

*User profile block - avatar, username, stats

Page-related actions:

*

*Send to a friend

*Tweet, Like/Share, +1, Flattr

*Alternative formats RSS/XML/CSV etc

*Print

jQuery UI elements (is this re-inventing the wheel?):

*

*Accordion

*Tabbed box

*Dialog

*Single button

*Multiple choice button

*Slider

*Datepicker

*Progress bar

*Autocomplete

*Overlay/shadow

*Framework icons

Is there anything I'm missing? I'd like to include as many common elements as possible. If you buy themes do you find they miss something important, or contain something awesome that I haven't thought of?
Hopefully this will turn into a community wiki question

A: Some really useful things that you always spend time working on:

*

*Menus (Horizontal, Vertical, Expandable, etc..)

*Form verification (This is if you are also including javascript)

*Tooltips

*WYSIYG editor

*Maps

Hope it helps

A: How about common UI widgets like:

*

*Calendar

*Tabs

Or boxes:

*

*Rounded corners

And maybe:

*

*Feedback / things that catch attention (e.g. your X have been updated)

*em / strong

I think the tricky one is making sure you catch all the combinations such as em in a h2 (a simple example but that sort of thing).
The jquery-ui theme roller page might give you some ideas.

A: Existing kitchen sinks around the web:

*

*HTML-ipsum

*jQuery UI theme roller

*Paul Randall's kitchen sink

*Themes on ThemeForest often have good examples

A: Sounds awesome!
You could go crazy and include a web chat/IM widget.  Having just styled one, it seems to be a unique problem.


text:
Q: Каким образом в списке List найти повторяющиеся значения? Метод Distinct не годится ибо он удаляет не уникальные значения, LINQ тоже не пригоден так как было требование его не использовать.
A: Попробуйте всё же LINQ.
list.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key)

Требование не использовать LINQ игнорируйте, скажите, что разработчику виднее.

Самое быстрое решение (O(n)), было бы, наверное, пройтись по списку, записывая по пути элементы в HashSet.
A: Пройдите в цикле по всем элементам списка.
Для каждого элемента списка пройдитесь по остальным элементам списка, найдёте равный данному - удаляйте (можно сохранить индексы таких элементов и потом все разом удалить).
Прикольно будет добавить сюда многопоточность для многоядерных ЦП (которой в LINQ, вероятно, нет).
P.S. Требование не использовать LINQ оправданно.
Согласитесь, сделать как я написал - сложнее, а значит, полезнее для развития.
Плюс LINQ нет в .NET 3.0 и ниже